Reputation: 87
My code makes elements fade in consecutively on repeat clicks of a 'target' element. Is there an alternative ('better') way of achieving this than to place the next click event as the callback of the preceding one?
$(document).ready(function () {
$(".preHide").hide();
$("#target").click(function () {
$("#fade1").fadeIn(2000, function () {
$("#target").click(function () {
$("#fade2").fadeIn(2000, function () {
$("#target").click(function () {
$("#fade3").fadeIn(2000, function () {
$("#target").click(function () {
$("#fade4").fadeIn(2000, function () {
$("#target, .targetWrapper").fadeOut();
$("#fade5").fadeIn();
});
});
});
});
});
});
});
});
});
This is easy to read but seems unnecessarily verbose.
Upvotes: 1
Views: 107
Reputation: 193261
Right now you bind 4 click events, which is not ideal of course. What about this simplified approach?
var clicks = 0;
$("#target").click(function() {
var callback = ++clicks < 5 ? $.noop : function() {
$("#target, .targetWrapper").fadeOut();
$(this).fadeIn();
};
$("#fade" + clicks).fadeIn(2000, callback);
});
Upvotes: 2