Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: onchange or addEventListener?

I am totally new to Javascript. But I learned a little about Activescript before. I was taught to use addEventListener to handle events.

But when I come to JavaScript, although addEventListener is an option, it seems a minor way to use addEventListener. Instead, people use onChange().

Except syntactically, are there any behavioural differences?

I was also taught to always use removeEventListener. It seems not very necessary. If I use onChange, there is no need to code removeEventListener?

Thank you

like image 593
Trio Cheung Avatar asked Feb 14 '13 20:02

Trio Cheung


3 Answers

Two main differences :

  • addEventListener isn't compatible with old IE browsers
  • onchange doesn't add an event listener : it replaces the existing one
like image 107
Denys Séguret Avatar answered Nov 19 '22 17:11

Denys Séguret


With addEventListener you can attach multiple event listeners. This is not true of the onchange attribute.

like image 44
Waleed Khan Avatar answered Nov 19 '22 16:11

Waleed Khan


I personally think addEventListener is a lot of better. An example you can do with this in HTML5

document.addEventListener("input", function(){
  target = window.event.target.value;
  window.event.target.nextSibling.nextSibling.value = target*2;
});
<input name="1" value="25">
<input name="2" value="50" readonly>
<p>Hello World</p>
like image 31
Jens Ingels Avatar answered Nov 19 '22 17:11

Jens Ingels