Remove an event handler after 3 clicks

0

I have this code, which I need the click event to be removed after x attempts.

Example: link

var qtdadeCliques = 0;
var eventCon = function(evento){
    qtdadeCliques++;
    if (qtdadeCliques >= 3) {
        alert("You clicked the div 'red'!");
       $(this).off(evento);
    }
};
$("#div3").on("click", eventCon);
    
asked by anonymous 13.01.2015 / 12:48

3 answers

3

Some details are missing for this to work:

method .off() is misconfigured:

The method can be used without parameters but it will remove all the event handlers added with .on() , half dangerous / unpredictable. It is best to define which type of event (and not the event object itself as you have), and now to be safe to pass the function that you want to undo. That is:

$(this).off("click", eventCon);
// ou somente $(this).off(); que desaconselho

Another problem already mentioned is the issue of the code being run before the DOM is ready. This solves wrapper $("#div3").on("click", eventCon); with a jQuery domready function. Example:

$(function () {
    // código a correr aqui...
});

So the whole code would be:

$(function () {
    $("#div3").on("click", eventCon);
});

var qtdadeCliques = 0;
var eventCon = function (evento) {
    qtdadeCliques++;
    if (qtdadeCliques >= 3) {
        alert('Chegou a 3!');
        $(this).off('click', eventCon);
    }
};

jsFiddle: link

    
13.01.2015 / 18:53
1

Place the .on () inside the Jquery Ready.

 (function($) {
    $(function() { 
      $("#div3").on("click", eventCon); 
    }); 
  })(jQuery);
    
13.01.2015 / 15:12
0

The section below has a slightly different approach than the others mentioned, using the design pattern IIFE (Immediately-Invoked Function Expression) . The idea is to avoid polluting the global context (window) with unnecessary variables. I recommend reading the jQuery API where you explain the use of the off method and the #

(function($){
    $(function(){
        $(document.documentElement).on("click", (function(){
            var clicksCount = 0;

            return function clickFn(event) {
                if (++clicksCount < 3) return;

                alert("Three!");
                $(this).off("click", clickFn);
            };
        }()));
    });
})(jQuery);

The example can be checked in JSFiddle

    
14.01.2015 / 23:29