Reputation: 169
I want when i move the mouse write specific text on the screen
example:"hello world"
i have code but he is not what I want
script --->
window.focus();
const output = document.querySelector('output');
let text = 'A';
window.addEventListener('mousemove', ({
x,
y
}) => {
if (x > 100) text = 'W';
if (x > 400) text = 'X';
if (y > 100) text = 'B';
if (y > 400) text = 'J';
output.textContent += text;
});
please help me!!
Upvotes: 0
Views: 639
Reputation: 6151
note that I changed for document.querySelector('#output');
because I used a div with id "output". If you are using and <output>
tag (?), keep it as in your original code.
Here the letter will move with the page scroll, if you want to keep at the same place while scrolling, use position: static;
instead.
const output = document.querySelector('#output');
let text = 'Hello World!';
window.addEventListener('mousemove', ({
x,
y
}) => {
output.innerHTML += '<div style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;">' + text + '</div>';
});
<div id="output" style="width: 100%; height: 100%;"></div>
Upvotes: 1
Reputation: 1342
i have modifyied this answer: https://stackoverflow.com/a/7790764/9496199 to have the text hello world displayed instead of a dot, hope this helps.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<style>
body {
height: 3000px;
}
.dot {
width: fit-content;
height: fit-content;
background-color: invisible;
position: absolute;
}
</style>
</head>
<body>
<script>
(function() {
"use strict";
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
var dot, eventDoc, doc, body, pageX, pageY;
event = event || window.event; // IE-ism
// If pageX/Y aren't available and clientX/Y
// are, calculate pageX/Y - logic taken from jQuery
// Calculate pageX/Y if missing and clientX/Y available
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add a dot to follow the cursor
dot = document.createElement('div');
dot.className = "dot";
dot.innerHTML = "hello world";
dot.style.left = event.pageX + "px";
dot.style.top = event.pageY + "px";
document.body.appendChild(dot);
}
})();
</script>
</body>
</html>
Upvotes: 0