Devilix
Devilix

Reputation: 323

How to show a div after 5 right-clicks

I would like to make something that comes up after user right-clicked many times (5 clicks, for example). Then a div should be shown.

Right now I'm using this code:

document.oncontextmenu = function() { 
    $("#red").fadeIn(500).show().delay(3000).fadeOut(800);
    return false;
};

This works fine, but it misess five attempts like I have said in my request.

UPDATE: Here the right code!

document.oncontextmenu = (function() {
var counter = 0;
return function() { 
    counter++;
    if (counter == 5) {
        $("#red").fadeIn(500).show().delay(3000).fadeOut(800, function() {
        counter = 0;
    });
    }
    return false;
};

})();

Thanks to @James Thorpe

Upvotes: 2

Views: 119

Answers (1)

James Thorpe
James Thorpe

Reputation: 32202

Use what you have, but wrap it in a closure that has a variable to count how many times the inner function has been executed:

document.oncontextmenu = (function() {
    var counter = 0;
    return function() { 
        counter++;
        if (counter == 5)
            $("#red").fadeIn(500).show().delay(3000).fadeOut(800);
        return false;
    };
})();

Note that the outer function is invoked immediately to create the variable, then returns the inner function as the event handler. By using such a closure, we keep everything related to the event (including the counter variable) within the local scope without leaking anything to the global scope.

If you want to be able to invoke the div multiple times, you just need to reset the counter each time it's shown. The best place to do that is in the callback function supplied to the fadeOut function, so that the count only begins again once the div has been hidden.

if (counter == 5) {
    $("#red").fadeIn(500).show().delay(3000).fadeOut(800, function() {
        counter = 0;
    });
}

Upvotes: 5

Related Questions