JavaScript Events with example
Here you will learn to code the program of Javascript Events with examples.
What are JavaScript events
JavaScript events are actions or occurrences that happen in the browser or on a web page, triggered by users or the browser itself. Here are some common events in JavaScript:
onClick: Occurs when a user clicks on an element.
Load: Occurs when a resource and its dependent resources have finished loading.
onmouseover: Occurs when the mouse pointer is moved onto an element.
onmouseout: Occurs when the mouse pointer is moved out of an element.
Keydown: Occurs when a key is pressed down.
Keyup: Occurs when a key is released.
onkeypress: Triggered when you press a key.
onFocus: Occurs when an element receives focus.
onBlur: Occurs when an element loses focus.
Submit: Occurs when a form is submitted.
Onload– Occurs when the page is loaded.
onload and onunload event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <html> <head> <script language="javascript"> function hello() { alert("Good Morning"); } function bye() { alert("Good Bye..."); } </script> </head> <body onload="hello()" onunload="bye()"> </body> </html> |
onClick event
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head> <script language="javascript"> function first() { alert("Welcome to CodeRevise.com"); } </script> </head> <body> <input type="button" value="Click Me" onclick="first()"> </body> </html> |
onfocus and onblur event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <html> <head> <script language="javascript"> function myFunction(x) { x.style.background = "green"; } function myFunction2() { let x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> </head> <body> Enter your name : <input type="text" id="fname" onfocus="myFunction(this)" onblur="myFunction2()"> <p>onfocus => When the input field gets focus, a function changes the background-color.</p> <br> <p>onblur => When the input field loose focus, a function change the lowercase to uppercase.</p> </body> </html> |
onmouseout and onmouseover event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <html> <head> <script language="javascript"> function mouseOver() { document.getElementById("demo").style.color = "red"; } function mouseOut() { document.getElementById("demo").style.color = "black"; } </script> </head> <body> <h1>Example of onmouseout and onmouseover event</h1><br><br> <h1 id="demo" onmouseover="mouseOver()" onmouseout="mouseOut()">Mouse over me</h1> <p>onmouseover => The text color changed to red</p> <br> <p>onmouseout => The text color changed to black</p> </body> </html> |
onkeypress event
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <body> <h1>The onkeypress Event</h1> <p>onkeypress is triggered when you press a key.</p> <input type="text" onkeypress="fun1()"> <script> function fun1() { alert("key pressed in text box"); } </script> </body> </html> |
Check out our other JavaScript examples