+ 3

addEventListener vs on(eventname) what to use when...Is one more preferavle than the others?

I am a beginner to javascript and confused over the term stated above both seems to do the same thing...Whats the difference then?

16th Feb 2018, 7:45 PM
Film Fanatic
Film Fanatic - avatar
1 Antwort
+ 10
Simply saying - "element.onevent = function" rewrites previous "element.onevent"s, in other side, "element.addEventListener(event, function)" don't do that. Using "addEventListener", you can add as many event functions, as you want to one element. Try uncomment/comment two sections of this code: ... //don't forget to add element with id="test" var q = 0; var test = document.getElementById('test'); test.style.background = '#ccc'; test.style.display = 'block'; test.style.width = '640px'; test.style.height = '480px'; //1 test.addEventListener('click', function() {test.innerText += ',' + q++;}); test.addEventListener('click', function() {test.innerText += ' ' + (q+=2);}); //2 /*test.onclick = function() {test.innerText += ',' + q++;}; test.onclick = function() {test.innerText += ' ' + (q+=2);};*/
17th Feb 2018, 7:18 AM
K137(){/**/};
K137(){/**/}; - avatar