Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting div background image using JQuery

Tags:

jquery

css

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.

like image 221
rogerp Avatar asked Oct 23 '09 08:10

rogerp


People also ask

How to change background jQuery?

You can change the <body> background color by first selecting the element using jQuery selector $() and chain it with the css() method as follows: $("body"). css("background-color","blue"); The code above will change the background color from yellow to blue .

How to set body background image in jQuery?

To change the background image using jQuery, you can use the jQuery CSS() method. For this, the whole property value is specified using the url() functional notation. Approach: Suppose we have an image URL stored in a variable and then use css() method to change the value of background image.

How can change background image of button click in HTML?

The default button in HTML can be changed to an image using CSS. The required button is selected using the respective CSS selector. The background property can then be set to include a background image and change the image type as required. The border of the button can also be removed to show only the image itself.

How do I put multiple images as my background in CSS?

CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.


2 Answers

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')"); 
like image 159
Victor Avatar answered Sep 30 '22 16:09

Victor


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.

like image 44
djdd87 Avatar answered Sep 30 '22 16:09

djdd87