JavaScript Events:
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
onclick Event Type
This event type which occurs when a user clicks the left button of his mouse. We can put our validation, warning etc., against this event type.
Example
<html> <head> <script type = "text/javascript"> <!-- function func() { alert("Hello World!") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type = "button" onclick = "func()" value = "Say Hello" /> </form> </body> </html>
onsubmit Event Type
onsubmit is an event that occurs when we try to submit a form. We can put our form validation against this event type. In following example we use validate() function, If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
Example<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
declare required validation
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
<html> <head> <script type = "text/javascript"> <!-- function validation() { declare required validation ......... return either true or false } //--> </script> </head> <body> <form method = "POST" action = "t.cgi" onsubmit = "return validate()"> ....... <input type = "submit" value = "Submit" /> </form> </body> </html>
onmouseover and onmouseout
These two event types will help us create nice effects with images or even with text as well. The onmouseover event triggers when we bring our mouse over any element and the onmouseout triggers when we move our mouse out from that element.
Example
<html> <head> <style> #msg{ width:200px; height:200px; background-color:#FC6; } </style> <script type="text/javascript"> function mover() { document.getElementById("msg").innerHTML="Hello to all"; } function mout() { document.getElementById("msg").innerHTML="Bye to all"; } </script> </head> <body> <img src="picts/rkt.jpg" onmouseover="mover()" onmouseout="mout()" /> <div id="msg"> </div> </div> </body> </html>
0 Comments