skip to Main Content

When clicking on the button, I am assigning random margins from the top and left to it, so it can move but it’s not working.

HTML

<button id="bouncing" class="btn btn-primary">Click Me</button>

JS

var button = document.querySelector("button");

button.addEventListener("click", function() {
  var changeTop = (Math.random() * ($(window).height() - $("button").height()));
  var changeLeft = (Math.random() * ($(window).width() - $("button").width()));
  $("button").css("margin-top", changeTop + "px");
  $("button").css("margin-left", changeLeft + "px");
});

2

Answers


  1. You forgot to add jquery. Add it via CDN or install it and it will work, like this-

    var button = document.querySelector("button");
    
    button.addEventListener("click", function() {
      var changeTop = (Math.random() * ($(window).height() - $("button").height()));
      var changeLeft = (Math.random() * ($(window).width() - $("button").width()));
      $("button").css("margin-top", changeTop + "px");
      $("button").css("margin-left", changeLeft + "px");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="bouncing" class="btn btn-primary">Click Me</button>
    Login or Signup to reply.
  2. This works fine.You probably didn’t include jQuery in your code

    var button = document.querySelector("button");
    
    button.addEventListener("click", function() {
      var changeTop = (Math.random() * ($(window).height() - $("button").height()));
      var changeLeft = (Math.random() * ($(window).width() - $("button").width()));
      $("button").css("margin-top", changeTop + "px");
      $("button").css("margin-left", changeLeft + "px");
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="bouncing" class="btn btn-primary">Click Me</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search