I 'm currently building a full background image layout and I want to change the image based on which page the user is visiting. To get to the point: I need to change a images attribute when the user clickes on a link. This is how far I got:
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
});
});
<a href="" title="Switch" class="menulink">switch me</a>
<img src="img/picture2.jpg" id="bg" />
Thank you, probably easy stuff, but over my head!
The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS. I would name the images starting with bw_ and clr_ and just use JS to swap between them.
To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.
With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method. This is demonstrated below: jQuery.
Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
Interesting question on the differences between prevent default and return false.
In this case, return false will work just fine because the event doesn't need to be propagated.
You need to use preventDefault()
to make it so the link does not go through when u click on it:
fiddle: http://jsfiddle.net/maniator/Sevdm/
$(function() {
$('.menulink').click(function(e){
e.preventDefault();
$("#bg").attr('src',"img/picture1.jpg");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With