Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change image source on click with jQuery?

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!

like image 723
Johannes Kärnstam Avatar asked Apr 06 '11 18:04

Johannes Kärnstam


People also ask

How do I change my Onclick picture?

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.

How do I change the source of a picture?

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.

How can add image in HTML using jQuery?

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.

How add src attribute in 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.


2 Answers

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.

like image 141
Hugo Migneron Avatar answered Oct 14 '22 05:10

Hugo Migneron


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");
 });
});
like image 25
Naftali Avatar answered Oct 14 '22 05:10

Naftali