Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener to the whole body of a page except one div

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>

like image 290
shauna vayne Avatar asked Nov 13 '19 12:11

shauna vayne


People also ask

How do you make Eventlistener work only once?

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.

How do you add an event listener to the body element?

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.

Is it better to use onclick or addEventListener?

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.

What is third argument in addEventListener method?

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 .


1 Answers

Check the targets class name.

document.body.addEventListener('click', function(e) {
    if (!e.target.classList.contains('sssss')) {
        // your code
    }
});
like image 94
ztom Avatar answered Oct 02 '22 23:10

ztom