tags:

views:

135

answers:

3

Hello,

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 does not get displayed. How to fix this ?

Thank You.

+1  A: 

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

Also, can you navigate to the image through your browser correctly? I.e. yourdomain/images/pic.jpg?

Edit: Also, have you set a width and height for the div? The div will not auto-resize for a background image.

GenericTypeTea
Should work with 'background' or 'background-image'. Checking the image, by navigating to it, is always a good idea.
belugabob
belugabob
That's why I asked the question.
GenericTypeTea
+1  A: 

maybe it also works 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')");
Victor
Should work with 'background' or 'background-image'. Shouldn't be necessary to use quotes.
belugabob
It shouldn't be, but it seems it is for browsers that are not IE. (+1) For Saving me hours of pain.
Byron Cobb
A: 

This is probably down to relative path issues.

What is the path (i.e the URL that appears in the browser navigation bar) for the page that contains the code that you posted? Where is this in relation to the images directory?

managing this can be a bit of a nightmare, especially if you've included a javascript file into multiple pages, that are at different levels within a URL hierarchy.

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

belugabob