Why onmousemove ?
The JavaScript onmousemove feature works when the user moves the mouse. (on a specified item)
Syntax:
| HTML Attribute | <element onmousemove = “handler(event)“> |
| Event Property | object.onmousemove = handler; |
| attachEvent Method | object.attachEvent(“onmousemove“, handler) |
| addEventListener Method | object.addEventListener(“mousemove“, handler, useCapture) |
onmousemove Examples
Example 1
<body>
<div class="container">
<h2>onmousemove Event</h2>
<div id="box" onmousemove="moveFunction(event)" ></div>
<div id="posX"></div>
<div id="posY"></div>
</div>
<script>
function moveFunction(e) {
let x = e.clientX;
let y = e.clientY;
let printX = document.getElementById("posX");
let printY = document.getElementById("posY");
printX.innerHTML = "Coordinate X: " + x ;
printY.innerHTML = "Coordinate Y: " + y ;
}
</script>
</body>
Example 2
<body>
<div class="container">
<h2>onmousemove Event</h2>
<div id="box"></div>
<div id="posX"></div>
<div id="posY"></div>
</div>
<script>
document.getElementById("box").onmousemove = function () {
moveFunction(event)
}
function moveFunction(e) {
let x = e.clientX;
let y = e.clientY;
let printX = document.getElementById("posX");
let printY = document.getElementById("posY");
printX.innerHTML = "Coordinate X: " + x ;
printY.innerHTML = "Coordinate Y: " + y ;
}
</script>
</body>
Example 3
<body>
<div class="container">
<h2>onmousemove Event</h2>
<div id="box"></div>
<div id="posX"></div>
<div id="posY"></div>
</div>
<script>
document.getElementById("box").addEventListener("mousemove", moveFunction)
function moveFunction(e) {
let x = e.clientX;
let y = e.clientY;
let printX = document.getElementById("posX");
let printY = document.getElementById("posY");
printX.innerHTML = "Coordinate X: " + x ;
printY.innerHTML = "Coordinate Y: " + y ;
}
</script>
</body>
Example 4
<body>
<div class="container">
<h2>onmousemove Event</h2>
<div id="box"></div>
<div id="result"></div>
</div>
<script>
document.getElementById("box").addEventListener("mousemove", moveFunction)
let a = 0;
function moveFunction() {
a++;
document.getElementById("result").innerHTML = a;
}
</script>
</body>
Example 5
<body>
<div class="container">
<h2>onmousemove Event</h2>
<div id="box" onmousemove="moveFunction()"></div>
</div>
<script>
var i = 0;
function moveFunction() {
let box = document.getElementById("box");
var backgroundC = ["Orange", "Green", "Blue", "Red", "Black", "Brown"];
if (i < backgroundC.length) {
box.style.backgroundColor = backgroundC[i];
i += 1;
}
else {
i = 0;
}
}
</script>
</body>
Leave a comment