Home > Mobile >  Button not moving when click on it using some calculation
Button not moving when click on it using some calculation

Time:12-13

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" >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");
});

CodePudding user response:

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" >Click Me</button>

CodePudding user response:

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" >Click Me</button>

  • Related