
Mouse events occur when the user moves or clicks the mouse button. Mouse event is DOM Ver 2.
| Event | Description |
|---|---|
| onclick | When the user click a mouse button over an HTML element. |
| onmouseover | When the user move the mouse over an HTML element. |
| onmouseout | When the user move the mouse away from an HTML element. |
| onmousedown | When the user press the mouse button over an HTML element. |
| onmouseup | When the user release the mouse button over an HTML element. |
| onmouseenter | The onmouseenter event occurs when the mouse pointer is moved onto an element. |
| onmouseleave | The onmouseleave event occurs when the mouse pointer is moved out of an element. |
| onmousemove | When the user moves the mouse over an HTML element. |
<h2 onclick="this.style.color='red'">Click Me!</h2>
Example 2: JavaScript onmouseover, onmouseout event. 1
<head>
<style>
table{ width: 300px; height: 100px; }
table td:first-child{ background-color: red; }
table td:nth-child(2){ background-color: blue; }
table td:nth-child(3){ background-color: green; }
</style>
</head>
<body>
<p>Change the background color using JavaScript Event onmouseover and onmouseout.</p>
<table>
<tr>
<td onmouseover="bgChange('red')" onmouseout="bgChange('transparent')"> </td>
<td onmouseover="bgChange('blue')" onmouseout="bgChange('transparent')"> </td>
<td onmouseover="bgChange('green')" onmouseout="bgChange('transparent')"> </td>
</tr>
</table>
<script>
function bgChange(bg) {
document.body.style.background=bg;
}
</script>
</body>
Example 3: JavaScript onmouseover, onmouseout event. 1
<h2 id="h2text" onmouseover="nameon()" onmouseout="nameout()">Mouse over this text!</h2>
<script>
function nameon() {
document.getElementById('h2text').innerHTML="WELCOME!";
}
function nameout() {
document.getElementById('h2text').innerHTML="How are you today?";
}
</script>
Example 4: JavaScript onmousedown, onmouseup event. Long mouse down on image to see the effect. 1
<img src="https://www.ankitweblogic.com/images/h2.jpg" onmousedown="this.src='https://www.ankitweblogic.com/images/h6.jpg'" onmouseup="this.src='https://www.ankitweblogic.com/images/h2.jpg'" alt="JavaScript Mousedown Mouseup Event">
Example 5: JavaScript onmouseenter, onmouseleave event. 1
<marquee direction="left" bgColor="green" onmouseenter="this.stop()" onmouseleave="this.start()">
Scrolling Text with JavaScript events onmouseenter and onmouseleave
</marquee>
<body>
<div onmousemove="moveright()">
<h1 id="header">Move the mouse over this page</h1>
</div>
<script>
let i=1;
function moveright() {
document.getElementById('header').style.position="relative";
document.getElementById('header').style.left=i+"px";
i++;
}
</script>
</body>
Ad: