javascript event handlers

oggiemc
oggiemc used Ask the Experts™
on
Can someone explain whats happening in the followong lines of code, taken from the application attached..

var $ = function ( id ) {
return document.getElementById( id );
}
$("btnDisplay").onclick = display_click;           // In particular, what is going on here??

Thanks
head>
<title>JavaScript Event Handler</title>
<script type="text/javascript">
// This function receives an id and gets the related XHTML object.
var $ = function ( id ) {
return document.getElementById( id );
}
var display_click = function () {
alert( "You clicked the button.");
}
window.onload = function () {
$("btnDisplay").onclick = display_click;
}
</script>
</head>
<body>
<p><input type="button" value="Display Message" id="btnDisplay" /></p>
</body>
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
Instead rewriting the long sequence of code : document.getElementById( id ) we decide to write like a lot of javascript framework $

$("btnDisplay").onclick = display_click;  
is a short way to write :
document.getElementById("btnDisplay").onclick = display_click;   // attach a function to the onclick attribute of the button btnDisplay

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial