JavaScript Events

Event: An Event is change in the state of an object.In HTML there are various events which represents that some action is performed by the user.For eg. onclick(),onload() etc.

Event Handler: When HTML events embed in JavaScript code,then these code react over events and execute them.This process is known as Event Handling and JavaScript handle these HTML events via Event Handler.

Some Events are as following:

Mouse Events:

Event Handler Description
onclick When mouse click on an element.
onmouseover When the cursor of the mouse comes over an element.
onmouseout When the cursor of the mouse leaves an element.
onmousedown When the mouse button is pressed over the element.
onmouseup When the mouse button is released over the element.
onmousemove When the mouse make any movement.

Example:

<html>

<body>
<script language="Javascript" type="text/Javascript">
    <!--
    function clickevent()
    {
        document.write("You Perform Mouse Click Event");
    }
    //-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Click Me!!!"/>
</form>
</body>
</html>

Explanation: In example above we define a function named clickevent() which have an single write statement.We place an input button and on click of that button clickevent() function will invoke.

Output:

You Perform Mouse Click Event

Keyboard Event:

Event Handler Description
onkeydown & onkeyup When the user press and then release the key

Example:

<html>    
<body>  
<h2> Enter something here</h2>  
<script>  
<!--  
    function keydownevent()  
    {  
        document.getElementById("input1");  
        alert("You pressed a key");  
    }  
//-->  
</script>  
<form>
<input type="text" id="input1" onkeydown="keydownevent()"/>  
</form>
</body>  
</html>

Form Event:

Event Handler Description
onfocus When the user focuses on an element
onsubmit When the user submits the form
onblur When the focus is away from a form element
onchange When the user modifies or changes the value of a form element

Example:

<html>  
<body>  
<h2> Type here</h2>  
<script>  
<!--  
    function focusevent()  
    {  
        document.getElementById("input1").style.background=" pink";  
    }  
//-->  
</script> 
<form>
<input type="text" id="input1" onfocus="focusevent()"/>  
</form> 
</body>  
</html>

Window/Document Event:

Event Handler Description
onload When the browser finishes the loading of the page
onunload When the visitor leaves the current webpage, the browser unloads it
onresize When the visitor resizes the window of the browser

Example:

<html>  
<body onload="window.alert('Page successfully loaded');">  
<script>  
<!--  
document.write("The page is loaded successfully");  
//-->  
</script>  
</body>  
</html>