Search code examples
jqueryhtmlimagetogglesrc

How can I toggle an img's src value between two images?


I want to toggle an img's src value so that the first time I click it, it changes to another image, and the second time, it reverts back to the original image.

The img is defined in HTML this way:

<img id="imgPostTravel" name="imgPostTravel" src="/_layouts/images/TravelFormHelp/posttravelpdf.png" alt="post Travel image" height="275" width="350">

I can change the first image to the second with this jQuery:

$('#imgPostTravelTopRight').click(function () {
    $('#imgPostTravelTopRight').attr('src', '/_layouts/images/TravelFormHelp/posttravelpdf.png');
});

I tried this to toggle the img src:

$('#imgPostTravelTopRight').toggle(function () {
    $('#imgPostTravelTopRight').attr('src', '/_layouts/images/TravelFormHelp/posttravelpdf.png');
}, function () {
    $('#imgPostTravelTopRight').attr('src', '/_layouts/images/TravelFormHelp/2_PTE_Top_Right_Jig.png');
});

...but it doesn't work. I read that "toggle" was deprecated, and I tried this:

if $(('#imgPostTravelTopRight').attr('src') == '/_layouts/images/TravelFormHelp/posttravelpdf.png') {
    $('#imgPostTravelTopRight').attr('src', '/_layouts/images/TravelFormHelp/2_PTE_Top_Right_Jig.png');
} else {
    $('#imgPostTravelTopRight').attr('src', '/_layouts/images/TravelFormHelp/posttravelpdf.png');
}

...but that works even less well - in fact, it smashes "everything" all to smithereens - even code that needed to run prior to that doesn't run now...


Solution

  • The reason that your last attempt doesn't work is because you have a syntax error:

    if $(('#imgPostTravelTopRight').attr('src') == '/_layouts/images/TravelFormHelp/posttravelpdf.png') {
    // ^ This should be ($( instead of $((
    

    Another solution is to use the .attr(name, function) overload:

    $('#imgPostTravelTopRight').attr("src", function(index, val) {
        return val == '/_layouts/images/TravelFormHelp/posttravelpdf.png' ?
           '/_layouts/images/TravelFormHelp/2_PTE_Top_Right_Jig.png' :
           '/_layouts/images/TravelFormHelp/posttravelpdf.png'
    });