I´m new to jQuery and I´m intressred in showing different background image on click event. Is there any easy way?
Asked
Active
Viewed 2.3k times
8 Answers
4
1.7+
$("#id").on("click", function () {
$(this).css("background-image", "url(/url/to/background/image.jpg)");
});
< 1.7
$("#id").bind("click", function () {
$(this).css("background-image", "url(/url/to/background/image.jpg)");
});

Ash Clarke
- 4,807
- 1
- 37
- 48
-
1I dont see any use of `bind()` and `.on()` on this case. Unless we start like `may be OP wants to do this and that`. – Starx Mar 20 '12 at 11:27
-
2
-
Thanx! But the image disappears then the page loads (wordpress)... I tried with "return false", but the buttn get inactive after the first click then... – wpdesign May 10 '12 at 15:15
0
I had this same issue and found a solution using this - https://github.com/rewish/jquery-bgswitcher#readme

Bizzaro
- 65
- 2
- 12
0
Its as simple as this
$("#mylink").click(function() {
// ^ Attach a function on click event of an element with id="mylink"
//Change the css of a element with id="myDiv"
$("#myDiv").css("backgroundImage", "url(newimage.jpg)");
// Note ^: In jQuery, the parameters with "-" as define that way
// But of course .css() supports "-" also, but make a habit of doing in camel-case
});
Demo

Starx
- 77,474
- 47
- 185
- 261
0
$("#your_element").click(function () {
$("#your_element").css("background-image", "url(" + image_url + ")");
}
Replace #your_element
with the appropriate selector, and image_url
with a valid url and you're golden.

Drakekin
- 1,341
- 1
- 11
- 23
0
$("#divBg").css("background-image", "url(http://www.androidgamespro.com/static/pic7/micky_tap_tap-jazz_jackrabbit-1_010-icon0.png)");
Here is the sample : http://jsfiddle.net/aGAha/2/

Shyju
- 214,206
- 104
- 411
- 497
0
Reading your Question and knowing that you are new to jQuery, i would like to explain the answer in little more details.
Everybody has given the answers correct in all possible ways.
firstly to access any element on the page you need to select the element using jQuery selectors
all jQuery methods are accessible inside the document.ready function
$(document).ready(function() {
//this represents window.load in javascript.
//now to select the element suppose you have anchor tag <a> with id=clickme
$("#clickme").click(function() {
//select the element whose background image you want to change. suppose with id=imgBack
$("#imgBack").css({'background-image':'url(newimage.jpg)'});
// Note image can be of any format (.png, .jpg, .gif, etc).
// this way you can change the image.
})
});
for more details in selecting the element with class name you can refer jQuery website.

Murtaza
- 3,045
- 2
- 25
- 39
0
$("#mylink").click(function() {
$('body').css({'background-image':'url(new_image.jpg)'});
});
<div id="mylink">Click me</a>

sujal
- 1,058
- 3
- 18
- 29