Search code examples
jqueryimagefunctionhref

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!


Solution

  • 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.