Search code examples
javascriptjquerytogglesrcattr

Toggle images on click using jQuery


I have two images which I need to toggle on clicking on the image.

    <img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' 
data-src='images/prof_arrow1.png' />

When the user click the image the src should get the value of data-swap and when you click again the src should change to data-src. This should keep happening just like a toggle. Any help appreciated.

$("#arrowRotate").click(function() {
    var swapImage = $("#arrowGrey").attr("data-swap");
    $("#arrowGrey").attr({
        'src': swapImage,
        id: 'arrowOrange'
    });
});  

This is where I have got so far.


Solution

  • Based on my understanding from your question, Hope this is the one you expect,

    $("#arrowRotate").click(function() { 
          var _this = $(this);
          var current = _this.attr("src");
          var swap = _this.attr("data-swap");     
         _this.attr('src', swap).attr("data-swap",current);   
    });  
    

    DEMO Fiddle