Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "click" and onclick

Tags:

javascript

What is the difference between click in

document.getElementById("myBtn").addEventListener("click", displayDate);    

and onclick in

<!DOCTYPE html>
<html>
<body>

<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>

</body>
</html> 

Are they both considered as events? Why can't we use click instead of onclick and visce versa?

like image 857
Mohamed Karam Avatar asked Apr 30 '16 21:04

Mohamed Karam


2 Answers

The difference is that the first is an event listener, and the second is an event handler content attribute.

Event handler content attributes store an internal raw uncompiled handler, which produces an event listener via the event handler processing and getting the current value of the event handler algorithms.

In practice, this affects the scope, e.g.

(function() { var element = document.body;
  var str = "console.log([typeof foo, typeof bar])";
  var func = function() { console.log([typeof foo, typeof bar]); };
  element.foo = 'foo';
  var bar = 'bar';
  element.setAttribute('onclick', str);
  element.addEventListener('click', func);
  element.click();
  // Event handler content attribute logs ["string", "undefined"]
  // Event listener logs ["undefined", "string"]
})();

I discourage using event handlers. They are an old reminiscence and are superseded by event listeners.

like image 68
Oriol Avatar answered Sep 20 '22 14:09

Oriol


Yes, they are both events, simply put the same, and one use onclick when assign its handler inline, and the other click when assign using an event listener (which is the recommended way).

And you can't use them vice versa, as this is how it has to be done or they won't work.

Read more at MDN:

  • https://developer.mozilla.org/en-US/docs/Web/Events/click
  • https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers
like image 30
Asons Avatar answered Sep 16 '22 14:09

Asons