JavaScript and events are best practice

I once read that the following encoding method is considered bad:

<a HREF="page.htm" onClick="alert('Hello World')">text link</a>

Basically, using these event handlers (like onClick) in an HTML tag is the wrong approach to use. What is the reason for this? What is the name of this "bad" technique? What is the “right” way to do this?

+5
source share
4 answers

This is a built-in attribute of the event handler . (+1 chjj answer for alternatives). It is usually considered "bad for a number of reasons:

  • you mix small pieces of JavaScript syntax with HTML syntax:

    • , , , ;

    • , HTML:

:.

<a href="x.html" onclick="this.innerHTML= '&lt;em>I like &quot;fish &amp;amp; chips&quot;&lt;/em>';">
  • - , . . ;

    • , DOM;

    • , , .

+5

. DOM 1 element.onclick, .

, . : , .

:

element.addEventListener('click', function() {
  console.log('hello world');
}, false); // required for old gecko

IE:

element.attachEvent('onclick', function() {
  console.log('hello world');
});

, DOM 1:

element.onclick = function() {
  console.log('hello world');
};

( : alert - , .)

, , . (, , [event], , [0] . , JS-land.)

, , - - . , HTML.

+6

, , HTML script.

Best practice is to attach the event this way:

window.onload = function() {
    document.getElementById("MyLink").onclick = function() {
        alert('Hello World');
        return false;
    }
}

After providing the link identifier MyLinkfor example.

+2
source

A better approach is called unobtrusive JavaScript , and it basically means separating behavior (JS) from structure (HTML), just like CSS is separating presentation from structure, and also for the same reasons.

+2
source

All Articles