How to format my jQuery

I have managed to setup a background image on hover of another element using this great forum! As I am new to jQuery and javascript, I am struggling to format adding additional effects on hover. e.g. I don't just want to use an append on the background-image I also want to do a background-size:cover; append and a transition: all 0.33s ease. How would I go about adding this to the current syntax?

$(document).ready(function() {

    //Preload
    $('<img/>').hide().attr('src', '../img/background-experience.jpg').load(function(){
        $('body').append($(this));
    });

    $('.btn').hover(function() {
        $('body').css('background-image', 'url("../img/background-experience.jpg")');
    }, function() {
        $('body').css('background', '');
    });
});

EDIT: FOLLOWING HELP FROM NOEL

Added using custom class which may be a better solution now having issues with the transition this is my scss code.

body {
  background: $black;
  color: $white;
  font-family: $default-font;
  font-weight: 600;
  transition: all 0.33s ease;
}

.my-custom-class {
  background-image:url('https://yt3.ggpht.com/-V92UP8yaNyQ/AAAAAAAAAAI/AAAAAAAAAAA/zOYDMx8Qk3c/s900-c-k-no-mo-rj-c0xffffff/photo.jpg');
  background-size:cover;
}

Answers 1

  • You can just put everything in a css class that you can add to your body on hover of the button. This requires two things: (1) defining the css rule; then (2) adding, removing this on hover.

    Below is a sample code to show this in action. Hope this helps!

    $('.btn').hover(function() {
            $('body').addClass('my-custom-class');
        }, function() {
            $('body').removeClass('my-custom-class');
        });
    .my-custom-class {
      background-image:url('https://yt3.ggpht.com/-V92UP8yaNyQ/AAAAAAAAAAI/AAAAAAAAAAA/zOYDMx8Qk3c/s900-c-k-no-mo-rj-c0xffffff/photo.jpg');
      
      background-size:cover;
    }
    
    body {
      background-image:url('https://www.petdrugsonline.co.uk/images/page-headers/cats-master-header');
      background-size:cover;
    transition: all 0.33s ease;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button class="btn">My button</button>


Related Articles