I wrote a function that should change the position of the button when the cursor approaches the button. Unfortunately the button stays in the same position and doesn't react for cursor except clicking (it does nothing). I saw similar question but that code didn't do what I need.
here is my function and part of the html code with buttons:
function nextPage() {
window.location.href = "yes.html";
}
function moveButton() {
var x = Math.random() * (window.innerWidth - document.getElementById('noButton').offsetWidth);
var y = Math.random() * (window.innerHeight - document.getElementById('noButton').offsetHeight);
document.getElementById('noButton').style.left = `${x}px`;
document.getElementById('noButton').style.top = `${y}px`;
}
<div class="buttons">
<button class="button" id="yesButton" onclick="nextPage()">Yes!</button>
<button class="button" id="noButton" onmouseover="moveButton()" onclick="moveButton()" >No...</button>
</div>
The issue is because the buttons are positioned relatively, so they cannot be moved to any position in the DOM. To do what you need you would need to set position: absolute
.
Also note that your code can be improved by placing the references to the elements in variables which you re-use, instead of making repeated calls to the DOM, which are comparatively very slow.
In addition, it's much better practice to bind your event handlers in JS, and avoid the onX
event attributes in your HTML.
Lastly, the mouseover
event fires once for every pixel that the mouse moves over the element. For this use case mouseenter
is a more appropriate event.
Here's a working example with the above changes implemented:
const yesButton = document.querySelector('#yesButton');
const noButton = document.querySelector('#noButton');
const moveNoButton = () => {
var x = Math.random() * (window.innerWidth - noButton.offsetWidth);
var y = Math.random() * (window.innerHeight - noButton.offsetHeight);
noButton.style.position = 'absolute';
noButton.style.left = `${x}px`;
noButton.style.top = `${y}px`;
}
yesButton.addEventListener('click', () => {
window.location.assign('yes.html');
})
noButton.addEventListener('click', moveNoButton);
noButton.addEventListener('mouseenter', moveNoButton);
<div class="buttons">
<button class="button" id="yesButton">Yes!</button>
<button class="button" id="noButton">No...</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With