Attach Event Handlers For Click Event On All Elements In The Dom
Solution 1:
currentTarget
returns the node to which the event has bubbled (if at all). Instead, interrogate target
, so:
Vanilla:
document.addEventListener('click', function(evt) {
alert(evt.target.tagName);
}, false);
jQuery:
$(document).on('click', function(evt) {
alert(evt.target.tagName);
});
Solution 2:
Just Do this:
var listener = functionhandleClick(event){
element = event.targetconsole.log(element)
}
var body = document.body
body.addEventListener('click', listener, true);
This will print the element clicked on the DOM.
Solution 3:
I faced the same type of problem to find out which element is clicked on the navbar. I was working in animation slide. So, To solve it, I try to handling all the events of <ul>
TO BE NOTED: This is just for a piece of block. Not entire webpage.
Here is my reactjs code. Concept is same.
jsx
<ulclassName="right"onClick={setRainbow}><li><Linkto="/">Home</Link></li><li><NavLinkto="/about">About</NavLink></li><li><NavLinkto="/contact">Contact</NavLink></li></ul>
function
constsetRainbow = (e) => {
console.log(e.target)
console.log(e.target.href)
console.log(e.target.text)
if (e.target.text === 'About') {
// to do
} else {
// to do
}
}
Solution 4:
Try this:
$(document).on('click', function(e) {
// now use e.target here
});
You can also kill the bubbling on the click event by using e.stopPropagation()
Solution 5:
I don't see any need to use jQuery for something like this, though my suggestion does rely on MutationEvents, which I understand are to be replaced.
You can get notified upon the insertion of any new node into the DOM. In the callback that fires, you can trivially attach an onclick handler to the new node. I've only handled the case where new nodes are added.
<!DOCTYPE html><html><head><script>window.addEventListener('load', onDocLoaded, false);
functiononDocLoaded()
{
window.addEventListener('DOMNodeInserted', onNodeInserted, false);
document.body.appendChild( newEl('div') );
}
functiononNodeInserted(evt)
{
evt.srcElement.addEventListener('click', onNodeClicked, false);
}
functiononNodeClicked()
{
document.body.appendChild( newEl('div') );
}
</script><style>div
{
border: solid 1px red;
padding: 8px;
margin: 4px;
display: inline-block;
}
</style></head><body></body></html>
Post a Comment for "Attach Event Handlers For Click Event On All Elements In The Dom"