Search code examples
javascriptdom-events

JavasScript event handling best practice?


When defining a JavaScript call, like so:

<input type="button" onclick="someJavaScriptFunction" />

What is the best way to write the actual call? I've seen numerous method:

javascript:someJavascriptFunction();

or

justSomeJavaScriptFunction();

or

withoutTheSemicolon()

Are there any benefits or caveats to any of the methods? I realize that using addEventListener is more flexible in certain cases.


Solution

  • If you want best practice, separate markup from script content. Assign your event handlers in script elements. As you say, using addEventListener is one way of doing this, although you have to use attachEvent as well if you want to support versions of Internet Explorer before version 9.

    It's perfectly valid, however, to assign onevent properties. For instance:

    <script>
        window.onload = function() {
            document.getElementById('yourID').onclick = function() {
               alert('element clicked');
            };
        };
    </script>
    

    This may well suit your purpose adequately, if you only have a few items.