Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading