Home > Net >  How do I move an element in a straight line with a start button in JavaScript?
How do I move an element in a straight line with a start button in JavaScript?

Time:03-29

Basically, let's say I have a box created in HTML/CSS.

<style type='text/css'>
    #box {
      width: 48px;
      height: 48px;
      background-color: black;
      position: absolute;
      left: 280px;
      top: 180px;
    }
  </style>

Style does not matter all that much.

How do I get that box to start on the left side of the page and press a start button that brings it to about the middle of the page WITHOUT having to press a stop button using JavaScript?

I know how to move it with arrow keys, a continuous movement, or a start and then stop button, but not how to just change the position.

CodePudding user response:

Consider the following.

$(function() {
  $("button").click(function() {
    $("#box").animate({
      left: $(window).width() - $("#box").width()
    });
  });
});
#box {
  width: 48px;
  height: 48px;
  background-color: black;
  position: absolute;
  left: 280px;
  top: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"></div>
<button>Go</button>

You can also do this with style without animation.

#box.moved {
  left: calc(100% - 48px);
}
  • Related