Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a div from left to right using javascript

I have div named movingImage that I want to move to the right 50px every time I click a button.

Here's my javascript:

function moving_Image() {
    document.getElementById("movingImage").style.right = "50px";
}

And html:

<h1 id="movingImage"> __________ </h1>
<input type="button" value="click me" onclick="moving_Image()"> 
like image 854
Ayush Mishra Avatar asked Jan 12 '16 15:01

Ayush Mishra


People also ask

How do I move a div from left to right?

If you want to move the div container, make sure the container is set as position "relative." Then adding style="float: right;" will work. If you want to only move the div within that container, then you need to use float="right" on that particular element (object) instead of positioning it with a style.

How do you make a div move?

We have to create an HTML div and add some CSS to the div using a class ball. In CSS, we add some background-color to the body and give some height, width, and color to the div. Now we will add margin-left to the div using JavaScript. So it will move left to right.

How do I move a div text to the left?

If you want to align text to the left in a div, you can use text-align: left .

How do I move a div horizontally?

Answer: Use the CSS margin property If you would like to center align a <div> element horizontally with respect to the parent element you can use the CSS margin property with the value auto for the left and right side, i.e. set the style rule margin: 0 auto; for the div element.


2 Answers

The element you want to move, needs to have the CSS property position: relative;:

I also changed .style.left to .style.right, you will see why:

var imageOffset = 0
function moving_Image() {
  imageOffset += 50
  document.getElementById("movingImage").style.left = imageOffset + "px";
}
#movingImage {
  position: relative;
}
<h1 id="movingImage">__________</h1>
<input type="button" value="click me" onclick="moving_Image()">

If you don't understand something else, please feel free to ask in the comments.

like image 106
CoderPi Avatar answered Sep 27 '22 22:09

CoderPi


use this code instead:

<body>
    <script>
        function movingImage(){
            var movingImage = document.getElementById("movingImage").style.left;
            movingImage.style.left = movingImage.substring(0,MovingImage.length-1) + 50.toString() + "px";
        }
    </script>
    <h1 id="movingImage" style="position: absolute; left: 0px;">Move Image!</h1>
    <input type="button" value="Move, Move Image!" onclick="movingImage()"> 
</body>
like image 39
Kamyar Mirzavaziri Avatar answered Sep 27 '22 22:09

Kamyar Mirzavaziri