For those looking for a shorter but yet working version you could do this:
$('a#trigger').on('click', function(e) {
e.preventDefault();
var w = ($('div#test').width() == 300 ? 100 : 300);
$('div#test').animate({width:w},150);
});
The shortest version:
$('a#trigger').on('click', function(e) {
e.preventDefault();
$('div#test').animate({width:($('div#test').width() == 300 ? 100 : 300)},150);
});
On a function:
function toggleWidth(target, start, end, duration) {
var w = ($(target).width() == start ? end : start);
$(target).animate({width:w},duration);
return w;
}
Usage:
$('a#trigger').on('click', function(e) {
e.preventDefault();
toggleWidth($("div#test"), 300, 100, 150);
});
Finally on a JQuery.fn.extend function:
jQuery.fn.extend({
toggleWidth: function(start, end, duration) {
var w = ($(this).width() == start ? end : start);
$(this).animate({width:w},duration);
return w;
}
});
Usage:
$('a#trigger').on('click', function(e) {
e.preventDefault();
$("div#test").toggleWidth(300, 100, 150);
});