0

Related: Jquery timeout for doubleclick

Given this code:

function handleClick() {
  var div = $(this);
  var original = $(this).html();
  div.html("Tap again");
  $(".onlyfire").addClass("fire").off("click");
  $(".fire").one("click", function(fire) {
    alert("this should not be showing once the text is changed back to original");
    $(this).off("click")
  });
  setTimeout(function() {
    $(div).html(original);
    $(".onlyfire").removeClass("fire").click(handleClick);
  }, 2000);
}

function onlyfire() {
  $(".onlyfire").click(handleClick);
};
onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="onlyfire">
  Do Something
</div>

the fire className is removed from .onlyfire element following 2000ms, where expected result is for click event which was attached to .fire would also be rendered inapplicable, as there would not be a .fire element within document.

However, as pointed out @120382833 at comment

Click on Do something, wait for 2 seconds until the Do Something is back, Click again and it will show the alert.. And it shouldn't.. It should display tap again and only if you click in first 2 seconds the alert should show up.

To reproduce

  1. Inspect .onlyfire element at console;
  2. click .onlyfire element;
  3. do nothing for two seconds;
  4. the original text should be set back at .onlyfire element;
  5. .fire className will be removed from .onlyfire element;
  6. click .onlyfire element again
  7. handler attached to .fire element is called, in turn calling alert("this should not be showing once the text is changed back to original"), though no .fire element exists in document at that point

Question: Is this a jQuery bug, or expected behaviour? Or, have we overlooked something within javascript which would explain result?

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177

2 Answers2

4

Event handlers are bound to elements not to their classNames. Static event handlers do not work like delegated event handlers.

Ram
  • 143,282
  • 16
  • 168
  • 197
4

That is expected behaviour.

Once an event handler is attached, the class changes made to that element do not influence the fact that the event will trigger the event handler. The class only plays a role in finding the element to attach the handler to. Once that is done, the class selector plays no role any more.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Are the details of this behaviour available at jQuery documentation? Is the same true for `document.querySelector(".fire").oneventname` and `document.querySelector(".fire").addEventListener("eventname")`? – guest271314 Aug 20 '16 at 18:21
  • 2
    It is indeed not related to jQuery, but how the native DOM methods work. `querySelecor` delivers a matching element, and the `addEventListener` method or `oneventname` property act on this, without knowing even how you got that element. – trincot Aug 20 '16 at 18:29