With jQuery, you can change the background-image
CSS property by using the css()
method. The method is used to set or retrieve one CSS property value.
The syntax of css()
method is as follows:
css("propertyName", "value");
You can set the background-image
property, to any element you’ve selected using jQuery selector method:
$('.imgEl').css('background-image', 'url(./assets/image.png)');
Finally, you can also set other CSS properties to make the background looks good on your page, such as background-repeat
, background-position
, and height
properties as follows:
$('.imgEl').css('background-image', 'url(./assets/image.png)');
$('.imgEl').css('background-repeat', 'no-repeat'); // do not repeat the image
$('.imgEl').css('background-position', 'center'); // center the image
$('.imgEl').css('height', '500px'); // sets the height
And that’s how you can change background image using jQuery 😉