0

I have problem with event target. I want to check which element were clicked but it don't work. What is the solution this problem ?

var prod = document.querySelectorAll("button");

function dodaj(e) {
    var tar = e.target;
    
    console.log(tar);
}


for(var i = 0; i < prod.length; i++) {
    prod[i].addEventListener("click", function() {
       dodaj(); 
    }, false);
}

1
  • Try: prod[i].addEventListener("click", function(e) { dodaj(e); }, false); Commented Feb 19, 2017 at 20:51

2 Answers 2

2

You haven't passed anything into dodaj. You could just pass dodaj directly into addEventListener.

prod[i].addEventListener("click", dodaj, false);
Sign up to request clarification or add additional context in comments.

Comments

1

The issue is that your click event handler was an anonymous function that was putting in a call to the actual function that does the work (dodaj) and that function was not receiving the reference to the event - the anonymous function was.

You can change the anonymous function so that it receives the event and then passes it to dodaj like this:

prod[i].addEventListener("click", function(evt) {
   dodaj(evt); 
}, false);

However, since that "wrapper" function really wasn't adding any value to your code, you can/should remove it entirely and just register the actual callback function as the click event handler.

var prod = document.querySelectorAll("button");

function dodaj(e) {  
    console.log(e.target);
}

for(var i = 0; i < prod.length; i++) {
  // When any button gets clicked, call the dodaj function
  // directly. This is the function that will receive a 
  // reference to the click event.
  prod[i].addEventListener("click", dodaj);
}
<button id="one">Click Me</button>
<button id="two">Click Me</button>
<button id="three">Click Me</button>
<button id="four">Click Me</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.