Search code examples
javascriptjqueryonclickprototypejsobserver-pattern

onClick Vs Observer


I would like to know why it's better to use observers rather than adding the action directly into the onclick="".

eg.

$('mybutton').observe('click', respondToClick);

vs

<a href="#" onclic="respondToClick()">button</a>

Thanks


Solution

  • This is a fairly common question so I'll refer you to a quality article on quirksmode.org that answers this question and other question you may have about event handling.

    Here is an excerpt:

    <a href="somewhere.html" onclick="alert('I\'ve been clicked!')">
    

    It is very important to realize that this ancient way of event handling was de facto standardized by Netscape. All other browsers, including Explorer, had to conform to the way Netscape 2 and 3 handled events if they wanted JavaScript to work. Therefore these ancient events and event handlers work in all JavaScript browsers.

    Have fun reading.