I've been looking for some solutions to solve this problem, but nothing helps
Here is my JavaScript code
var specifiedElement = document.getElementById('a');
document.addEventListener('click', function(event) {
var isClickInside = specifiedElement.contains(event.target);
if (!isClickInside) {
alert('You clicked outside A and B')
}
});
div {
background: #aaa;
height:2em;
padding: 1em;
margin-bottom:10px;
text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>
(In JS Fiddle: https://jsfiddle.net/1zj9dmq7/)
I want when I click div a/b element, the "alert" function will not run, just running when clicked outside of that 2 elements, and without jQuery
Maybe someone can help me please, Thank You
Answer: Use the event. target Propertytarget property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.
We can detect clicks outside an element with Vue. js by creating our own directive. We call Vue. directive with the directive name and an object that has the bind and unbind methods to add the el.
To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs. Approach: Here the approach is to use @HostListener decorator.
To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.
Try this:
var a = document.getElementById('a');
var b = document.getElementById('b');
document.addEventListener('click', function(event) {
var isClickInside = a.contains(event.target)||b.contains(event.target);
if (!isClickInside) {
alert('You clicked outside A and B')
}
});
Demo: https://jsfiddle.net/1zj9dmq7/1/
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