pab
pab

Reputation: 973

Switch images with jQuery

I found this which is what I need but I need to be able to switch back to the first original image on the last click.

So I have the 1st image, I click to change it, then I need to click it again to reveal the first image.

Here is a link to a fiddle http://jsfiddle.net/maniator/Sevdm/

Upvotes: 0

Views: 3175

Answers (3)

Alnitak
Alnitak

Reputation: 339786

You can take advantage of the fact that it's possible to store arbitrary properties on JS elements, e.g:

$(function() {
    $('.menulink').on('click', function() {
        var img = document.getElementById('bg');
        if (img.old) {  // restore the original
            img.src = img.old;
            delete img.old;
        } else {        // store original, and change
            img.old = img.src;
            img.src = 'http://.../';
        }
        return false;
     });
 });

Upvotes: 2

Darek Rossman
Darek Rossman

Reputation: 1323

Another solution, this let's you keep all your images in the html and add more as needed:

<a href="" title="Switch" class="menulink">switch me</a>
<img src="http://placehold.it/333/3ef/img/picture1.jpg"/>
<img src="http://placehold.it/333/fe3/img/picture2.jpg"/>​

And the javascript (this isn't very scalable, but it's a decent starting point):

$(function() {
    var currentImage = 0;
    $('img').not(':first').hide(0);

    $('.menulink').click(function(e){
        e.preventDefault();
        $('img').eq(currentImage).hide(0);
        currentImage = currentImage >= $('img').length-1 ? 0 : currentImage+1
        $('img').eq(currentImage).show(0);  
    });
});

See the fiddle: http://jsfiddle.net/e95K5/

Upvotes: 0

zessx
zessx

Reputation: 68790

You can store the old src value in a variable :

$(function() {
    var old_img = '';
     $('.menulink').click(function(e){
        e.preventDefault();
         if(old_img == '') {
            old_img = $("#bg").attr('src');                   
            $("#bg").attr('src',"http://placehold.it/333/3ef/img/picture1.jpg");
         } else {
             $("#bg").attr('src', old_img );
             old_img = '';      
         }
     });
});

jsFiddle

Upvotes: 2

Related Questions