I have a webpage with a modal with a custom dropdown under a shadowroot as follows:
<div id="main">
#shadow-root
<div id="sample-modal">
<div role="dialog" aria-hidden="true">
<div >
<div >
<h6 style="font-size:0.85rem" id="download-modal-label">Modal Title</h6>
</div>
<form onsubmit="return false;">
<div id="modal-body" style="overflow: inherit !important">
<div >
<button onclick="myFunction()" >Dropdown</button>
<div id="myDropdown" >
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">About</a>
<a href="#base">Base</a>
<a href="#blog">Blog</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
For this, I want to add an event listener where if I click anywhere besides the dropdown, I hide the dropdown div. For this, I added the event listener as follows:
let root = document.getElementById("main").shadowRoot;
$(root).on("click", function(e) {
var clickedOn=$(e.target);
});
But this doesn't seem to work at all. I tried attaching the click event listener to the document, to check the event target as follows:
$(document).on("click", function(e) {
var clickedOn=$(e.target);
});
This event listener is triggered, but the target element 'e' it shown as the <div id="main">
irrespective of if I click on any element including the dropdown element under the modal. How do I add the event listener where I get the correct element under the shadowRoot which was clicked on using the 'click' event listener?
CodePudding user response:
use addEventListener
root.addEventListener("click", function(e) {
var clickedOn=$(e.target);
});