Reputation: 37
I´m new to jQuery and I´m intressred in showing different background image on click event. Is there any easy way?
Upvotes: 0
Views: 23524
Reputation: 65
I had this same issue and found a solution using this - https://github.com/rewish/jquery-bgswitcher#readme
Upvotes: 0
Reputation: 1050
$("#mylink").click(function() {
$('body').css({'background-image':'url(new_image.jpg)'});
});
<div id="mylink">Click me</a>
Upvotes: 0
Reputation: 3065
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.
Upvotes: 0
Reputation: 78981
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
});
Upvotes: 0
Reputation: 218732
$("#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/
Upvotes: 0
Reputation: 1348
$("#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.
Upvotes: 0
Reputation: 4887
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)");
});
Upvotes: 4