Home > database >  Button not moving
Button not moving

Time:12-12

I want to make the button moves random when clicked But it's not moving when it get clicked

In others this code works but in mine it doesn't

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

I just want to make the button moves That's all

CodePudding user response:

You forgot to add the jquery CDN. Add it and it will work, see here-

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:

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>

  • Related