I have a JS/jQuery code that has 2 buttons, and when the cursor hovers over one of them, it moves to a random position.
What can I do to not allow the button to move out of the viewport, so the "user" doesn’t have to scroll to find the button after it moves?
I tried setting overflow to hidden, but as I expected, it didn’t prohibit the button to appear outside of the area, the scroll just stopped showing.
I guess I probably have to set a limit to the locations where the button can move to, but I have no idea on how to do it.
Here’s the script which generates the random position of the button on hover:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#random-button').on('mouseover', function() {
$(this).css({
'top': Math.random() * window.innerHeight + "px",
'left': Math.random() * window.innerWidth + "px"
});
})
});
</script>
3
Answers
You have to subtract the width and height of the button from the bounds of your
Math.random()
result.You may want to add padding and subtract padding as well, so it doesn’t touch the sides, e.g.:
JSFiddle Demo
Well first I’ll say that for what you want, you don’t need jQuery at all. That hundreds of kilobytes downloaded just so you can select an element. JavaScript has this built in, no libraries needed.
So, basically you will need to measure the window size and then pick a semi-random value from 0 to whatever that size is.
Hello I tried to do in this way, see if you satisfies you.