Basic JavaScript Question:
Download Questions PDF

How to Handle Event Handlers?

Answer:

You can add an event handler in the HTML definition of the element like this,
<script type="text/javascript"><!--
function hitme() {
alert("I've been hit!");
}
// -->
</script>
<input type="button" id="hitme" name="hitme" value="hit me" onclick="hitme()"

Or, interestingly enough you can just assign the event's name on the object directly with a reference to the method you want to assign.

<input type="button" id="hitme2" name="hitme2" value="hit me2"/>
<script type="text/javascript"><!--
function hitme2() {
alert("I've been hit too!");
}
document.getElementById("hitme2").onclick = hitme2;
// -->
</script>

You can also use an anonymous method like this:

document.getElementById("hitme3").onclick = function () { alert("howdy!"); }

You can also use the the W3C addEvventListener() method, but it does not work in IE yet:

<input type="button" id="hitme4" name="hitme4" value="hit me4"/>
<script type="text/javascript"><!--
function hitme4() {
alert("I've been hit four!");
}


Download JavaScript Interview Questions And Answers PDF

Previous QuestionNext Question
How to getting values from cookies to set widgets?How to remove the event listener?