Binding Events in JavaScript

There are different ways you can bind an event handler to a JavaScript Event. The first is the traditional way of using the HTML attribute on<event> = “handler”.


<a href=”somewhere.html” onclick=”myfunction” onmouseover=”myhoverhandler” >Click here</a>

and the JavaScript code would be

<script type=”text/javascript”> function myfunction() { /* JavaScript Code here */ } </script>

The second way of binding the events would be assigning the DOM object directly using javascript as

var myElement = document.getElementById(“myId”); // OR any other method of selecting the DOM.

//assigning the event handler

myElement.on<event> = handlerFunction;


myElement.onclick = function() { }

myElement.onmouseover = myFunction;

where myfunction can be defined as

function myfunction() { }

( OR )

myFunction = function () { }

NOTE : Never Use

myElement.onclick = alert(“hi”);

It is not good to use the above way. In the next post I’ll discuss about the next way of binding.

  • http://www.financialaidfor-college.com financial aid for college

    Superb blog post, I have book marked this internet site so ideally I’ll see much more on this subject in the foreseeable future!

  • http://www.new-federal-grants.com federal grants

    Thanks for some quality points there. I am kind of new to online , so I printed this off to put in my file, any better way to go about keeping track of it then printing?

  • http://www.flapzipzam.com sam waiseghoby

    Hey there this is a fantastic post. I’m going to e-mail this to my pals. I came on this while exploring on aol I’ll be sure to come back. thanks for sharing.