Adding background image using jQuery

A guide on adding background image using jQuery

Posted on May 12, 2021

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 😉

Related articles:

Level up your programming skills

I'm sending out an email once every Wednesday with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.