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?
In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.
Keeping events alive Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.
Reloading the page destroys the page's current elements and builds new ones from scratch, so event listeners don't survive that. (It also destroys the JavaScript environment that was associated with the page.
If there is no memory leak, the used memory will increase by around 1000kb or less after the tests are run. However, if there is a memory leak, the memory will increase by about 16,000kb. Removing the event listener first always results in lower memory usage (no leaks).
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
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
.
No, it doesn't remove them, but since the element and all of its descendants aren't rendered, there is no way for the user to trigger an event on any of them, so the browser will never test the element to see if it has any event handlers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With