JavaScript Events
JavaScript Events
JavaScript events are actions or occurrences, such as user interactions or browser activities,
that a web page can respond to. These events allow developers to execute specific code in
response to user inputs, enhancing interactivity and functionality.
Mouse Events
Example:
<html>
function clickevent()
{
document.write("This is John");
}
</script>
<body>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
When the button labeled "Who's this?" is clicked, the function clickevent() is executed. This
replaces the entire content of the page with the text:
"This is John”
Example:
<html>
function mouseoverevent()
{
alert("Mouse Over Event");
}
</script>
<body>
<p onmouseover="mouseoverevent()"> Keep cursor over</p>
</body>
</html>
The alert of ‘Mouse Over Event’ is shown when the cursor is kept over the text.
Example:
<html>
function mouseoutevent()
{
alert("Mouse has left the text!");
}
</script>
<body>
<form>
<p onmouseout="mouseoutevent()"> Hover over this text and then move your mouse
away.</p>
</form>
</body>
</html>
When the mouse is moved away from the text, it displays an alert saying:
"Mouse has left the text!”
Example:
<html>
<script>
function mouseDown() {
alert("Mouse button pressed!");
}
</script>
<body>
<input type="button" onmousedown="mouseDown()">Press Me</input>
</body>
</html>
When you press the mouse button down on the "Press Me" button, an alert appears saying:
"Mouse button pressed!”
Example:
<html>
<script>
function mouseUp() {
alert("Mouse button released!");
}
</script>
<body>
<input type="button" onmouseup="mouseUp()">Release Me</input>
</body>
</html>
When you release the mouse button after pressing it on the "Release Me" button, an alert
appears saying:
"Mouse button released!”
Example:
<html>
<script>
function mousemoveevent() {
alert("Mouse is moving!");
}
</script>
<body>
<p onmouseup="mousemoveevent()">Move your mouse over this text</p>
</body>
</html>
When you move the mouse pointer over the text an alert appears saying:
"Mouse is moving!"
Example:
<html>
<script>
function doubleClick() {
alert("Button double-clicked!");
}
</script>
<body>
<input type ="button" ondblclick="doubleClick()">Double Click Me</input>
</body>
</html>
When you double-click on the "Double Click Me" button, an alert appears saying:
"Button double-clicked!”
Keyboard Events
Keyboard events are triggered/activated when the user interacts with the keyboard.
Example:
<html>
<script>
function keydownevent() {
alert("Key Down event” );
}
</script>
<form>
<input type="text" onkeydown="keyDownEvent()" placeholder="Type something"><br>
</form>
</html>
The alert of ‘Key Down Event’ is shown when the key is pressed.
Example:
<html>
<script>
function keyupevent() {
alert("Key Up event");
}
</script>
<form>
<input type="text" onkeyup="keyUpEvent()" placeholder="Type something">
</form>
</html>