Reputation: 165
This is a pretty straight-forward problem. I basically have a div block on a page that, when clicked, grows in size, and when clicked again returns back to what it was. My problem is that it just doesn't seem to work at all. Plus, I'm sure there is a much cleaner way to toggle between two animation states than an if statement like this, but I'm not sure how exactly to go about doing that.
$(document).ready(function(){
var toggle = 0;
$(".login").click(function(){
if($toggle == 0){
$(this).animate({
height: '200',
}, 500, function(){
});
$toggle = 1;
}
else if($toggle == 1){
$(this).animate({
height: '100',
}, 500, function(){
});
$toggle = 0;
}
});
});
Corresponding html code is simply
<div class="login">Click Me</div>
Let me know if anything else is needed.
Upvotes: 1
Views: 14676
Reputation: 1
I want to defend your toggle solution, it isn't incorrect.
In some case only this way of code will work correct, while .toggle()
will do some weird things.
Only instead of if($toggle == 0){...
you need use if ( toggle === 0 ){
Upvotes: 0
Reputation: 318162
var H=H==200?100:200;
$(".login").on('click', function(){
$(this).animate({height: H}, 500, function() {H=H==200?100:200;});
});
Upvotes: 0
Reputation: 1507
Two problems I see. One is the scope of your toggle variable. The other is the common after the single attribute in your animation attribute list. Try this:
$(document).ready(function(){
$(".login").click(function(){
if($(this).hasClass('expanded')){
$(this)
.removeClass('expanded')
.stop()
.animate({height: '100px'}, 500)
;
}
else{
$(this)
.addClass('expanded')
.stop()
.animate({height: '200px'}, 500)
;
}
});
});
Upvotes: 0
Reputation: 707158
Your code isn't working because you have used toggle
in one place and $toggle
in another.
But, this can be done more simply like this:
$(document).ready(function(){
$(".login").toggle(function() {
$(this).animate({height: '200'});
}, function() {
$(this).animate({height: '100'});
});
});
Working demo here: http://jsfiddle.net/jfriend00/5Wu6m/
When given a list of functions as arguments, the .toggle(fn1, fn2)
method will alternate between the functions given starting with the first one. This automatically keeps track of the toggle state for you - you don't have to do that.
jQuery doc is here. There are multiple forms of .toggle() depending upon the arguments used so you don't always find the right one when searching the jQuery doc.
Upvotes: 10
Reputation: 78630
Notice the difference between
var toggle = 0;
and
if($toggle == 0){
You define a variable named toggle
, then use it as $toggle
.
Upvotes: 1