Faiyet
Faiyet

Reputation: 5471

Toggling between image

I have two images with which I am using in an anchor tag. I am using jquery toggle on the click event of the anchor tag to swap between images.

    $(document).ready(function(){
        $('#registrationForm').hide();
        $('#callform').append("<a id='formlink'>IMAGE 1</a>");
        $("#formlink").click(function(){
            $('#registrationForm').toggle(function(){
                $('#formlink').empty().append(IMAGE 2);
            });
        });
    });

This works fine the first time around, however i want to toggle between the two images whenever the other is clicked. Any ideas ?

Upvotes: 1

Views: 478

Answers (5)

Dexter
Dexter

Reputation: 18452

I'd suggest adding both images initially, but hiding the second image. You can then toggle both images each time the link is clicked without needing to track the state of the images:

$(document).ready(function(){
    $('#callform').append("<a id='formlink1' class='formlink'>IMAGE 1</a>");
    $('#callform').append("<a id='formlink2' class='formlink' style='display: none;'>IMAGE 2</a>");
    $(".formlink").click( function(){
        $('#formlink1').toggle();
        $('#formlink2').toggle();
    });
});

Upvotes: 1

mcgrailm
mcgrailm

Reputation: 17640

this is how I toggle an image

 $('.accordion').live('click',function() {
    if($(this).attr("src").indexOf('closed') == -1){
        $(this).attr("src",'img/accordionclosed.gif');
    }else{
        $(this).("src",'img/accordionopen.gif');
    }
 });

hth

Upvotes: 0

foreline
foreline

Reputation: 3821

$(document).ready(function(){
    var i = 0;
    $('#registrationForm').hide();
    $('#callform').append("<a id='formlink'>IMAGE 1</a>");
    $("#formlink").click(function(){
        $('#registrationForm').toggle(function(){
            if ( ++i % 2 ) {
                $('#formlink').empty().append(IMAGE 2);
            } else {
                $('#formlink').empty().append(IMAGE 1);
            }
        });
    });
});

Upvotes: 0

Dancrumb
Dancrumb

Reputation: 27539

Your code is designed to append 'IMAGE 2' after the toggle is complete, and nothing else.

You probably want something like:

$("#formlink").click(function(){
    $('#registrationForm').toggle(function(){    
        var imageToShow = $(this).css('display') == 'none')?'IMAGE 1':'IMAGE 2';
        $('#formlink').empty().append(imageToShow);
    });
});

Upvotes: 1

Ignacio
Ignacio

Reputation: 8035

You could just setup a flag when you change to IMAGE1.

selected_image = 'image1'
if(selected_image == 'image1')
    toggle to image 2
else
    toggle to image 1

Upvotes: 1

Related Questions