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()">
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.
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.
If you want to align text to the left in a div, you can use text-align: left .
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With