Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript click event listener on multiple elements and get target ID

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

like image 967
arielschon12 Avatar asked Dec 15 '12 14:12

arielschon12


People also ask

Can I add an event listener to multiple elements in JavaScript?

Adding an Event Listener to Multiple Elements Using a for...of Loop + IIFE. Open the console and click any of the buttons. The same event listener is added to each button using a for...of loop along with an immediately invoked function that passes the current element of the loop back into the function.

How do I find my event target element ID?

To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');

How do I get the clicked event ID?

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.


1 Answers

You are not passing an article object to redirect as a parameter.

Try this (EDIT):

articles = document.getElementsByTagName('article');
for (var i = 0; i < articles.length; i++) {
    articles[i].addEventListener('click',redirect,false);
}
function redirect(ev){
    alert(ev.target.id);
}

Hope, it will solve the bug.

like image 54
Mohit Pandey Avatar answered Oct 15 '22 13:10

Mohit Pandey