How can I diagonally move an element using Javascript? - javascript

I've created an article with a red background, you can move it using WASD keys, however, the real trouble comes in when I try to create a diagonal movement (for ex, if W and D are pressed, the article should go to the top right corner), it doesn't seem to work:
document.body.addEventListener('keypress', function(event) {
var oldLeft = getComputedStyle(document.body).left,
newLeft;
var oldTop = getComputedStyle(document.body).top,
newTop;
oldLeft = parseInt(oldLeft, 10);
oldTop = parseInt(oldTop, 10);
console.log(event);
if ( event.key == 'a') {
newLeft = oldLeft - 10;
}
else if ( event.key == 'd') {
newLeft = oldLeft + 10;
}
else if (event.key == 'w') {
newTop = oldTop - 10;
}
else if (event.key == 's') {
newTop = oldTop + 10;
}
//HERE
if ((event.key =='w') || (event.key == 'd')) {
newLeft = oldLeft + 10;
newTop = oldTop - 10;
}
document.body.style.left = newLeft + 'px';
document.body.style.top = newTop + 'px';
});
article {
width: 33.75em;
padding: 1.5em;
margin: 0 auto;
background: #f6be00;
/*border: 4px solid white;*/
border-radius: 1.25em;
position: relative;
left: 0;
}
body {
position: relative;
background: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/styles.css">
<title>Javascript</title>
</head>
<body>
<article class="article">
<ul id="browser">
</ul>
<ul id="user">
</ul>
</article>
<script src="javascript/main.js"></script>
</body>
</html>
It goes to the top right corner but that happens even when I don't press W and D at the same time.

Use keydown events to collect keys to an array, and keyup events to wait until all keys are un-pressed to execute the changes:
var clicked = {};
document.body.addEventListener('keydown', function(event) {
clicked[event.key] = false; // collect keys an init as false
});
document.body.addEventListener('keyup', function(event) {
clicked[event.key] = true; // change keys to true
// if not all keys are true don't execute anything
if (!Object.values(clicked).every(Boolean)) return;
var left = parseInt(getComputedStyle(document.body).left, 10);
var top = parseInt(getComputedStyle(document.body).top, 10);
// get the clicked keys
const keys = Object.keys(clicked);
// iterate them and change the values
keys.forEach(function(key) {
switch (key) {
case 'a':
{
left -= 10;
break;
}
case 'd':
{
left += 10;
break;
}
case 'w':
{
top -= 10;
break;
}
case 's':
{
top += 10;
break;
}
}
});
clicked = {}; // clear clicked keys
document.body.style.left = left + 'px';
document.body.style.top = top + 'px';
});
article {
width: 33.75em;
padding: 1.5em;
margin: 0 auto;
background: #f6be00;
/*border: 4px solid white;*/
border-radius: 1.25em;
position: relative;
left: 0;
}
body {
position: relative;
background: red;
}
<article class="article"></article>

Related

How to drag images in JS

I have a large background image and some much smaller images for the user to drag around on the background. I need this to be efficient in terms of performance, so i'm trying to avoid libraries. I'm fine with drag 'n' drop if it work's well, but im trying to get drag.
Im pretty much trying to do this. But after 8 years there must be a cleaner way to do this right?
I currently have a drag 'n' drop system that almost works, but when i drop the smaller images, they are just a little off and it's very annoying. Is there a way to fix my code, or do i need to take a whole different approach?
This is my code so far:
var draggedPoint;
function dragStart(event) {
draggedPoint = event.target; // my global var
}
function drop(event) {
event.preventDefault();
let xDiff = draggedPoint.x - event.pageX;
let yDiff = draggedPoint.y - event.pageY;
let left = draggedPoint.style.marginLeft; // get margins
let top = draggedPoint.style.marginTop;
let leftNum = Number(left.substring(0, left.length - 2)); // cut off px from the end
let topNum = Number(top.substring(0, top.length - 2));
let newLeft = leftNum - xDiff + "px" // count new margins and put px back to the end
let newTop = topNum - yDiff + "px"
draggedPoint.style.marginLeft = newLeft;
draggedPoint.style.marginTop = newTop;
}
function allowDrop(event) {
event.preventDefault();
}
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.style.marginLeft = `${Math.floor(Math.random() * 900)}px`
sensor.style.marginTop = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = function() {
sensorClick(logs[i].id)
};
sensor.addEventListener("dragstart", dragStart, null);
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
<!-- my html: -->
<style>
.map {
width: 900px;
height: 500px;
align-content: center;
margin: 150px auto 150px auto;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<div class="map" onDrop="drop(event)" ondragover="allowDrop(event)">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false">
<div>
With the answers from here and some time i was able to get a smooth drag and click with pure js.
Here is a JSFiddle to see it in action.
let maxLeft;
let maxTop;
const minLeft = 0;
const minTop = 0;
let timeDelta;
let imgs = [
"https://upload.wikimedia.org/wikipedia/commons/6/67/Orange_juice_1_edit1.jpg",
"https://upload.wikimedia.org/wikipedia/commons/f/ff/Solid_blue.svg",
"https://upload.wikimedia.org/wikipedia/commons/b/b4/Litoria_infrafrenata_-_Julatten.jpg"
]
var originalX;
var originalY;
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function sensorClick () {
if (Date.now() - timeDelta < 150) { // check that we didn't drag
createPopup(this);
}
}
// create a popup when we click
function createPopup(parent) {
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
let popup = document.createElement("div");
popup.id = "popup";
popup.className = "popup";
popup.style.top = parent.y - 110 + "px";
popup.style.left = parent.x - 75 + "px";
let text = document.createElement("span");
text.textContent = parent.id;
popup.appendChild(text);
var map = document.getElementsByClassName("map")[0];
map.appendChild(popup);
}
// when our base is loaded
function baseOnLoad() {
var map = document.getElementsByClassName("map")[0];
let base = document.getElementsByClassName("base")[0];
maxLeft = base.width - 50;
maxTop = base.height - 50;
/* my smaller images: */
for (let i = 0; i < 6; i++) {
let sensor = document.createElement("img");
sensor.src = imgs[i % imgs.length];
sensor.alt = i;
sensor.id = i;
sensor.draggable = true;
sensor.classList.add("sensor");
sensor.classList.add("dragme");
sensor.style.left = `${Math.floor(Math.random() * 900)}px`
sensor.style.top = `${Math.floor(Math.random() * 500)}px`
sensor.onclick = sensorClick;
let parent = document.getElementsByClassName("map")[0];
parent.appendChild(sensor);
}
}
function startDrag(e) {
timeDelta = Date.now(); // get current millis
// determine event object
if (!e) var e = window.event;
// prevent default event
if(e.preventDefault) e.preventDefault();
// IE uses srcElement, others use target
targ = e.target ? e.target : e.srcElement;
originalX = targ.style.left;
originalY = targ.style.top;
// check that this is a draggable element
if (!targ.classList.contains('dragme')) return;
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// calculate integer values for top and left properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
document.onmousemove = dragDiv; // move div element
return false; // prevent default event
}
function dragDiv(e) {
if (!drag) return;
if (!e) var e = window.event;
// move div element and check for borders
let newLeft = coordX + e.clientX - offsetX;
if (newLeft < maxLeft && newLeft > minLeft) targ.style.left = newLeft + 'px'
let newTop = coordY + e.clientY - offsetY;
if (newTop < maxTop && newTop > minTop) targ.style.top = newTop + 'px'
return false; // prevent default event
}
function stopDrag() {
if (typeof drag == "undefined") return;
if (drag) {
if (Date.now() - timeDelta > 150) { // we dragged
let p = document.getElementById("popup");
if (p) {
p.parentNode.removeChild(p);
}
} else {
targ.style.left = originalX;
targ.style.top = originalY;
}
}
drag = false;
}
.map {
width: 900px;
height: 500px;
margin: 50px
position: relative;
}
.map .base {
position: absolute;
width: inherit;
height: inherit;
}
.map .sensor {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
}
.dragme {
cursor: move;
left: 0px;
top: 0px;
}
.popup {
position: absolute;
display: inline-block;
width: 200px;
height: 100px;
background-color: #9FC990;
border-radius: 10%;
}
.popup::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -10px;
border-width: 10px;
border-style: solid;
border-color: #9FC990 transparent transparent transparent;
}
.popup span {
width: 90%;
margin: 10px;
display: inline-block;
text-align: center;
}
<div class="map" width="950px" height="500px">
<img src='https://upload.wikimedia.org/wikipedia/commons/f/f7/Plan-Oum-el-Awamid.jpg' alt="pohja" class="base" draggable="false" onload="baseOnLoad()">
<div>

Moving the square using mousedown event on front end

Practicing some front end stuff just by using addEventListener. What I am trying to achieve here is that : click the square and then hold the mouse while moving the square to another place on the page and stop moving by release the mouse. Something is not right as the square seems to move in one direction only. Need some help here.
#square_cursor {
position: relative;
left: 109px;
top: 109px;
height: 50px;
width: 50px;
background-color: rgb(219, 136, 136);
border: 5px rgb(136, 219, 219) solid;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id='square_cursor'></div>
<script>
let mouse_over_detector = false; //move the mouse over WITHOUT clicking
let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
let drag_detector = false; //move and holding the mouse together
let window_click_detector = false;
let window_motion_detector = false;
let position_x = 0;
let position_y = 0;
let new_position_x = 0;
let new_position_y = 0;
window.addEventListener('mousedown', () => {
window_click_detector = true;
})
window.addEventListener('mouseup', () => {
window_click_detector = false;
brick.style.backgroundColor = 'rgb(219, 136, 136)';
})
let brick = document.getElementById('square_cursor');
//done
brick.addEventListener('mousedown', (event) => {
position_x = event.clientX;
position_y = event.clientY;
mouse_click_detector = true;
brick.style.backgroundColor = 'yellow';
})
brick.addEventListener('mousemove', (event) => {
if (mouse_click_detector === true) {
new_position_x = event.clientX;
new_position_y = event.clientY;
dragAndDrop(position_x, position_y, event.offsetX, event.offsetY);
}
});
brick.addEventListener('mouseout', () => {
mouse_over_detector = false;
mouse_click_detector = false;
})
brick.addEventListener('mouseup', () => {
mouse_click_detector = false;
})
function dragAndDrop(a, b, c, d) {
console.log('new x: ')
console.log(a - c);
console.log('new y: ')
console.log(b - d);
brick.style.left = a - c + 'px'
brick.style.top = b - d + 'px';
}
</script>
</body>
</html>
SOLVED IT THIS MORNING by using just addEventListener wooohoooo!
So the keys here are, first, being able to identify the DOM hierarchy and second, knowing what clientX does for the selected element. I am going to post my solution in snippet mode.
But I am still gonna give a vote to the 1st answer.
#square_cursor{
position:absolute;
left:109px;
top:109px;
height:50px;
width:50px;
background-color: rgb(219, 136, 136);
border:5px rgb(136, 219, 219) solid;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id='square_cursor'></div>
<script>
let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
let window_click_detector = false;
let position_x = 0;
let position_y = 0;
let click_position_x = 0;
let click_position_y = 0;
let brick = document.getElementById('square_cursor');
brick.addEventListener('mousedown', () => {
mouse_click_detector = true
})
window.addEventListener('mouseup', () => {
mouse_click_detector = false;
window_click_detector = false;
brick.style.backgroundColor = 'rgb(219, 136, 136)';
})
window.addEventListener('mousedown', (event) => {
if (mouse_click_detector === true) {
window_click_detector = true;
brick.style.backgroundColor = 'yellow';
click_position_x = event.offsetX;
click_position_y = event.offsetY;
}
})
window.addEventListener('mousemove', (event) => {
if (mouse_click_detector === true) {
position_x = event.clientX;
position_y = event.clientY;
brick.style.left = position_x - click_position_x + 'px';
brick.style.top = position_y - click_position_y + 'px';
}
})
</script>
</body>
</html>
"The most personal is the most creative" --- Martin Scorsese
Something like this..
//Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
}
}
#mydiv {
position: absolute; /* NECESSARY */
background-color: dodgerblue;
border: 1px solid #d3d3d3;
height: 20px;
width: 20px;
}
<div id="mydiv">
</div>
Minimalist code,
with simplified calculations by transform: translate(x,y).
const myDiv = document.querySelector('#my-div');
myDiv.ref_ms = { x: 0, y: 0 };
myDiv.addEventListener('mousedown', (e) =>
{
myDiv.ref_ms.x = e.clientX;
myDiv.ref_ms.y = e.clientY;
myDiv.classList.add('movCursor')
if (myDiv.style.transform !== '')
{
let [ mx, my ] = myDiv.style.transform.match(/-?\d*\.?\d+/g).map(Number);
myDiv.ref_ms.x -= mx;
myDiv.ref_ms.y -= my;
}
})
window.addEventListener('mousemove', e =>
{
if (myDiv.classList.contains('movCursor')
&& e.clientX > 0 && e.clientY > 0 )
{
myDiv.style = `transform: translate(${e.clientX - myDiv.ref_ms.x}px, ${e.clientY - myDiv.ref_ms.y}px);`;
}
})
window.addEventListener('mouseup', () =>
{
myDiv.classList.remove('movCursor')
})
#my-div {
background : dodgerblue;
border : 1px solid #d3d3d3;
height : 50px;
width : 50px;
margin : 30px;
cursor : grab;
}
.movCursor {
cursor : grabbing !important;
}
<div id="my-div"></div>

JavaScript - Stop laser once its in its incrementation cycle

To see a working example simply copy code into notepad++ and run in chrome as a .html file, I have had trouble getting a working example in snippet or code pen, I would have given a link to those websites if I could get it working in them.
The QUESTION is; once I fire the laser once it behaves exactly the way I want it to. It increments with lzxR++; until it hits boarder of the game arena BUT if I hit the space bar WHILST the laser is moving the code iterates again and tries to display the laser in two places at once which looks bad and very choppy, so how can I get it to work so the if I hit the space bar a second time even whilst the laser was mid incrementation - it STOPS the incrementing and simply shoots a fresh new laser without trying to increment multiple lasers at once???
below is the Code:
<html>
<head>
<style>
#blueCanvas {
position: absolute;
background-color: black;
width: 932px;
height: 512px;
border: 1px solid black;
top: 20px;
left: 20px;
}
#blueBall {
position: relative;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 10px;
border-radius: 100%;
top: 0px;
left: 0px;
}
#laser {
position: absolute;
background-color: white;
border: 1px solid blue;
width: 10px;
height: 1px;
top: 10px;
left: 10px;
}
#pixelTrackerTop {
position: absolute;
top: 530px;
left: 20px;
}
#pixelTrackerLeft {
position: absolute;
top: 550px;
left: 20px;
}
</style>
<title>Portfolio</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
document.addEventListener("keydown", keyBoardInput);
var topY = 0;
var leftX = 0;
var lzrY = 0;
var lzrX = 0;
function moveUp() {
var Y = document.getElementById("blueBall");
topY = topY -= 1;
Y.style.top = topY;
masterTrack();
if (topY < 1) {
topY = 0;
Y.style.top = topY;
};
stopUp = setTimeout("moveUp()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYup();
console.log('moveUp');
};
function moveDown() {
var Y = document.getElementById("blueBall");
topY = topY += 1;
Y.style.top = topY;
masterTrack();
if (topY > 500) {
topY = 500;
Y.style.top = topY;
};
stopDown = setTimeout("moveDown()", 1)
/**allows for progression of speed with additional key strokes**/
topStop();
stopConflictYdown();
console.log('moveDown');
};
function moveLeft() {
var X = document.getElementById("blueBall");
leftX = leftX -= 1;
X.style.left = leftX;
masterTrack();
if (leftX < 1) {
leftX = 0;
Y.style.leftX = leftX;
};
stopLeft = setTimeout("moveLeft()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXleft();
console.log('moveLeft');
};
function moveRight() {
var X = document.getElementById("blueBall");
leftX = leftX += 1;
X.style.left = leftX;
masterTrack();
if (leftX > 920) {
leftX = 920;
Y.style.leftX = leftX;
};
stopRight = setTimeout("moveRight()", 1)
/**allows for progression of speed with additional key strokes**/
leftStop();
stopConflictXright();
console.log('moveRight');
};
function masterTrack() {
var pxY = topY;
var pxX = leftX;
document.getElementById('pixelTrackerTop').innerHTML =
'Top position is ' + pxY;
document.getElementById('pixelTrackerLeft').innerHTML =
'Left position is ' + pxX;
};
function topStop() {
if (topY <= 0) {
clearTimeout(stopUp);
console.log('stopUp activated');
};
if (topY >= 500) {
clearTimeout(stopDown);
console.log('stopDown activated');
};
};
function leftStop() {
if (leftX <= 0) {
clearTimeout(stopLeft);
console.log('stopLeft activated');
};
if (leftX >= 920) {
clearTimeout(stopRight);
console.log('stopRight activated');
};
};
function stopConflictYup() {
clearTimeout(stopDown);
};
function stopConflictYdown() {
clearTimeout(stopUp);
};
function stopConflictXleft() {
clearTimeout(stopRight);
};
function stopConflictXright() {
clearTimeout(stopLeft);
};
function shootLaser() {
var l = document.getElementById("laser");
var lzrY = topY;
var lzrX = leftX;
fireLaser();
function fireLaser() {
l.style.left = lzrX; /**initial x pos **/
l.style.top = topY; /**initial y pos **/
var move = setInterval(moveLaser, 1);
/**continue to increment laser unless IF is met**/
function moveLaser() { /**CALL and start the interval**/
var bcrb = document.getElementById("blueCanvas").style.left;
if (lzrX > bcrb + 920) {
/**if the X axis of the laser goes beyond the
blueCanvas 0 point by 920 then stop incrementing the laser on its X
axis**/
clearInterval(move);
/**if statement was found true so stop increment of laser**/
} else {
lzrX++;
l.style.left = lzrX;
};
};
};
};
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
shootLaser();
};
if (i == 38) {
if (topY > 0) {
moveUp();
};
};
if (i == 40) {
if (topY < 500) {
moveDown();
};
};
if (i == 37) {
if (leftX > 0) {
moveLeft();
};
};
if (i == 39) {
if (leftX < 920) {
moveRight();
};
};
};
/**
!! gradual progression of opacity is overall
!! being able to speed up element is best done with setTimout
!! setInterval is constant regards to visual speed
!! NEXT STEP IS ARRAYS OR CLASSES
IN ORDER TO SHOOT MULITPLE OF SAME ELEMENT? MAYBEE?
var l = document.getElementById("laser");
lzrX = lzrX += 1;
l.style.left = lzrX;
lzrY = topY += 1;
l.style.top = lzrY;
**/
</SCRIPT>
</head>
<div id="blueCanvas">
<div id="laser"></div>
<div id="blueBall">
</div>
</div>
<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>
</body>
</html>
Solved the problem with using a variable called "g" and incrementing it once the laser is shot!
var g = 0;
function keyBoardInput() {
var i = event.keyCode;
if (i == 32) {
if (g < 1) {
shootLaser();
g++;
};
};

Document is not defined error for 'document.getElementById()'

Essentially, I keep getting the message "document is not defined" when I run my .js doc on command line. I'm trying to create a super basic game where the user helps the squirrel get to the chestnuts by using arrow keys. So far I can't move the squirrel yet, and I suspect it has to do with the document is not defined error that I'm getting (lines 1-3 and maybe also 52 in the link).
You can find my code (html, css and js) in the following jsfiddle link
(http://jsfiddle.net/8Lbkcsq2/)
var squirrelImg = document.getElementById("squirrelImg");
var forest = document.getElementById("forest");
var chestnutImg = document.getElementById("chestnutsImg");
var squirrel = {
name: "Mr. Squirrel",
has_chestnuts: false,
hungry: true
};
var chestnuts = {
name: "chestnuts"
};
var positionLeft = 0;
var positionTop = 0;
function move(e) {
// 39 for right arrow
if (e.keyCode === 39) {
if (positionLeft < 850) {
positionLeft += 50;
squirrelImg.style.left = positionLeft + "px";
}
}
// 40 for down arrow
if (e.keyCode === 40) {
if (positionTop < 600) {
positionTop += 50;
squirrelImg.style.top = positionTop + "px";
}
}
// 37 for left arrow
if (e.keyCode === 37) {
positionLeft -= 50;
if (positionLeft < 0) {
positionLeft += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.left = positionLeft + "px";
}
// 38 for up arrow
if (e.keyCode === 38) {
positionTop -= 100;
if (positionTop < 0) {
positionTop += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.top = positionTop + "px";
}
foundChestnuts();
}
document.onKeyDown = move();
function foundChestnuts() {
if ((squirrelImg.style.top == "300px") && (squirrelImg.style.left == "750px")) {
squirrel.has_chestnuts = true;
alert("Thank you for helping Mr. Squirrel find his chestnuts!");
var eat = confirm("Should Mr.Squirrel eat his chestnuts?");
if (eat === true) {
alert("Time to eat!");
alert("Yum! Mr. Squirrel isn't hungry anymore!");
} else {
alert("I guess Mr. Squirrel can wait a little longer...");
}
} else {
squirrel.has_chestnuts = false;
}
}
body {
background-color: #b5916c;
}
h3 {
font-weight: bold;
text-decoration: underline;
}
p {
font-family:'Dancing Script', cursive;
font-size: large;
}
#forest {
background-image: url(http://s21.postimg.org/jyht762hj/forestfloor.jpg);
width: 850px;
height: 600px;
position: relative;
/*opacity: 0.5;*/
}
#squirrelImg {
position: absolute;
background-image: url(http://s24.postimg.org/wkqh9by4x/squirrel.png);
height: 100px;
width: 100px;
left: 0;
top: 0;
}
#chestnutsImg {
position: absolute;
background-image: url(http://s28.postimg.org/kgiubxhnd/chestnuts.jpg);
height: 100px;
width: 100px;
left: 750px;
top: 300px;
}
<body>
<h3>A Plea from Mr. Squirrel:</h3>
<p>My dearest human,</p>
<p>I seem to have misplaced my chestnuts and I am quite famished.</p>
<p>Would you mind assisting me in locating them?</p>
<p>Much obliged!</p>
<div id="forest">
<div id="squirrelImg"></div>
<div id="chestnutsImg"></div>
</div>
</body>
The issue is that move() requires an event to be passed to it but when you do document.onKeyDown = move(); no event is passed.
Change document.onKeyDown = move(); to document.addEventListener("keydown", move, false);
working jsfiddle
Add a event listener document.body.addEventListener('keydown', function(e) {...} instead of document.onKeyDown = move().
Updated Fiddle
var squirrelImg = document.getElementById("squirrelImg");
var forest = document.getElementById("forest");
var chestnutImg = document.getElementById("chestnutsImg");
var squirrel = {
name: "Mr. Squirrel",
has_chestnuts: false,
hungry: true
};
var chestnuts = {
name: "chestnuts"
};
var positionLeft = 0;
var positionTop = 0;
document.body.addEventListener('keydown', function(e) {
// 39 for right arrow
if (e.keyCode === 39) {
if (positionLeft < 850) {
positionLeft += 50;
squirrelImg.style.left = positionLeft + "px";
}
}
// 40 for down arrow
if (e.keyCode === 40) {
if (positionTop < 600) {
positionTop += 50;
squirrelImg.style.top = positionTop + "px";
}
}
// 37 for left arrow
if (e.keyCode === 37) {
positionLeft -= 50;
if (positionLeft < 0) {
positionLeft += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.left = positionLeft + "px";
}
// 38 for up arrow
if (e.keyCode === 38) {
positionTop -= 100;
if (positionTop < 0) {
positionTop += 50; // CHANGE TO +=50 LATER
}
squirrelImg.style.top = positionTop + "px";
}
foundChestnuts();
});
// combined 3 functions previously separated for foundChestnuts, eatChestnuts and hungerLevel into the function below
function foundChestnuts() {
if ((squirrelImg.style.top == "300px") && (squirrelImg.style.left == "750px")) {
squirrel.has_chestnuts = true;
alert("Thank you for helping Mr. Squirrel find his chestnuts!");
var eat = confirm("Should Mr.Squirrel eat his chestnuts?");
if (eat === true) {
alert("Time to eat!");
alert("Yum! Mr. Squirrel isn't hungry anymore!");
} else {
alert("I guess Mr. Squirrel can wait a little longer...");
}
} else {
squirrel.has_chestnuts = false;
}
}
body {
background-color: #b5916c;
}
h3 {
font-weight: bold;
text-decoration: underline;
}
p {
font-family: 'Dancing Script', cursive;
font-size: large;
}
#forest {
background-image: url(http://s21.postimg.org/jyht762hj/forestfloor.jpg);
width: 850px;
height: 600px;
position: relative;
/*opacity: 0.5;*/
}
#squirrelImg {
position: absolute;
background-image: url(http://s24.postimg.org/wkqh9by4x/squirrel.png);
height: 100px;
width: 100px;
left: 0;
top: 0;
}
#chestnutsImg {
position: absolute;
background-image: url(http://s28.postimg.org/kgiubxhnd/chestnuts.jpg);
height: 100px;
width: 100px;
left: 750px;
top: 300px;
}
<body>
<h3>A Plea from Mr. Squirrel:</h3>
<p>My dearest human,</p>
<p>I seem to have misplaced my chestnuts and I am quite famished.</p>
<p>Would you mind assisting me in locating them?</p>
<p>Much obliged!</p>
<div id="forest">
<div id="squirrelImg"></div>
<div id="chestnutsImg"></div>
</div>
</body>
please place the script before </body>, or in window.onload callback function.
Because document object is not created when you call document.getElementById.
Yes, the problem is document.onKeyDown = move(). The right event handler isdocument.onkeydown, and handler should be a function move, not a function result move(). So just changed to document.onkeydown=move

Error in javascript Drag and Drop

I have done drag and drop of popup in JavaScript and it is dragged in all directions properly but down.MouseUp event is not triggered properly when I drag the popup towards down.So that it is moving even though I released mouse. I am really screwed up with this bug.Please help..I have to resolve it urgently....
Here is my code..
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
body{
margin:0px;
padding:0px;
}
iframe{
width:800px;
height:500px;
}
img{border:none;}
.parentDisabled
{
width:100%;
height:100%
background-color:red;
position:absolute;
top:0;
left:0;
display:block;
border:1px solid blue;
}
#popup{
position:absolute;
width:800px;
height:500px;
border:2px solid #999188;
display:none;
}
#header{
padding-right:0px;
width:800px;
}
#close{
cursor:hand;
width:15px;
position: absolute;
right:0;
top:0;
padding:2px 2px 0px 0px;
}
#move{
cursor:move;
background:#999188;
width:800px;
line-height:10px;
}
#container{
}
.navigate{
border:1px solid black ;
background:#CC00FF;
color:white;
padding:5px;
cursor:hand;
font-weight:bold;
width:150px;
}
</style>
</HEAD>
<BODY>
<div onClick="showPopUp('w3schools');" class="navigate">W3Schools</div>
<div onClick="showPopUp('yahoo');" class="navigate">Yahoo</div>
<div onClick="showPopUp('linkedin');" class="navigate">LinkedIn</div>
<div onClick="showPopUp('vistex');" class="navigate">Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span>
<span id="close"><img src="close_red.gif" onClick="closePopUp()" alt="Close"/></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder=0>
page cannot be displayed
</iframe>
</div>
</div>
</BODY>
<script>
var popUpEle=null;
function showPopUp(value,evt)
{
evt = evt ? evt : window.event;
var left=evt.clientX;
var top=evt.clientY;
popUpEle = document.getElementById('popup');
if(popUpEle)
{
closePopUp();
var url= "http://www."+value+".com";
document.getElementById('Page_View').src=url;
popUpEle.style.left=left;
popUpEle.style.top=top;
popUpEle.style.filter="revealTrans( transition=1, duration=1)";
popUpEle.filters.revealTrans( transition=1, duration=1).Apply();
popUpEle.filters.revealTrans( transition=1, duration=1).Play();
popUpEle.style.display="inline";
}
}
function closePopUp(){
if(popUpEle)
{
popUpEle.style.filter="revealTrans( transition=0, duration=4)";
popUpEle.filters.revealTrans( transition=0, duration=5).Apply();
popUpEle.filters.revealTrans( transition=0, duration=5).Play();
popUpEle.style.display="none";
}
}
var dragApproved=false;
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
if (e.pageX || e.pageY)
{
oElem.mouseX = e.pageX;
oElem.mouseY = e.pageY;
}
else if (e.clientX || e.clientY) {
oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var clientXTmp,clientYTmp;
if (e.pageX || e.pageY)
{
clientXTmp = e.pageX;
clientXTmp = e.pageY;
}
else if (e.clientX || e.clientY) {
clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
var tmpX = x + (clientXTmp - oElem.mouseX);
var tmpY = y + (clientYTmp - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = clientXTmp;
oElem.mouseY = clientYTmp;
return false;
},
// private method. Stop drag process.
_dragEnd : function()
{
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('popup'));</script>
</HTML>
First, your script didn't work in firefox or chrome so I did some changes.
Second, there's a limitation when moving the mouse very fast over the iframe. It seems that when the mouse is over an iframe, the 'mousemove' event isn't fired.
I inserted some fixes to your code and here it is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<style>
body
{
margin: 0px;
padding: 0px;
}
iframe
{
width: 800px;
height: 500px;
}
img
{
border: none;
}
.parentDisabled
{
width: 100%;
height: 100% background-color:red;
position: absolute;
top: 0;
left: 0;
display: block;
border: 1px solid blue;
}
#popup
{
position: absolute;
width: 800px;
height: 500px;
border: 2px solid #999188;
display: none;
}
#header
{
padding-right: 0px;
width: 800px;
height:20px;
background:#d8d8d8;
cursor:move;
}
#close
{
cursor: hand;
width: 15px;
position: absolute;
right: 0;
top: 0;
padding: 2px 2px 0px 0px;
}
#move
{
cursor: move;
background: #999188;
width: 800px;
line-height: 10px;
}
#container
{
}
.navigate
{
border: 1px solid black;
background: #CC00FF;
color: white;
padding: 5px;
cursor: hand;
font-weight: bold;
width: 150px;
}
</style>
</head>
<body>
<div onclick="showPopUp('w3schools', event);" class="navigate">
W3Schools</div>
<div onclick="showPopUp('yahoo', event);" class="navigate">
Yahoo</div>
<div onclick="showPopUp('linkedin', event);" class="navigate">
LinkedIn</div>
<div onclick="showPopUp('vistex', event);" class="navigate">
Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span><span id="close">
<img src="close_red.gif" onclick="closePopUp()" alt="Close" /></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder="0">page cannot be displayed </iframe>
</div>
</div>
<div id='log'></div>
<script type="text/javascript">
var popUpEle = null;
var isIE = navigator.appVersion.indexOf("MSIE") !== -1;
function showPopUp(value, evt)
{
evt = evt ? evt : window.event;
var left = evt.clientX;
var top = evt.clientY;
popUpEle = document.getElementById('popup');
if (popUpEle)
{
closePopUp();
var url = "http://www." + value + ".com";
document.getElementById('Page_View').src = url;
popUpEle.style.left = left;
popUpEle.style.top = top;
popUpEle.style.filter = "revealTrans( transition=1, duration=1)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 1, duration = 1).Apply();
popUpEle.filters.revealTrans(transition = 1, duration = 1).Play();
}
popUpEle.style.display = "block";
}
}
function closePopUp()
{
if (popUpEle)
{
popUpEle.style.filter = "revealTrans( transition=0, duration=4)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 0, duration = 5).Apply();
popUpEle.filters.revealTrans(transition = 0, duration = 5).Play();
}
popUpEle.style.display = "none";
}
}
var DragHandler = {
// private property.
_oElem: null,
_dragElement: null,
// public method. Attach drag handler to an element.
attach: function (oElem)
{
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin: function (e)
{
e = window.event || e;
var oElem = DragHandler._oElem = this;
// saving current mouse position
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
// if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
// if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
// var x = parseInt(oElem.style.left);
// var y = parseInt(oElem.style.top);
// e = e ? e : window.event;
// if (e.pageX || e.pageY)
// {
// oElem.mouseX = e.pageX;
// oElem.mouseY = e.pageY;
// }
// else if (e.clientX || e.clientY)
// {
// oElem.mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
// oElem.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
// }
// saving the element which invoked the drag
// to capture 'mouseout' event
DragHandler._dragElement = document.elementFromPoint(e.clientX, e.clientY);
DragHandler._dragElement.onmouseout = DragHandler._dragMouseOut;
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
_dragMouseOut: function (e)
{
e = window.event || e;
//document.getElementById("log").innerHTML += "mouseout!: " + e.clientX + "," + e.clientY + "<br/>";
// calculating move by
var oElem = DragHandler._oElem;
var moveByX = e.clientX - oElem.mouseX;
var moveByY = e.clientY - oElem.mouseY;
//if (document.getElementById("log").offsetHeight > 100)
//document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML += "mouseout x: " + moveByX + ", y:" + moveByY + "<br/>";
// setting position
var futureX = (x + moveByX);
if (futureX < 0) futureX = 0;
var futureY = (y + moveByY);
if (futureY < 0) futureY = 0;
oElem.style.left = futureX + 'px';
oElem.style.top = futureY + 'px';
oElem.mouseX = e.clientX;
if (oElem.mouseX < 0) oElem.mouseX = 0;
oElem.mouseY = e.clientY;
if (oElem.mouseY < 0) oElem.mouseY = 0;
},
// private method. Drag (move) element.
_drag: function (e)
{
e = window.event || e;
var oElem = DragHandler._oElem;
document.getElementById("log").innerHTML += "mousemove!!!<br/>";
// current element position
var x = oElem.offsetLeft;
var y = oElem.offsetTop;
// calculating move by
var moveByX = e.clientX - oElem.mouseX;
var moveByY = e.clientY - oElem.mouseY;
//if (document.getElementById("log").offsetHeight > 100)
//document.getElementById("log").innerHTML = "";
document.getElementById("log").innerHTML += "mouse move x: " + moveByX + ", y:" + moveByY + "<br/>";
// setting position
var futureX = (x + moveByX);
if (futureX < 0) futureX = 0;
var futureY = (y + moveByY);
if (futureY < 0) futureY = 0;
oElem.style.left = futureX + 'px';
oElem.style.top = futureY + 'px';
oElem.mouseX = e.clientX;
if (oElem.mouseX < 0) oElem.mouseX = 0;
oElem.mouseY = e.clientY;
if (oElem.mouseY < 0) oElem.mouseY = 0;
// canceling selection
if (!isIE)
return false;
else
document.selection.empty();
},
// private method. Stop drag process.
_dragEnd: function ()
{
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
DragHandler._dragElement.onmouseout = null;
DragHandler._dragElement = null;
}
}
DragHandler.attach(document.getElementById('popup'));
</script>
</body></html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<style>
body
{
margin: 0px;
padding: 0px;
}
iframe
{
width: 400px;
height: 200px;
}
img
{
border: none;
}
.parentDisabled
{
width: 100%;
height: 100% background-color:red;
position: absolute;
top: 0;
left: 0;
display: block;
border: 1px solid blue;
}
#popup
{
position: absolute;
width: 400px;
height: 200px;
border: 2px solid #999188;
display: none;
}
#header
{
padding-right: 0px;
width: 400px;
height:20px;
background:#d8d8d8;
cursor:move;
}
#close
{
cursor: hand;
width: 15px;
position: absolute;
right: 0;
top: 0;
padding: 2px 2px 0px 0px;
}
#move
{
cursor: move;
background: #999188;
width: 400px;
line-height: 10px;
}
#container
{
}
.navigate
{
border: 1px solid black;
background: #CC00FF;
color: white;
padding: 5px;
cursor: hand;
font-weight: bold;
width: 150px;
}
</style>
</head>
<body>
<div onclick="showPopUp('w3schools', event);" class="navigate">
W3Schools</div>
<div onclick="showPopUp('yahoo', event);" class="navigate">
Yahoo</div>
<div onclick="showPopUp('linkedin', event);" class="navigate">
LinkedIn</div>
<div onclick="showPopUp('vistex', event);" class="navigate">
Vistex</div>
<div id="popup">
<div id="header">
<span id="move"></span><span id="close">
<img src="close_red.gif" onclick="closePopUp()" alt="Close" /></span>
</div>
<div id="container">
<iframe name="frame" id="Page_View" frameborder="0">page cannot be displayed </iframe>
</div>
</div>
<div id='log'></div>
</body>
<script>
var popUpEle = null;
var isIE = navigator.appVersion.indexOf("MSIE") !== -1;
function showPopUp(value, evt)
{
evt = evt ? evt : window.event;
var left = evt.clientX;
var top = evt.clientY;
popUpEle = document.getElementById('popup');
if (popUpEle)
{
closePopUp();
var url = "http://www." + value + ".com";
document.getElementById('Page_View').src = url;
popUpEle.style.left = left;
popUpEle.style.top = top;
popUpEle.style.filter = "revealTrans( transition=1, duration=1)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 1, duration = 1).Apply();
popUpEle.filters.revealTrans(transition = 1, duration = 1).Play();
}
popUpEle.style.display = "block";
}
}
function closePopUp()
{
if (popUpEle)
{
popUpEle.style.filter = "revealTrans( transition=0, duration=4)";
if (isIE)
{
popUpEle.filters.revealTrans(transition = 0, duration = 5).Apply();
popUpEle.filters.revealTrans(transition = 0, duration = 5).Play();
}
popUpEle.style.display = "none";
}
}
var dragApproved=false;
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
if (!document.all)return;
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))){ oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
if (e.pageX || e.pageY)
{
oElem.mouseX = e.pageX;
oElem.mouseY = e.pageY;
}
else if (e.clientX || e.clientY) {
oElem.mouseX = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
oElem.mouseY = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
document.onmousemove = DragHandler._drag;
dragApproved=true;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
if(dragApproved && event.button==1)
{
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var clientXTmp,clientYTmp;
if (e.pageX || e.pageY)
{
clientXTmp = e.pageX;
clientXTmp = e.pageY;
}
else if (e.clientX || e.clientY) {
clientXTmp = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
clientYTmp = e.clientY + document.body.scrollTop+ document.documentElement.scrollTop;
}
var tmpX = x + (clientXTmp - oElem.mouseX);
var tmpY = y + (clientYTmp - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
//Avoiding scrolling of rigth and bottom of the window
if((tmpX+oElem.offsetWidth) > document.body.offsetWidth)
{
tmpX= document.body.offsetWidth-oElem.offsetWidth;
}
if((tmpY+oElem.offsetHeight) > document.body.offsetHeight)
{
tmpY= document.body.offsetHeight-oElem.offsetHeight;
}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = clientXTmp;
oElem.mouseY = clientYTmp;
return false;
}
},
// private method. Stop drag process.
_dragEnd : function()
{
dragApproved=false;
var oElem = DragHandler._oElem;
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('popup'));
</script>
</HTML>

Categories