Following is my code, there is a small box inside a container box, on click of button, it animates to down and hits the bottom of the container, and then it should rise up from there. But instead it starts flickering rapidly at the same place. Pls tell me how to rise the box once it hits the bottom .
<style>
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<p>
<button id=button>Click Me</button>
</p>
<div id ="myContainer">
<div id ="myAnimation">Fish</div>
</div>
<script>
button =document.getElementById("button");
button.onclick = function() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
/*if (pos == 350) {
clearInterval(id);
}
else*/
if(pos<175)
{
pos++;
elem.style.top = 2*pos + 'px';
elem.style.left = pos + 'px';
}
else
{
pos--;
elem.style.top = pos + 'px';
elem.style.right = pos + 'px';
}
}
}
</script>
Hi made a little solution, you need a switch to made up untill go top, and reveerse to bottom.
button =document.getElementById("button");
button.onclick = function() {
var elem = document.getElementById("myAnimation");
var pos = 0, up=false;
var id = setInterval(frame, 10);
function frame() {
console.log(up, pos);
/*if (pos == 350) {
clearInterval(id);
}
else*/
if(pos<175 && !up)
{
pos++;
if(pos===175) up=true;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
else
{
pos--;
if(pos<=0) up=false;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Related
Question: WHAT THE "myMove()" METHOD DOES? Can you explain it?
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
Click Me
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Quick note: In this answer, I'll be assuming the final question reads:
What does the `myMove()` method do?
Let's first take a look at the variables:
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
The variable elem refers to the red box which is being moved across the canvas (a div element). We set the pos tick variable to 0, which will control how many times we will move the box across the screen. Finally, id refers to a setInterval function which calls the defined frame function every 10 milliseconds.
Now let's look at the function frame:
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
First, it runs a quick check to see if the ticks are done, or in other words, checks to see if the position is 350. Then, if it is, it stops the loop. If it is not, it makes the box move down 1 pixel by setting the position from the top to the pos variable.
All of this code is contained within the myMove() function.
I started to build a simple JavaScript game this morning, I'm trying to figure out how I can control so that the div "box" can't be permitted to move outside of it's parent container? My guess would be with an if statement controlling the offsetLeft and offsetTop?
Javascript here:
(function () {
"use strict";
var box = document.querySelector(".box");
document.addEventListener("keydown", function (event) {
var key = event.key;
var left = box.offsetLeft;
var top = box.offsetTop;
var step = 10;
switch (key) {
case "ArrowUp":
event.preventDefault();
box.style.top = top - step + "px";
break;
case "ArrowDown":
event.preventDefault();
box.style.top = top + step + "px";
break;
case "ArrowLeft":
event.preventDefault();
box.style.left = left - step + "px";
break;
case "ArrowRight":
event.preventDefault();
box.style.left = left + step + "px";
break;
}
console.log(event.key);
});
window.console.log("Sandbox is ready!");
})();
CSS here:
h1 {
text-align: center;
}
h3 {
color: green;
}
.content {
border: 1px solid black;
background-color: #eee;
padding: 2em;
margin: 0 auto;
height: 500px;
width: 800px;
border-radius: 30px;
text-align: center;
}
.box {
position: absolute;
height: 100px;
width: 100px;
background-color: green;
}
HTML below:
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<h1>Simple game</h1>
<div id="content" class="content">
<div class="box"></div>
</div>
<script src="js/main.js"></script>
</body>
</html>
CSS and HTML coded added.
Fiddle here:
https://jsfiddle.net/uwp0s9jz/
Please see the code below.
(function () {
"use strict";
var box = document.querySelector(".box");
var container = document.getElementById('content').getBoundingClientRect()
var paddingSize = 32
document.addEventListener("keydown", function (event) {
var key = event.key;
var left = box.offsetLeft;
var top = box.offsetTop;
var step = 10;
switch (key) {
case "ArrowUp":
event.preventDefault();
if (top > container.top + paddingSize) {
box.style.top = top - step + "px";
}
break;
case "ArrowDown":
event.preventDefault();
if (top < container.height - container.x - paddingSize) {
box.style.top = top + step + "px";
}
break;
case "ArrowLeft":
event.preventDefault();
if (left > container.left + paddingSize) {
box.style.left = left - step + "px";
}
break;
case "ArrowRight":
event.preventDefault();
if (left < container.width - container.y - paddingSize) {
box.style.left = left + step + "px";
}
break;
}
console.log(event.key);
});
})();
Fiddle here
You need to use getBoundingClientRect() to determine if you out of boundary I have updated the top and left for you as a start. You will need to factor in the border-radius if you want.
Fiddle updated: here
Use box parent offsets to determine the position of the box.
fiddle link
(function () {
"use strict";
var box = document.querySelector(".box");
var boxparent = document.querySelector(".content");
var temp;
document.addEventListener("keydown", function (event){
var key = event.key;
var left = box.offsetLeft;
var top = box.offsetTop;
var step = 10;
event.preventDefault();
switch (key) {
case "ArrowUp":
temp = top - step;
if(temp > boxparent.offsetTop)
box.style.top = temp + "px";
break;
case "ArrowDown":
temp = top + step;
if((temp + step + step) < boxparent.offsetHeight)
box.style.top = top + step + "px";
break;
case "ArrowLeft":
temp = left - step;
if(temp > boxparent.offsetLeft)
box.style.left = left - step + "px";
break;
case "ArrowRight":
temp = left - step;
if((left + box.offsetWidth) < boxparent.offsetWidth)
box.style.left = left + step + "px";
break;
}
});
})();
I have an element which I would like to move with the mouse.
var troll = document.getElementById('troll');
troll.addEventListener('dragover', (e) => {
e.preventDefault();
e.target.style.left = e.clientX + 'px';
e.target.style.top = e.clientY + 'px';
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
From left to right and from top to bottom it works OK. Not perfect, since the very first move takes a whole space and it doesn't look smooth. But the main problem is that I can't move from right to left or from bottom to top.
Any help would be appreciated.
You wanna use drag not dragover, and some logic to know where you're going up or down or left or top.
var troll = document.getElementById('troll');
var X,Y = 0;
troll.addEventListener('drag', (e) => {
e.preventDefault();
if (e.clientX > X)
{
e.target.style.left = X + 'px';
}
else if (e.clientX < X)
{
e.target.style.left = X-- + 'px';
}
if (e.clientY > Y)
{
e.target.style.top = Y + 'px';
}
else if (e.clientY < Y)
{
e.target.style.top = Y-- + 'px';
}
X = e.clientX;
Y = e.clientY;
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
My question is how to loop an animation continuously. For example please follow the link below of W3School where a simple box moves from top to bottom and then stops.
http://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3
But what I can't figure out is how to make this box animation non stop i.e. after it goes to the bottom it again moves up to its starting place and the animation continues forever.
You can make these adjustments to the JS:
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 150) { pos = 0; }
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
#container { width: 200px; height: 200px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; }
<div id ="container">
<div id ="animate"></div>
</div>
Delete the clearInterval(id); that stops the animation timer and in its place add this pos = 0; to reposition the box every time it reaches the corner.
Change script to this and it won't stop anymore. runAlready is needed to lock appearing of the second rectangle and pos=0 in the if statement set the coordinate of the rectangle to the top left corner.
var runAlready=false;
function myMove() {
if(!runAlready){
runAlready=true;
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
pos=0;
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
}
The setInterval(frame, 5) tells the program to call the frame() function every 5/1000th of a second. That is what creates the animation.
The clearInterval(id) function tells it to stop the animation.
Take a look at the change I added below. It uses a variable named 'direction' to change the direction of the box. Rather than stopping the animation when the box gets to the LR corner, it reverses the direction and keeps going.
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
var direction = 1;
function frame() {
if (pos == 0){
direction = 1;
} else if(pos == 350){
direction = -1;
}
pos += direction;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
Why when the ball is placed relative positioning when you press the mouse it bounces? Absolute positioning is when this doesn't happen.
var ball = document.querySelector('.ball');
ball.onmousedown = function(event) {
var shiftX = event.pageX - getCoords(this).left,
shiftY = event.pageY - getCoords(this).top;
this.style.position = 'relative';
this.zIndex = 10000;
function move(event) {
this.style.left = event.pageX - shiftX + 'px';
this.style.top = event.pageY - shiftY + 'px';
}
move.call(this, event);
document.onmousemove = function(event) {
move.call(ball, event);
};
this.onmouseup = function(event) {
document.onmousemove = this.onmouseup = null;
};
return false;
};
ball.ondragstart = function() {
return false;
};
function getCoords(elem) {
var box = elem.getBoundingClientRect();
return {
top: box.top + window.pageYOffset,
left: box.left + window.pageXOffset
};
}
body {
margin: 50px;
}
img {
cursor: pointer;
}
<img class="ball" src="https://js.cx/clipart/ball.svg" alt="" />
I guess it's because of the padding of the body element. Please explain.
it seems i found answer
Implementing drag and drop on relatively positioned elements in JavaScript
and as it says, with relative position, your element contain offset of all objects in his parent-tag
and parent's margin and padding too
so when you try to get elemtn's position, you should count it's real offset in parent, see in my code example work with count index
<html>
<body>
<div id=obj1 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj2 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<div id=obj3 style="width:100px; height:100px; background:#000; position:relative; " ></div>
<script>
var dragObj, count=0;
function set_drag_drop(obj)
{
if(count>0){
// count margins and divs offset
// body{ margin:10px; }
// height:100px;
obj.adx = 10;
obj.ady = 10 + (count*100)
}else{
obj.adx = 0;
obj.ady = 0;
}
count++;
obj.onmousedown = function(e)
{
var rect = obj.getBoundingClientRect();
obj.dx = rect.left - e.clientX;
obj.dy = rect.top - e.clientY;
obj.isDown = true;
dragObj = this;
}
obj.onmouseup = function(e)
{
obj.isDown = false;
}
document.onmousemove = function(e)
{
if(dragObj && dragObj.isDown)
{
dragObj.style.left = e.pageX -dragObj.adx+ dragObj.dx +"px";
dragObj.style.top = e.pageY -dragObj.ady+ dragObj.dy + "px";
}
}
}
set_drag_drop(document.getElementById("obj1"));
set_drag_drop(document.getElementById("obj2"));
set_drag_drop(document.getElementById("obj3"));
</script>
</html>