Changing a div attribute using a function? - javascript

I am not sure why my move function, is not changing the style.left or style.top attributes of my 'toy'
Any tips, or general information/links on how to animate a div? I'm pulling my hair out over here. :)
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
//var moveX = math.random() * velocity;
//var moveY = math.random() * velocity;
function init() {
alert("in init fucntion");
ref = document.getElementById("toy");
alert("ref = " + ref.valueOf());
timer = setInterval(move, 50);
}
function move() {
alert("called move");
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
alert("left = " + left.valueOf() + " top = " + top.valueOf());
left += 5;
top += 5;
alert("left =" + left.valueOf() + "top = " + top.valueOf());
ref.style.left += left;
ref.style.top += 5;
alert("ref.style.left = " + ref.style.left.valueOf() + " ref.style.top = " + ref.style.top.valueOf());
ref.style.left = (left + deltaX) % posEnd;
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>

You just need to specify the units the position is in. For example, style.left = 10 won't work - you need style.left = '10px';
Here is a slightly simplified version of your move() function showing this:
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
And a fully working snippet:
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
function init() {
ref = document.getElementById("toy");
timer = setInterval(move, 500);
}
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
</body>
</html>

Related

How to call Wordpress post featured image instead of static url

Trying to add this image hover effect to the featured image in a blog post template in Wordpress. Currently the JS is calling an image URL, but I want the effect to target the featured image of the post template. I think it may be possible using PHP in the JS file but im not sure how to do it, can anyone help me out please?
// options
var options = {
imgSrc : "https://unsplash.it/g/1024/768?image=887",
containerName : "tileContainer",
grid : false,
tileWidth : 80,
tileHeight : 80,
mouseTrail:true
}
// ----------------------------------------------------------
var tileWidth, tileHeight, numTiles, tileHolder, tileContainer;
var directionX, directionY;
var imgOriginalWidth, imgOriginalHeight;
var imgCoverWidth, imgCoverHeight;
var imageLoaded = false;
numTiles=0;
tileWidth = options.tileWidth;
tileHeight = options.tileHeight;
tileContainer = document.getElementsByClassName(options.containerName)[0];
function init(){
if(options.grid == false)tileContainer.className += " noGrid";
//preload image and get original image size, then create tiles
var image = new Image();
image.src = options.imgSrc;
image.onload = function(e){
imageLoaded = true;
imgOriginalWidth = e.currentTarget.width;
imgOriginalHeight = e.currentTarget.height;
createTileHolder();
checkTileNumber();
positionImage();
addListeners();
};
}
function resizeHandler()
{
if(imageLoaded == false)return;
//not working yet
checkTileNumber();
positionImage();
}
function createTileHolder(){
tileHolder = document.createElement('div');
tileHolder.className = "tileHolder";
tileHolder.style.position = "absolute";
tileHolder.style.top = "50%";
tileHolder.style.left = "50%";
tileHolder.style.transform = "translate(-50%, -50%)";
tileContainer.appendChild(tileHolder);
}
function checkTileNumber()
{
tileHolder.style.width = Math.ceil(tileContainer.offsetWidth / tileWidth) * tileWidth + "px";
tileHolder.style.height = Math.ceil(tileContainer.offsetHeight / tileHeight) * tileHeight + "px";
var tilesFitInWindow = Math.ceil(tileContainer.offsetWidth / tileWidth) * Math.ceil(tileContainer.offsetHeight / tileHeight);
if(numTiles < tilesFitInWindow){
for (var i=0, l=tilesFitInWindow-numTiles; i < l; i++){
addTiles();
}
}else if(numTiles > tilesFitInWindow){
for (var i=0, l=numTiles-tilesFitInWindow; i < l; i++){
removeTiles();
}
}
}
function addTiles()
{
var tile = document.createElement('div');
tile.className = "tile";
//maintain aspect ratio
imgCoverWidth = tileContainer.offsetWidth;
imgCoverHeight = tileContainer.offsetHeight;
if(imgOriginalWidth > imgOriginalHeight){
imgCoverHeight = imgOriginalHeight / imgOriginalWidth * imgCoverWidth;
}else{
imgCoverWidth = imgOriginalWidth / imgOriginalHeight * imgCoverHeight;
}
tile.style.background = 'url("'+options.imgSrc+'") no-repeat';
tile.style.backgroundSize = imgCoverWidth + "px " + imgCoverHeight + "px";
tile.style.width = tileWidth + "px";
tile.style.height = tileHeight + "px";
document.querySelectorAll(".tileHolder")[0].appendChild(tile);
tile.addEventListener("mouseover", moveImage);
numTiles++;
}
function removeTiles()
{
var tileToRemove = document.querySelectorAll(".tile")[0];
tileToRemove.removeEventListener("mouseover", moveImage);
TweenMax.killTweensOf(tileToRemove);
tileToRemove.parentNode.removeChild(tileToRemove);
numTiles--;
}
function addListeners(){
if(options.mouseTrail){
document.addEventListener('mousemove', function (event) {
directionX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
directionY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
});
}
}
function positionImage(){
for(var t=0, l=numTiles; t < l; t++)
{
var nowTile = document.querySelectorAll(".tile")[t];
var left = (-nowTile.offsetLeft - (tileHolder.offsetLeft - (tileHolder.offsetWidth/2)));
var top = (-nowTile.offsetTop - (tileHolder.offsetTop - (tileHolder.offsetHeight/2)));
nowTile.style.backgroundPosition = left + "px " + top + "px";
}
}
function resetImage(nowTile){
var left = (-nowTile.offsetLeft - (tileHolder.offsetLeft - (tileHolder.offsetWidth/2)));
var top = (-nowTile.offsetTop - (tileHolder.offsetTop - (tileHolder.offsetHeight/2)));
TweenMax.to(nowTile, 1, {backgroundPosition:left + "px " + top + "px", ease:Power1.easeInOut});
}
function moveImage(e){
var nowTile = e.currentTarget
var minWidth = -tileContainer.offsetWidth+nowTile.offsetWidth;
var minHeight = -tileContainer.offsetHeight+nowTile.offsetHeight;
var nowLeftPos = (-nowTile.offsetLeft - (tileHolder.offsetLeft - (tileHolder.offsetWidth/2)));
var nowTopPos = (-nowTile.offsetTop - (tileHolder.offsetTop - (tileHolder.offsetHeight/2)))
var offset = 60;
var left = nowLeftPos;
var top = nowTopPos;
if(options.mouseTrail){
//direction-aware movement
if(directionX > 0){
left = nowLeftPos + offset;
}else if(directionX < 0){
left = nowLeftPos - offset;
}
if(directionY > 0){
top = nowTopPos + offset;
}else if(directionY < 0){
top = nowTopPos - offset;
}
}else{
//random movement
left = getRandomInt(nowLeftPos - offset , nowLeftPos + offset);
top = getRandomInt(nowTopPos - offset, nowTopPos + offset);
}
// bounds
if(left < minWidth)left=minWidth;
if(left > 0)left=0;
if(top < minHeight)top=minHeight;
if(top > 0)top=0;
//tween
TweenMax.to(nowTile, 1.5, {backgroundPosition:left + "px " + top + "px", ease:Power1.easeOut, onComplete:resetImage, onCompleteParams:[nowTile]});
}
///////////////////////////////////////////////////////////////////
init();
// handle event
//window.addEventListener("optimizedResize", resizeHandler);
////////////////////////UTILS//////////////////////////////////////
//////////////////////////////////////////////////////////////////
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
(function() {
var throttle = function(type, name, obj) {
obj = obj || window;
var running = false;
var func = function() {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
/* init - you can init any event */
throttle("resize", "optimizedResize");
})();
body{background-color:#1A1919;text-align:center;}
.tileContainer{
border:10px solid black;
display:inline-block;
position:relative;
width:1024px;
height:768px;
overflow:hidden;
box-sizing:border-box;
}
.tile{
position:relative;
vertical-align:top;
display:inline-block;
border-right:1px solid rgba(0, 0, 0, 0.5);
border-bottom:1px solid rgba(0, 0, 0, 0.5);
box-sizing:border-box;
}
.tile:after{
content:"";
background-color:#cc1c32;
width:6px;
height:6px;
position:absolute;
top:100%;
right:0px;
transform:translate(50%, -50%);
z-index:2;
line-height:1;
}
/*-- no grid --*/
.noGrid .tile{
border-right:0px solid rgba(0, 0, 0, 0.5);
border-bottom:0px solid rgba(0, 0, 0, 0.5);
}
.noGrid .tile:after{
content:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tileContainer">
</div>

Zoom based on cursor using javascript

I've both tried to solve the problem as well as search StackOverflow for multiple solutions, none that seemed to work properly. I have what appears to be a close but not quite the end result I'm looking for. I'm trying to make it so when the user zooms using the mousewheel, the zoom being based on the cursor's position.
Could someone explain what I'm doing wrong here. Somewhere in my calculation for the image offset im doing something wrong which you'll see when you test it.
// offset image based on cursor position
var width = img_ele.getBoundingClientRect().width;
var height = img_ele.getBoundingClientRect().height;
var x_cursor = window.event.clientX;
var y_cursor = window.event.clientY;
var x = img_ele.offsetLeft;
var y = img_ele.offsetTop;
// Calculate displacement of zooming position.
var dx = x - ((x_cursor - x) * (factor - 1.0));
var dy = y - ((y_cursor - y) * (factor - 1.0));
img_ele.style.left = dx + 'px';
img_ele.style.top = dy + 'px';
Below is the full code. Just change the src image to one of your liking.
<!DOCTYPE html>
<html>
<body>
<div id="container">
<img ondragstart="return false" id="drag-img" src="map.jpg" />
</div>
<input type="button" id="zoomout" class="button" value="Zoom out">
<input type="button" id="zoomin" class="button" value="Zoom in">
<input type="button" id="zoomfit" class="button" value="Zoom fit">
</body>
</html>
<script>
var img_ele = null,
x_cursor = 0,
y_cursor = 0,
x_img_ele = 0,
y_img_ele = 0;
function zoom(factor) {
img_ele = document.getElementById('drag-img');
// Zoom into the image.
var width = img_ele.getBoundingClientRect().width;
var height = img_ele.getBoundingClientRect().height;
img_ele.style.width = (width * factor) + 'px';
img_ele.style.height = (height * factor) + 'px';
// offset image based on cursor position
var width = img_ele.getBoundingClientRect().width;
var height = img_ele.getBoundingClientRect().height;
var x_cursor = window.event.clientX;
var y_cursor = window.event.clientY;
var x = img_ele.offsetLeft;
var y = img_ele.offsetTop;
// Calculate displacement of zooming position.
var dx = x - ((x_cursor - x) * (factor - 1.0));
var dy = y - ((y_cursor - y) * (factor - 1.0));
img_ele.style.left = dx + 'px';
img_ele.style.top = dy + 'px';
console.log('MAP SIZE : ' + width, height);
console.log('MAP TOP/LEFT : ' + x, y, 'NEW:', dx, dy);
console.log('CURSOR : ' + x_cursor, y_cursor);
img_ele = null;
}
function zoom_fit() {
bb_el = document.getElementById('container')
img_el = document.getElementById('drag-img');
var width = bb_el.getBoundingClientRect().width;
var height = bb_el.getBoundingClientRect().height;
img_el.style.width = width + 'px';
img_el.style.height = height + 'px';
img_el.style.left = '0px';
img_el.style.top = '0px';
img_el = null;
}
document.getElementById('zoomout').addEventListener('click', function() {
zoom(0.9);
});
document.getElementById('zoomin').addEventListener('click', function() {
zoom(1.1);
});
document.getElementById('zoomfit').addEventListener('click', function() {
zoom_fit();
});
document.addEventListener('mousewheel', function(event) {
event.preventDefault();
x_cursor = window.event.clientX;
y_cursor = window.event.clientY;
// console.log('ZOOM : ' + 'X:', x_cursor, 'Y:', y_cursor);
if (event.deltaY < 0) {
// console.log('scrolling up');
zoom(1.1);
}
if (event.deltaY > 0) {
// console.log('scrolling down');
zoom(0.9);
}
});
function start_drag() {
img_ele = this;
// console.log('inside start_drag var img_ele set to : ' + this);
x_img_ele = window.event.clientX - document.getElementById('drag-img').offsetLeft;
y_img_ele = window.event.clientY - document.getElementById('drag-img').offsetTop;
// console.log('start_drag : ' + 'x_img_ele:', x_img_ele, 'y_img_ele:', y_img_ele);
}
function stop_drag() {
// console.log('stop drag');
img_ele = null;
}
function while_drag() {
// console.log('while_drag: ', window.event);
var x_cursor = window.event.clientX;
var y_cursor = window.event.clientY;
if (img_ele !== null) {
img_ele.style.left = (x_cursor - x_img_ele) + 'px';
img_ele.style.top = ( window.event.clientY - y_img_ele) + 'px';
// console.log('while_drag: ','x_cursor', x_cursor, 'x_img_ele', x_img_ele, 'y_cursor', y_cursor, 'y_img_ele', y_img_ele,'Image left and top', img_ele.style.left+' - '+img_ele.style.top);
}
}
document.getElementById('drag-img').addEventListener('mousedown', start_drag);
document.getElementById('container').addEventListener('mousemove', while_drag);
document.getElementById('container').addEventListener('mouseup', stop_drag);
function while_drag() {
var x_cursor = window.event.clientX;
var y_cursor = window.event.clientY;
if (img_ele !== null) {
img_ele.style.left = (x_cursor - x_img_ele) + 'px';
img_ele.style.top = ( window.event.clientY - y_img_ele) + 'px';
// console.log(img_ele.style.left+' - '+img_ele.style.top);
}
}
document.getElementById('drag-img').addEventListener('mousedown', start_drag);
document.getElementById('container').addEventListener('mousemove', while_drag);
document.getElementById('container').addEventListener('mouseup', stop_drag);
</script>
<style>
#drag-img {
cursor: move;
position: relative;
width: 400px;
height: 400px;
}
#container {
overflow: hidden;
background: red;
width: 400px;
height: 400px;
}
.button {
width: 80px;
height: 25px;
}
</style>

How to make my random generated div appear inside container div?

HTML
<div id="container">
<div id="wrapper">
</div>
<span id = "waveNum">Current Wave: 0</span>
<input type = "button" value = "Start Game" onclick = "startGame()"></input>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="main.js"></script>
</body>
Javascript
var keyArray = [];
var currentWave = 1;
var player;
var player2;
function initiate(){
player = new createPlayer(150,50,"player1","relative","blue");
player2 = new createPlayer(150,0,"player2","relative","green");
}
function startGame() {
point();
}
function createPlayer(l,t,id,pos,color){
this.speed = 3;
this.width = 25;
this.height = 25;
this.left = l;
this.top = t;
this.id = id;
this.model = $("<div id=" + id + "/>")
.css({"backgroundColor":color,"height":this.height,"width":this.width,
"left":this.left,"top":this.top,"position":pos})
$('#wrapper').append($(this.model));
}
function point(){
leftP = parseInt(Math.random()*970);
topP = parseInt(Math.random()*580);
$points = $("<div class=point/>")
.css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
"top":0,"position":"relative"})
$('#wrapper').append($points)
}
function update(){
//left
if(keyArray[65]){
var newLeft = parseInt(player.left)-player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//right
if(keyArray[68]){
var newLeft = parseInt(player.left)+player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//up
if(keyArray[87]){
var newTop = parseInt(player.top)-player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//down
if(keyArray[83]){
var newTop = parseInt(player.top)+player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//player2
//left
if(keyArray[37]){
var newLeft = parseInt(player2.left)-player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//right
if(keyArray[39]){
var newLeft = parseInt(player2.left)+player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//up
if(keyArray[38]){
var newTop = parseInt(player2.top)-player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
//down
if(keyArray[40]){
var newTop = parseInt(player2.top)+player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
blockade();
requestAnimationFrame(update);
}
function blockade(){
var elemLeft = parseInt($('#wrapper').css('left'));
var elemWidth = parseInt($('#wrapper').css('width'));
var elemTop= parseInt($('#wrapper').css('height'));
//blocks players from moving outside of game
if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
player.left = elemWidth - player.width - 2;
}
if(parseInt(player.top) + player.height >= elemTop){
player.top = elemTop - player.height - 2;
}
if(parseInt(player.top) < 3){
player.top = 3;
}
if(parseInt(player.left) < 3){
player.left = 3;
}
if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
player2.left = elemWidth - player2.width - 2;
}
if(parseInt(player2.top) + player2.height >= elemTop){
player2.top = elemTop - player2.height - 2;
}
if(parseInt(player2.top) < 3){
player2.top = 3;
}
if(parseInt(player2.left) < 3){
player2.left = 3;
}
}
window.onkeydown = function(page){
keyArray[page.keyCode] = page.type === 'keydown';
}
window.onkeyup = function(page){
keyArray[page.keyCode] = page.type === 'keydown'
}
CSS
html, body {margin: 0; height: 100%; overflow: hidden}
#container{
width:80%;
height:60%;
display: block;
text-align:center;
margin: 0 auto;
}
#wrapper{
left:0px;
width:1000px; /* 100% */
height:600px;
border:1px solid lime;
margin:0 auto;
background-color:black;
}
#player1, .point {
float: left;
clear: both;
}
body{
background-color:black;
}
#waveNum{
color:white;
font-size:200%;
}
.point {
overflow: auto;
}
So currently I need my point() function to generate a random div within the <div id="wrapper"> which it is but after a few different spawns, does not stay within the wrapper div eventually. It seems like the container of the point() seems to be shifting down. The more that is generated the more often it appears to the bottom and outside of the container.
Eventually my idea is for all of them to have the same top and left original positions in that way I could use my player and player2 to touch them (match left and top positions) and make them disappear like they are being collected like points. I also cant get them to have the same origin point. I think these issues might be related
You can use to make appeared specific div
z-index: 0
Try adding absolute positioning to your wrapper div and relative positioning to the container div:
#container {
position: relative;
}
#wrapper {
position: absolute;
top: 0;
left: 0;
}
This takes the div out of normal flow from the rest of the document.
See here for more explanations on why this works.

Drawing squares within squares in JS

I am trying to run a script to draw a pattern of squares within squares.
var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;
while(width > 30) {
var divNode = document.createElement("div");
divNode.style.position = "absolute";
divNode.style.marginLeft = left;
divNode.style.marginTop = top;
divNode.style.width = width;
divNode.style.height = height;
divNode.style.background = randomColor();
bodyNode.appendChild(divNode);
width -= 10;
height -= 10;
top += 10;
left += 10;
}
function randomColor()
{
var color = "#";
for(var i =0; i < 6; i++)
{
var number = Math.floor(Math.random() * 10);
color += number;
}
return color;
}
But the properties which get added to the div are:
{
position: absolute;
margin-left: 260px;
width: 350px;
height: 350px;
background: rgb(88, 88, 5);
}
I am trying to achieve this pattern but I get a different pattern as shown in the image below.
What am I missing?
you are missing "px" suffix of Top,Left,Width,Height
See your corrected code here - https://jsfiddle.net/jw2rohr5/
Your corrected code -
var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;
while(width > 30)
{
var divNode = document.createElement("div");
divNode.style.position = "absolute";
divNode.style.marginLeft = left + "px";
divNode.style.marginTop = top + "px";
divNode.style.width = width + "px";
divNode.style.height = height + "px";
divNode.style.background = randomColor();
bodyNode.appendChild(divNode);
width -= 10;
height -= 10;
top += 10;
left += 10;
}
function randomColor()
{
var color = "#";
for(var i =0; i < 6; i++)
{
var number = Math.floor(Math.random() * 10);
color += number;
}
return color;
}
You should give suffix like "%","px" etc..
Try
body{
position: relative;
}
When the content have a position by default(static) the margin of node children not work correctly

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