Customize div background image with jQuery

Im using jQuery to set the background image of a div as follows:

$(document).ready(function() { $('#pic').css("background","url(images/pic.jpg)"); }); 

But the image is not displayed. How to fix it?

Thanks.

+6
jquery css
source share
3 answers

it may also work with background , but I always use

 background-image 

And also I always put quotes around the path

 $('#pic').css("background-image","url('images/pic.jpg')"); 
+8
source share

This should work, but have you tried using "background-image" instead of "background"?

Also, can you correctly navigate to the image through your browser? That is, domain_name / image / pic.jpg?

Edit : Also, did you set the width and height for the div? Div will not automatically resize the background image.

+1
source share

This is likely due to relative path issues.

What is the path (i.e. the URL displayed in the browser navigation bar) for the page containing the code you posted? Where does this apply to the image catalog?

Managing this can be a bit of a nightmare, especially if you included the javascript file on several pages that are at different levels of the URL hierarchy.

The best way to handle this is to define the class in the css file, make the image URL relative to the location of the css file itself, and then simply apply the class to your div, instead of setting individual style attributes.

0
source share

All Articles