CSS / Javascript - Does "display:none" remove any associated event listeners temporarily?

sookie picture sookie · Nov 28, 2015 · Viewed 9.9k times · Source

I'm thinking more in terms of efficiency. If I choose to set the display of an element to none, will javascript continue to listen for events attached to it, or does it temporarily remove them until the display is reverted back?

Answer

Praveen Kumar Purushothaman picture Praveen Kumar Purushothaman · Nov 28, 2015

It depends on the kind of events happening. Let's try using a click event:

$(function () {
  // Let's attach an event.
  $("#eventContainer").click(function () {
    $("#eventAffected").html("I changed.");
  });
  // This will hide the container surely when you click.
  $("#hide-container").click(function () {
    $("#eventContainer").hide().css("display", "none");
  });
  // This will trigger the event on the element.
  $("#trigger-event").click(function () {
    $("#eventContainer").trigger("click");
  });
});
* {font-family: 'Segoe UI'; margin: 5px;}
#eventContainer, #eventAffected {background-color: #ccf; text-align: center; padding: 5px;}
#eventAffected {background-color: #cfc;}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="eventContainer">Hello I am the Event Box</div>
<div id="eventAffected">Hello, I change when event triggered on the above.</div>
<button id="hide-container">Hide</button>
<button id="trigger-event">Trigger Click</button>

Test Cases

  1. Click on the First Div. Second Div Changes, event is triggered.
  2. Click on the Trigger Click. Second Div Changes, event is triggered.
  3. Click on the Hide and Trigger Click. Second Div Changes, event is triggered.

Conclusion

Whether or not, the DOM element is visible in the screen or off-screen, all the events and behaviours are preserved. Only the CSS display is changed. Nothing else, nothing related to behaviour is affected.

This is similar to all the events, only thing is, you cannot calculate the dimensions or box model.

So this shows that the events are preserved when there's visibility: hidden or display: none.