6

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.

3 Answers 3

9

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')"); 
Sign up to request clarification or add additional context in comments.

2 Comments

Should work with 'background' or 'background-image'. Shouldn't be necessary to use quotes.
It shouldn't be, but it seems it is for browsers that are not IE. (+1) For Saving me hours of pain.
1

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.

3 Comments

Should work with 'background' or 'background-image'. Checking the image, by navigating to it, is always a good idea.
Good point about the width & height but, I assume, there is probably some other markup within the div that gives it height & width).
That's why I asked the question.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.