I was wondering if there was any way to add an event listener to the whole page except one div in it. To be more specific in the example below is there any way to add an event listener to the body except the div? e.g
html:
<body>
<div class="sssss"></div>
</body>
Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
To add an event listener to the body element: Access the body element on the document object. Use the addEventListener() method on the body element in the useEffect hook. Remove the event listener when the component unmounts.
Summary: addEventListener can add multiple events, whereas with onclick this cannot be done. onclick can be added as an HTML attribute, whereas an addEventListener can only be added within <script> elements. addEventListener can take a third argument which can stop the event propagation.
addEventListener listens for both capture phase and bubbling phase events. The third parameter (called useCapture in the specification) allows the programmer to specify which phase they want to use. In modern browsers, this defaults to false .
Check the target
s class name.
document.body.addEventListener('click', function(e) {
if (!e.target.classList.contains('sssss')) {
// your code
}
});
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