'Shadowroot : Not getting the correct target for event listener
I have a webpage with a modal with a custom dropdown under a shadowroot as follows:
<div id="main">
#shadow-root
<div class="modal fade in" id="sample-modal">
<div class="modal-dialog modal-xl" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" style="font-size:0.85rem" id="download-modal-label">Modal Title</h6>
</div>
<form onsubmit="return false;">
<div class="modal-body" id="modal-body" style="overflow: inherit !important">
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
