Jquery – How to set ‘body’ background in JQuery

cssdomjquery

I try to change the 'body' element background when a button is clicked, however nothing happens and no error is returned in Chrome browser console. I have tried multiple methods. For method 1, I have also tried replacing background with background-image. In the CSS code, a background image is already assigned.

JS code:

$('.btn').click(function(){
    //method1:
    $('body').css({backgroundImage: 'url:(https://working-url)'});
    //method2:
    $('body').css('background', 'url:(https://working-url)');
}

CSS code refering to 'body':

html,
body {
 margin: 0;
 padding: 0;
}

body {
 color: #F0F8FF ;
 background: url("back.jpg") no-repeat center center fixed;
 background-size: cover;
 font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, sans-serif;

}

Best Answer

You'll have to be careful when assigning the background is CSS with shorthand, which means assigning all the background properties in one line. If you assign another background later, it will override ALL of those properties. Meaning, since you are just adding the image, the no-repeat center center fixed will not transfer to the new background. You need to set those properties separately and change only background-image.

As for the jQuery you want to target like this:

$('body').css('background-image', 'url(https://working-url)');

or

$('body').css({'background-image': 'url(https://working-url)'});