Clearinterval method is unable to clear Rotation javascript animation - javascript

I am new to JS and i am trying to move object from left to right while spinning clockwise, here i applied setinterval for movement animation from left to right and also for rotation. I am able to clearinterval Movement from left to right but unable to clearinterval my Rotation i don't know why please if you can take a look
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
e.style.left = (eLeftPos + s) + 'px';
function rot() {
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
}
var rotID = setInterval(rot, 1000)
var leftPos = (eLeftPos + s) >= 1000
if ((eLeftPos + s) >= 1000) {
clearInterval(rotID)
console.log(rotID)
}
if ((eLeftPos + s) >= 1000) {
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>

You're unable to clear the interval from the rotation, because you start a new setInterval every time the first (movement) interval executes. You'll have a new rotation interval every 1000ms. Why not just move and rotate within the same setInterval callback and then theres only 1 to cancel:
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
var leftPos = (eLeftPos + s); // new left pos
e.style.left = leftPos + 'px';
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
if (leftPos >= 100) { // made 100 just to show the effect quicker
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>

Related

Not able to get the input text box editable inside animated javascript

I have added the code snippet over here. I was trying to do some random exercise. Can someone look why my textbox is not editable. There is falling leaf animation over here. Along with I have added one textbox on top of it. But currently I am not able to add any text to the textbox.
I am just adding more text in order to overcome the error message that the post is mostly having code and not much explanation.
var LeafScene = function(el) {
this.viewport = el;
this.world = document.createElement('div');
this.leaves = [];
this.options = {
numLeaves: 20,
wind: {
magnitude: 1.2,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 0
},
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
// animation helper
this.timer = 0;
this._resetLeaf = function(leaf) {
// place leaf towards the top left
leaf.x = this.width * 2 - Math.random()*this.width*1.75;
leaf.y = -10;
leaf.z = Math.random()*200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = Math.random()*this.height/2;
}
// at the start, the leaf can be anywhere
if (this.timer == 0) {
leaf.y = Math.random()*this.height;
}
// Choose axis of rotation.
// If axis is not X, chose a random static x-rotation for greater variability
leaf.rotation.speed = Math.random()*10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = 'X';
} else if (randomAxis > 0.25) {
leaf.rotation.axis = 'Y';
leaf.rotation.x = Math.random()*180 + 90;
} else {
leaf.rotation.axis = 'Z';
leaf.rotation.x = Math.random()*360 - 180;
// looks weird if the rotation is too fast around this axis
leaf.rotation.speed = Math.random()*3;
}
// random speed
leaf.xSpeedVariation = Math.random() * 0.8 - 0.4;
leaf.ySpeed = Math.random() + 1.5;
return leaf;
}
this._updateLeaf = function(leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = 'translateX( ' + leaf.x + 'px ) translateY( ' + leaf.y + 'px ) translateZ( ' + leaf.z + 'px ) rotate' + leaf.rotation.axis + '( ' + leaf.rotation.value + 'deg )';
if (leaf.rotation.axis !== 'X') {
t += ' rotateX(' + leaf.rotation.x + 'deg)';
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
// reset if out of view
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
}
this._updateWind = function() {
// wind follows a sine curve: asin(b*time + c) + a
// where a = wind magnitude as a function of leaf position, b = wind.duration, c = offset
// wind duration should be related to wind magnitude, e.g. higher windspeed means longer gust duration
if (this.timer === 0 || this.timer > (this.options.wind.start + this.options.wind.duration)) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration = this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function(t, y) {
// should go from full wind speed at the top, to 1/2 speed at the bottom, using leaf Y
var a = this.magnitude/2 * (screenHeight - 2*y/3)/screenHeight;
return a * Math.sin(2*Math.PI/this.duration * t + (3 * Math.PI/2)) + a;
}
}
}
}
LeafScene.prototype.init = function() {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement('div'),
x: 0,
y: 0,
z: 0,
rotation: {
axis: 'X',
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0,
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = 'leaf-scene';
this.viewport.appendChild(this.world);
// set perspective
this.world.style.webkitPerspective = "400px";
this.world.style.MozPerspective = "400px";
this.world.style.oPerspective = "400px";
this.world.style.perspective = "400px";
// reset window height/width on resize
var self = this;
window.onresize = function(event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
}
LeafScene.prototype.render = function() {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
}
// start up leaf scene
var leafContainer = document.querySelector('.falling-leaves'),
leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
body, html {
height: 100%;
}
form {
width: 600px;
margin: 0px auto;
padding: 15px;
}
input[type=text] {
display: block;
padding: 10px;
box-sizing: border-box;
font-size: x-large;
margin-top: 25%;
}
input[type=text] {
width: 100%;
margin-bottom: 15px;
}
.falling-leaves {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 100%;
max-width: 880px;
max-height: 880px; /* image is only 880x880 */
transform: translate(-50%, 0);
border: 20px solid #fff;
border-radius: 50px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/sidebar-bg.png) no-repeat center center;
background-size: cover;
overflow: hidden;
}
.leaf-scene {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
transform-style: preserve-3d;
}
.leaf-scene div {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/leaf.svg) no-repeat;
background-size: 100%;
transform-style: preserve-3d;
backface-visibility: visible;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
</head>
<body>
<div class="falling-leaves">
<form id="frmContact">
<input type="text" id="txtName" name="txtName" placeholder="Text goes here">
</form>
</div>
<script src="script/script.js"></script>
</body>
</html>

how do I make this element move backwards?

how do I stop the following interval and make the alien move backwards when it reaches 700px? I know I can do this with CSS but I want to do this strictly with JS. I don't understand how to stop the interval once it reaches the 700px left...
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = left + 2 + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
clearInterval(interval);
alien.style.left = left - 10 + "px";
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
Any help?
Introduce a speed variable which will switch from 2 to -2 when it reaches the right limit. You should then do the same at the left side, and switch the speed from -2 to 2 again.
As you want to keep moving, the stop function is no longer needed.
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
let speed = 2;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) speed = -2;
else if (left <= 0) speed = 2;
alien.style.left = left + speed + "px";
}
interval = setInterval(flow, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
To move your element you use left + 2 so it always is moving to one direction.
So when reaching 700px mark you should reverse it to be left - 2 until it's 0.
I have modified your code adding currentDirection variable
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
var currentDirection = 1;
var hasMoved = false;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = (left + 2 * currentDirection) + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
currentDirection = -1;
} else if (left < 0) {
currentDirection = 1;
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
background: gold;
height: 20px;
width: 20px;
}
.alien {
background: red;
height: 20px;
width: 20px;
position: absolute;
}
<div class="game">
</div>

sin and cos animations on a curved line with javascript and CSS

I am trying to use sin and cos to animate a CSS image to move on this shape. Can not make the CSS image to move on that curved bezier line.
Can someone assist on how to use sin or cos in so, if a CSS object added, it would move smoothly along such a line?
Here is the code that I tried to make the yellow circle to move on that line with sin and cos math in javascript.
Thanks
var field = document.getElementById("field");
var ball = document.getElementById("ball");
var ball2 = document.getElementById("ball2");
var maxX = field.clientWidth - ball.offsetWidth;
var maxY = field.clientHeight - ball.offsetHeight;
var duration = 5; // seconds
var gridSize = 50; // pixels
var start = null;
function step(timestamp) {
var progress, x, y, y2;
if (start === null)
start = timestamp;
progress = (timestamp - start) / duration / 1000; // percent
x = progress * maxX / gridSize; // x = ƒ(t)
y = 2 * Math.sin(x); // y = ƒ(x)
y2 = 2 * Math.cos(x);
ball.style.left = ball2.style.left = Math.min(maxX, gridSize * x)
+ "px";
ball.style.bottom = maxY / 2 + (gridSize * y) + "px";
ball2.style.bottom = maxY / 2 + (gridSize * y2) + "px";
if (progress >= 1)
start = null; // reset to start position
requestAnimationFrame(step);
}
requestAnimationFrame(step);
#field {
position: absolute;
height: 300px;
width: 300px;
z-index: 50;
top: 20px;
left: 20px;
}
#ball {
position: absolute;
left: 0;
bottom: 50%;
width: 40px;
background: yellow;
z-index: 5;
height: 40px;
border-radius: 200px;
}
#ball2 {
position: absolute;
left: 0;
bottom: 50%;
width: 20px;
height: 20px;
/*background: silver;*/
border-radius: 100px;
}
<div id="field">
<div id="ball"></div>
<div id="ball2"></div>
</div>
requestAnimationFrame calls the given function exactly ONCE
to animate, you need to call requestAnimationFrame within that given function, usually calling the function itself (though more complex animations may call something else, it doesn't matter)
The main point being, you need to call requestAnimationFrame for each frame you want to animate
var field = document.getElementById("field");
var ball = document.getElementById("ball");
var ball2 = document.getElementById("ball2");
var maxX = field.clientWidth - ball.offsetWidth;
var maxY = field.clientHeight - ball.offsetHeight;
var duration = 5; // seconds
var gridSize = 40; // pixels
var start = null;
function step(timestamp) {
var progress, x, y, y2;
if (start === null)
start = timestamp;
progress = (timestamp - start) / duration / 1000; // percent
x = progress * maxX / gridSize; // x = ƒ(t)
y = -2 * Math.cos(x); // y = ƒ(x)
y2 = 2 * Math.cos(x);
ball.style.left = ball2.style.left = Math.min(maxX, gridSize * x) +
"px";
ball.style.bottom = maxY / 2 + (gridSize * y) + "px";
ball2.style.bottom = maxY / 2 + (gridSize * y2) + "px";
if (progress >= 1)
start = null; // reset to start position
requestAnimationFrame(step);
}
requestAnimationFrame(step);
#field {
position: absolute;
height: 300px;
width: 300px;
z-index: 50;
top: 20px;
left: 20px;
}
#ball {
position: absolute;
left: 0;
bottom: 50%;
width: 40px;
background: yellow;
height: 40px;
border-radius: 200px;
}
#ball2 {
position: absolute;
left: 0;
bottom: 50%;
width: 20px;
height: 20px;
background: silver;
border-radius: 100px;
}
<div id="field">
<div id="ball"></div>
<div id="ball2"></div>
</div>

trail without a canvas

I've created the following code and I would like to have a trail following the dropped ball.
JSFiddle: https://jsfiddle.net/uj896hmq/72/
Code
var generateGame = function(){
var string = "";
var discAmount = 0;
for(var x = 0; x < 13; x++){
discAmount++;
string += "<div class='row'>";
for(var y = 1; y <= discAmount; y++){
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function(){
startGame();
});
var startGame = function(){
var $board = $('.board .wrapper'),
$el = $(".falling");
var currentRow = 0,
path = generatePath();
setInterval(function(){
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow]),
top = getPosition.position().top,
left = getPosition.position().left;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}, 500);
}
var generatePath = function(){
var path = [0];
for(var x = 1; x < 13; x++){
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(generatePath());
Point is I have no idea how I would achieve this with regular javascript and or jQuery, I thought of maybe placing a lot of divs at the position of the ball but that didn't seem proper.
Anyone has any ideas?
You can use SVG to dynamically add lines to the HTML without canvas. I've created a crude example that you can refer to. Basically it is just some calculations to position the lines.
var generateGame = function() {
var string = "";
var discAmount = 0;
for (var x = 0; x < 13; x++) {
discAmount++;
string += "<div class='row'>";
for (var y = 1; y <= discAmount; y++) {
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function() {
startGame();
});
var startGame = function() {
var $board = $('.board .wrapper'),
$el = $(".falling"),
$trail = $('.trail'),
$prevDisc = null;
var currentRow = 0,
path = generatePath();
$trail.empty();
setInterval(function() {
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow])
if (getPosition.length > 0) {
var top = getPosition.position().top,
left = getPosition.position().left;
if ($prevDisc) {
var isLeft = left < $prevDisc.position().left;
drawPath($prevDisc.position().left, currentRow - 1, isLeft);
}
$prevDisc = getPosition;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}
}, 500);
}
var generatePath = function() {
var path = [0];
for (var x = 1; x < 13; x++) {
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function drawPath(xPos, prevRow, isLeft) {
if (prevRow >= 0) {
var svgTopOffSet = 12;
var svgHeight = 22;
var svgWidth = 22;
var $trail = $('.trail');
var $newTrail = $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'));
$newTrail.attr({
x: xPos,
y: prevRow * svgHeight + svgTopOffSet
});
var $line = $(document.createElementNS('http://www.w3.org/2000/svg', 'line'));
$line.attr({
x1: svgWidth / 2,
y1: 0,
x2: isLeft ? 0 : svgWidth,
y2: svgWidth,
style: 'stroke:orange;stroke-width:3'
});
$newTrail.append($line);
$trail.append($newTrail);
}
}
body {
background: rgb(26, 30, 35);
}
.board {
width: 500px;
height: 300px;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.row {
display: flex;
justify-content: center;
}
.row .disc {
height: 6px;
width: 6px;
border-radius: 50%;
background: gray;
margin: 8px;
}
.wrapper .falling {
position: absolute;
height: 11px;
width: 11px;
border-radius: 50%;
background: orange;
transform: translate(50%, 50%);
z-index: 1;
}
.wrapper {
position: relative;
}
.trail {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
line { stroke-dasharray: 25; stroke-dashoffset: 25; animation: offset 0.5s linear forwards; }
#keyframes offset {
to {
stroke-dashoffset: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='board'>
<div class='wrapper'>
<svg class="trail">
</svg>
</div>
<button>
test game
</button>
</div>

Drag an HTML box and make another box follow it with JavaScript

I am trying to create something like drag a box (Hello World) to any location, and the second box (Follow World) will follow slowly.
In the code below, the drag box is fine, but the follow box will not follow properly. Also, the drag box cannot drop.
function startDrag(e) {
// determine event object
if (!e) {
var e = window.event;
}
// IE uses srcElement, others use target
var targ = e.target ? e.target : e.srcElement;
if (targ.className != 'dragme') {
return
};
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// assign default values for top and left properties
if (!targ.style.left) {
targ.style.left = '0px'
};
if (!targ.style.top) {
targ.style.top = '0px'
};
// calculate integer values for top and left
// properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
// move div element
document.onmousemove = dragDiv;
return false;
}
function dragDiv(e) {
if (!drag) {
return
};
if (!e) {
var e = window.event
};
var targ = e.target ? e.target : e.srcElement;
// move div element
targ.style.left = coordX + e.clientX - offsetX + 'px';
targ.style.top = coordY + e.clientY - offsetY + 'px';
return false;
}
function stopDrag() {
timer();
drag = false;
}
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function disp() {
var step = 1;
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
var ty = document.getElementById('draggable').offsetTop;
var ty = document.getElementById('draggable').offsetLeft;
if (y < ty) {
y = y + step;
document.getElementById('followme').style.top = y + "px"; // vertical movment
} else {
if (x < tx) {
x = x + step;
document.getElementById('followme').style.left = x + "px"; // horizontal movment
}
}
}
function timer() {
disp();
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML = "X: " + tx + " Y : " + ty
my_time = setTimeout('timer()', 10);
}
.dragme {
position: relative;
width: 60px;
height: 80px;
cursor: move;
}
.followme {
position: relative;
width: 60px;
height: 80px;
}
#draggable {
background-color: #ccc;
border: 1px solid #000;
}
#followme {
background-color: #ccc;
border: 1px solid #000;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and drop</title>
</head>
<body>
<div id='msg'></div>
<div id="draggable" class="dragme">"Hello World!"</div>
<div id="followme" class="followme">"Follow World!"</div>
Fix yours disp and timer functions to this:
function disp()
{
var step = 1;
// in dragDiv() you modifying style.left/style.top properties, not offsetTop/offsetLeft
var x = parseInt(document.getElementById('followme').style.left) || 0;
var y = parseInt(document.getElementById('followme').style.top) || 0;
var tx = parseInt(document.getElementById('draggable').style.left) || 0;
var ty = parseInt(document.getElementById('draggable').style.top) || 0;
// properly calculate offset
var dx = ((dx = tx - x) == 0) ? 0 : Math.abs(dx) / dx;
var dy = ((dy = ty - y) == 0) ? 0 : Math.abs(dy) / dy;
document.getElementById('followme').style.left = (x + dx * step) + "px"; // horisontal movment
document.getElementById('followme').style.top = (y + dy * step) + "px"; // vertical movment
}
function timer()
{
disp();
var y=document.getElementById('followme').offsetTop;
var x=document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML="X: " + x + " Y : " + y; // typo was here
my_time = setTimeout(function () {
clearTimeout(my_time); // need to clear timeout or it'll be adding each time 'Hello world' clicked
timer();
},10);
}
In the following snippet, the pink box is draggable and the blue box follows it around. You can change pixelsPerSecond to adjust the speed of movement.
function message(s) {
document.getElementById('messageContainer').innerHTML = s;
}
window.onload = function () {
var pixelsPerSecond = 80,
drag = document.getElementById('drag'),
follow = document.getElementById('follow'),
wrapper = document.getElementById('wrapper'),
messageContainer = document.getElementById('messageContainer'),
leftMax,
topMax;
function setBoundaries() {
leftMax = wrapper.offsetWidth - drag.offsetWidth;
topMax = wrapper.offsetHeight - drag.offsetHeight;
drag.style.left = Math.min(drag.offsetLeft, leftMax) + 'px';
drag.style.top = Math.min(drag.offsetTop, topMax) + 'px';
}
setBoundaries();
window.onresize = setBoundaries;
[drag, follow, messageContainer].forEach(function (element) {
element.className += ' unselectable';
element.ondragstart = element.onselectstart = function (event) {
event.preventDefault();
};
});
var start = Date.now();
drag.onmousedown = function (event) {
event = event || window.event;
var x0 = event.pageX || event.clientX,
y0 = event.pageY || event.clientY,
left0 = drag.offsetLeft,
top0 = drag.offsetTop;
window.onmousemove = function (event) {
var x = event.pageX || event.clientX,
y = event.pageY || event.clientY;
drag.style.left = Math.max(0, Math.min(left0 + x - x0, leftMax)) + 'px';
drag.style.top = Math.max(0, Math.min(top0 + y - y0, topMax)) + 'px';
};
window.onmouseup = function () {
window.onmousemove = window.onmouseup = undefined;
};
};
follow.x = follow.offsetLeft;
follow.y = follow.offsetTop;
function update() {
var elapsed = Date.now() - start;
if (elapsed === 0) {
window.requestAnimationFrame(update);
return;
}
var x1 = drag.offsetLeft,
y1 = drag.offsetTop + (drag.offsetTop + drag.offsetHeight <= topMax ?
drag.offsetHeight : -drag.offsetHeight),
x0 = follow.x,
y0 = follow.y,
dx = x1 - x0,
dy = y1 - y0,
distance = Math.sqrt(dx*dx + dy*dy),
angle = Math.atan2(dy, dx),
dd = Math.min(distance, pixelsPerSecond * elapsed / 1000);
message('x: ' + x1 + ', y: ' + y1);
follow.x += Math.cos(angle) * dd;
follow.style.left = follow.x + 'px';
follow.y += Math.sin(angle) * dd;
follow.style.top = follow.y + 'px';
start = Date.now();
window.requestAnimationFrame(update);
}
window.requestAnimationFrame(update);
};
#wrapper {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #eee;
font-family: sans-serif;
text-align: center;
}
.unselectable {
-webkit-user-select: none;
-khtml-user-drag: none;
-khtml-user-select: none;
-moz-user-select: none;
-moz-user-select: -moz-none;
-ms-user-select: none;
user-select: none;
}
#messageContainer {
position: absolute;
left: 80px;
top: 50px;
font-size: 36px;
color: #aaa;
cursor: default;
}
.box {
position: absolute;
width: 60px;
height: 80px;
}
.label {
margin: 30px auto;
font-size: 14px;
}
#drag {
left: 100px;
top: 120px;
background: #f0dddb;
border: 2px solid #deb7bb;
cursor: move;
}
#follow {
left: 0;
top: 0;
background-color: #ddebf3;
border: 2px solid #bfd5e1;
cursor: default;
}
<div id="wrapper">
<div id="messageContainer"></div>
<div class="box" id="follow"> <div class="label">it follows</div> </div>
<div class="box" id="drag"> <div class="label">drag me</div> </div>

Categories

Resources