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(fu开发者_开发百科nction(){
$('#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 ?
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();
});
});
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
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);
});
});
$(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);
}
});
});
});
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
精彩评论