Events - where to place them?

I am sure that around the js developer community we can have consensus around this:

Should we declare or do onclick, onkeyup ... etc. events inside or outside our HTML document?

1) I prefer to have them separately. Truth. 2) I also know that HTML5 adds new interactive elements to the game ...

Regards, MEM

0
source share
4 answers

Ideally, if you can define your event code and attach these events to the corresponding elements in separate JS files. Separate JS and HTML where possible.

+2
source
+3

inline .

element.onkeyup - .

. .

EDIT: Tim Down :

  • " , ...", . .

  • " " IE5.5 + FF2 + Safari 3+ Opera 9+. 99% + -, . - , . Javascript . , , , , , .

  • return false; - " / / DOM". , ? , event.stop().

+3

, , , , someElement.onclick = function(e) { ... };, , , <input type="button" onclick="doSomething()">, . , .

(, ) , . , , .

, , .


myElement.onclick = function(e) { alert("Clicked"); };

, script, .

  • , , Event (window.event IE, )
  • return false

  • HTML .

<input type="button" value="test" onclick="alert('Clicked');">

, , , , (. http://peter.michaux.ca/articles/the-window-onload-problem-still ). , .


addEventListener/attachEvent

(attachEvent )

myElement.addEventListener("click", function(e) { alert("Clicked"); }, false);

, . addEventListener DOM 2.

  • addEventListener is a modern standard, with support in IE 9, which means that all current major browsers will support the release of IE 9

disadvantages

  • It's a little tricky to implement cross browser correctly
  • IE is attachEventnot quite equivalentaddEventListener
  • In HTML source elements, handlers are usually not assigned until the document is loaded.
+2
source

Source: https://habr.com/ru/post/1777345/


All Articles