TL;DR version (a fiddle for you if you don't like to read explanations).
Problem
The problem with your code is that you attach 2 different event handlers to the same click event and they bot run on every click. If I merge your event handlers, the problem becomes more evident:
$("#clickdiv").click(function () {
$("#clickdiv").animate({'width': 2129},800);
$(this).animate({'width': 36},800);
});
On every click you animate to 2129 width and animate back to 36 width. This is clearly not what you want to do.
You need to somehow check the current state (is the <div>
currently wide or narrow?), and do something accordingly.
Solution
An elegant way of toggling the style of something with jQuery is .toggleClass()
.
This checks if a class on an element exists, and adds and removes it accordingly.
First you have to set up the css styles, for example:
#clickdiv {
width: 36px;
}
#clickdiv.longer {
width: 2129px;
}
You can then call:
$('#clickdiv').click(function () {
$(this).toggleClass('longer');
});
Of course adding a class does not animate by default, but this can be solved by enabling CSS3 transitions:
#clickdiv {
transition: all ease-in-out .5s;
}
This solution is very clean. Minimal plumbing code and CSS3 transitions are nice to look at.
As an alternative to CSS3, you could use the jQuery UI .toggleClass()
, which has parameters to enable animation. This requires you to also include jQuery UI, and modify the JS code like this:
$('#clickdiv').on('click', function () {
$('#clickdiv').toggleClass('longer', 500);
});
Notice the new last parameter of toggleClass()
.
The CSS transitions can be tested here.
The jQuery UI version can be tested here.