Web Technology - Old Questions

6.  How can you define event handler? Write a JavaScript to demonstrate event handling.

5 marks | Asked in 2074

Event handlers are JavaScript code that are not added inside the <script> tags, but rather, inside the html tags, that execute JavaScript when something happens, such as pressing a button, moving your mouse over a link, submitting a form etc. The basic syntax of these event handlers is:

    name_of_handler="JavaScript code here"

For example:

<a href="http://google.com" onClick="alert('hello!')">Google</a>

When the above link is clicked, the user will first see an alert message before being taken to Google.

Some event handlers used in JavaScript:


JavaScript code to demonstrate event handling:
<html>
   <head>   
      <script type = "text/javascript">
            function sayHello() {
               alert("Hello World")
            }
      </script>      
   </head>
   <body>
      <p>Click the following button and see result</p>      
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello" />
      </form>      
   </body>
</html>