I have a javascript file that sets an EventListener of 'click' on every element with the <article>
tag. I want to get the id of the article clicked when the event fires. For some reason, my code produces nothing!
My javascript:
articles = document.getElementsByTagName('article');
articles.addEventListener('click',redirect(e),false);
function redirect(e){
alert(e.target.id);
}
Why isn't this working? BTW my article setup is in a function called when the window is loaded, and i know that works for sure because that function has other stuff that work.
EDIT
So i fixed my code so it will loop and add the listener to every article element, and now i get an alert box with nothing in it. When trying to output the e.target without the ID, i get the following message for every element:
[object HTMLHeadingElement]
Any suggestions?
ANOTHER EDIT
My current javascript code:
function doFirst(){
articles = document.getElementsByTagName('article');
for (var i = 0; i < articles.length; i++) {
articles[i].addEventListener('click',redirect(articles[i]),false);
}
}
function redirect(e){
alert(e.id);
}
window.addEventListener('load',doFirst,false);
This is showing my alert boxes when the page finished loading, without considering that i haven't clicked a damn thing :O
You are executing the redirect function instead of passing the reference, try this:
Edit: Also, getElementsByTagName returns an array with articles, so you have to loop through them and call addEventListener on each one of them.
if does not work then try by e.id instead of e.target.id inside alert as below:
Thanks.
You are not passing an article object to redirect as a parameter.
Try this (EDIT):
Hope, it will solve the bug.
Why is nobody mentioning a single event which checks for the clicked element?
it's more performant to have less events..
if you don't need to check for click events on the whole body you could attach the event to some closer parent element
getElementsByTagName
returns a nodelist. You can then add an eventlistener to each one of those elements with a for loop.This mini javascript libary (1.3 KB) can do all these things
https://github.com/Norair1997/norjs/
This plugin can handle such stuff and more