9.3 JAVASCRIPT EVENTS

Interaction of JavaScript with HTML is handled through events that occur when the user or the browser manipulates a page.
(i) onclick event
(ii) onsubmit event
(iii) onmouseover & onmouseout events
(iv) HTML5 standard events

onclick event-
“onclick” event is frequently used event. This event occurs when a user clicks the left button of his/her mouse. You can use/activate your validation or warning or etc., against this event type.

Example
<html>
<head>
      <script type= “text/JavaScript”>
<!-- function sayWelcome () {
                alert(“Welcome”)
            }
          //--> //comments placed to prevent execution of js if browser does not support it.
      </script>
        </head>
      <body>
<p>Click on the button and get the result</p>
<form>
<input type=”button” onclick= “sayWelcome()” value=”Say Welcome” />
</form>
</body>
</html>

onsubmit event-
“onsubmit” event is generated when someone submits a form. You can create form validation action against “onsubmit” event.

Example:
The example given below show how to use “onsubmit” event. Here we are calling a validate() function. The validate() function called before submitting the form data to the webserver. If this function returns true, then the form data will be submitted to the webserver, otherwise it will not be submitted to the web server.
Try the following example.
<html>
<head>
<script type= “text/JavaScript”>
<!--
function validate() {
all validation goes here
........
return either true or false
}
//-->
</script>
</head>
    <body>
<form method= “POST” action= “submit.html” onsubmit= “return validate()”>
        .......
          <input type= “submit” value= “Submit” />
</form>
</body>
</html>

onmouseover & onmouseout events-
The “onmouseover” and “onmouseout” events will help you to create effects with images as well as with text too. The “onmouseover” event triggers (occurs) when you move or bring mouse pointer over any element.
 The “theonmouseout” event triggers (occurs) when you move or bring your mouse pointer out from that element. Example as given below-
<html>
   <head> 
      <script type= “text/JavaScript”>
         <!--
            function over() {
               document.write (“Mouse Over”);
            }
            function out() {
               document.write (“Mouse Out”);
            } 
         //-->
      </script> 
   </head>
   <body>
      <p>Bring your mouse inside the division to see the result:</p> 
      <div onmouseover= “over()” onmouseout= “out()”>
         <h2> This is inside the division </h2>
      </div>
   </body>
</html>

HTML5 standard events-
The standard HTML 5 events are listed here for your reference. Here script indicates a JavaScript function to be executed against that event.

1

2

3

4

Licensed under the Creative Commons Attribution Share Alike License 4.0

Made with eXeLearning (New Window)