I have this animation which I'd like to trigger upon click of a link. When I run the animations separately, it's working fine. But using the jquery toggle()
, it doesn't work anymore. Can anyone easily see why?
Without toggle()
it works (ran each separately):
$('#sign-in-fx').click(function() {
$('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart');
//$('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart');
});
With toggle()
nothing happens:
$('#sign-in-fx').click(function() {
$('.login_form').toggle(
function() {
$(this).animate({ width: '273' }, 'slow', 'easeInOutQuart')
},
function() {
$(this).animate({ width: '1' }, 'slow', 'easeInOutQuart')
}
);
});
This is similar to jQuery toggle animation
Now I think this is what you originally wanted to do:
$('#sign-in-fx').toggle(
function() {
$('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart')
},
function() {
$('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart')
}
);
You were calling toggle()
on the element to animate, but it has to be called on the element that will receive the click
event.
toggle()
used the way you are using it, is deprecated!
Use a flag, and toggle the animated width directly, like so:
var flag = true;
$('#sign-in-fx').on('click', function() {
$('.login_form').stop(true, true)
.animate({ width: flag?'273':'1' }, 'slow', 'easeInOutQuart');
flag=!flag;
});
FIDDLE
Or if you don't like globals, you can always use data() :
$('#sign-in-fx').on('click', function() {
var flag = $('.login_form').data('flag')!=undefined?$('.login_form').data('flag'):true;
$('.login_form').stop(true, true)
.animate({ width: flag?'273':'1' }, 'slow', 'easeInOutQuart')
.data('flag', !flag);
});
FIDDLE
I think you could also do as follows:
$('#sign-in-fx').click(function() {
if (! $('.login_form').is(':animated')) { //if no animation running
if ($('.login_form').width() > 1) {
$('.login_form').animate({ width: '1' }, 'slow', 'easeInOutQuart');
} else {
$('.login_form').animate({ width: '273' }, 'slow', 'easeInOutQuart');
}
}
});
Are you sure it is done on document.ready
? Your code seems fine.
$(function () {
$('.login_form').toggle(
function() {
$(this).animate({ width: '273' }, 'slow', 'easeInOutQuart')
},
function() {
$(this).animate({ width: '1' }, 'slow', 'easeInOutQuart')
}
);
});