views:

173

answers:

2

How to join multiple event handlers in Javascript as in the following scenario :

onClick="doSomething();" onKeyUp="doSomething();" onLoad="doSomething();"
+5  A: 
function doSomething(){ console.log("Done!"); }
var element = document.getElementById("my-element");
element.onClick = element.onKeyUp = element.onLoad = doSomething;
Nick Retallack
A: 

I suggest using a javascript library's code to add events to abstract browser differences away from yourself.

I also suggest passing the event itself to the function(both prototype and jquery do this).

<script>
function doSomething(event){
  /*your code here*/
  /*this refers to the dom node in both libraries*/
};
</script>

JQuery

<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"&gt;&lt;/script&gt;
<script>
  $("my-element").bind("click keyup load", doSomething);
</script>

Prototype

<script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"&gt;&lt;/script&gt;
<script>
  $('my-element').observe('click', doSomething);
  $('my-element').observe('keyup ', doSomething);
  $('my-element').observe('load', doSomething);
</script>
antony.trupe
why the downvote?
antony.trupe