skip to Main Content

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


  1. You have to subtract the width and height of the button from the bounds of your Math.random() result.

    $(document).ready(function() {
      $('#random-button').on('mouseover', function() {
        $(this).css({
          'top': Math.random() * (window.innerHeight - $(this).outerHeight()) + "px",
          'left': Math.random() * (window.innerWidth - $(this).outerWidth()) + "px"
        });
            console.log($(this).outerHeight())
      })
    });
    

    You may want to add padding and subtract padding as well, so it doesn’t touch the sides, e.g.:

    const pad = 5
    ...
    'top': pad + Math.random() * (window.innerHeight - $(this).outerHeight() - pad) + "px",
    ...
    

    JSFiddle Demo

    Login or Signup to reply.
  2. 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.

    var btn = document.querySelector('#random-button');
    var btnRect = btn.getBoundingClientRect();
    
    btn.addEventListener('mouseover', function() {
      btn.style.top = Math.random() * (window.innerHeight - btnRect.height) + "px";
      btn.style.left = Math.random() * (window.innerWidth - btnRect.width) + "px";
    }, false);
    #random-button {
      position: absolute;
    }
    <button id="random-button">try to click me</button>
    Login or Signup to reply.
  3. Hello I tried to do in this way, see if you satisfies you.

    var btn = document.querySelector('#button');
    var btnRect = btn.getBoundingClientRect();
    
    function RandomInterval(limit) {
      let random = Math.random() * limit;
      return random;
    };
    btn.addEventListener('mouseover', function() {
      btn.style.top = RandomInterval(1) * (window.innerHeight - btnRect.height) + "px";
      btn.style.left = RandomInterval(1) * (window.innerWidth - btnRect.width) + "px";
    }, false);
    #button {
      position: absolute;
    }
    <button id="button">Click here</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search