Cohagen
Cohagen

Reputation: 87

Alternative to repetative JQuery callbacks?

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

Answers (1)

dfsq
dfsq

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);
});

Demo: http://jsfiddle.net/94vmt4fk/1/

Upvotes: 2

Related Questions