Search code examples
jquerytoggleimagesrc

Replace img src from elements attribute


If I have this html on my page

<img src="samesrc" class="commentimg" name="differentimg1"/>

How onclick can I toggle the src= of <img> with the name= attribute, so when I click the <img> the src becomes differentimg1, and another class is applied

<img src="differentimg1" class="commentimg commentimgresize" name="differentimg1"/>

and then when clicked again the html source is returned to original ie

<img src="samesrc" class="commentimg" name="differentimg1"/>

This should be applied to all images but the src when toggled should correspond the element name= value.

I HAVE TRIED http://jsfiddle.net/yusaf/zy5j8/25/

$('.imgreplace').each(function(){
$('.imgreplace').click(function(){
    var replacesrc = $(".commentimg").attr("name");
    $('.commentimg').attr("src", "+replacesrc+");
    $('.commentimg').toggleClass('commentimgresize')
})
});

Solution

  • This works

    $('.commentimg').click(function(){
        var a = $(this).attr('src');
        var b = $(this).attr('name');
        $(this).attr('src',b).attr('name', a);
    });
    

    Example: http://jsfiddle.net/jasongennaro/zy5j8/26/

    Explanation: Onclick grab the src and name attributes, reverse them.