How to drag images in JS - javascript

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>

Related

How to make a draggable div resize-able on all 4 corners with pure javascript?

I noticed these resize pointers in the css spec...
https://drafts.csswg.org/css-ui-3/#valdef-cursor-se-resize
Is there a CSS shortcut for 4 corner resizability similar to the one corner ('resize: both') method?
If not, are there known conflicts when combining resizability with a draggable div?
My starting point was here...
https://www.w3schools.com/howto/howto_js_draggable.asp
Any help navigating the posX, posY is appreciated.
notes for getBoundingClient()
———---
| |
|____ | div.getBoundingClientRect()
SE (bottom right):
Height and width / top and left are stationary
SW (bottom left):
Height and width and left / top is stationary
NW (top left):
Height and width top and left
NE (top right):
Height and width and Top / Left is stationary
edit: removed padding and borders.
const myDiv = document.getElementById('mydiv')
let isResizing = false;
//Make the DIV element draggable:
dragElement(myDiv);
function dragElement(elmnt) {
if (!isResizing) {
let 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;
}
}
}
// Resize
(function fourCorners() {
const resizers = document.querySelectorAll('.resizer')
let currentResizer
for (let resizer of resizers) {
resizer.addEventListener('mousedown', mouseDown)
function mouseDown(e) {
currentResizer = e.target
e.preventDefault()
isResizing = true;
let posX = e.clientX;
let posY = e.clientY;
myDiv.addEventListener('mousemove', mouseMove)
myDiv.addEventListener('mouseup', mouseUp)
function mouseMove(e) {
e.preventDefault()
const rect = myDiv.getBoundingClientRect()
if (currentResizer.classList.contains('se')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width - (posX - e.clientX) + 'px';
myDiv.style.height = rect.height - (posY - e.clientY) + 'px';
} else if (currentResizer.classList.contains('sw')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width + (posX - e.clientX) + 'px';
myDiv.style.height = rect.height - (posY - e.clientY) + 'px';
myDiv.style.left = rect.left - (posX - e.clientX) + 'px';
} else if (currentResizer.classList.contains('ne')) {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width - (posX - e.clientX) + 'px';
myDiv.style.height = rect.height + (posY - e.clientY) + 'px';
myDiv.style.top = rect.top - (posY - e.clientY) + 'px';
} else {
//console.log(currentResizer.classList.value)
myDiv.style.width = rect.width + (posX - e.clientX) + 'px';
myDiv.style.height = rect.height + (posY - e.clientY) + 'px';
myDiv.style.top = rect.top - (posY - e.clientY) + 'px';
myDiv.style.left = rect.left - (posX - e.clientX) + 'px';
}
posX = e.clientX;
posY = e.clientY;
}
function mouseUp(e) {
myDiv.removeEventListener('mousemove', mouseMove)
myDiv.removeEventListener('mouseup', mouseUp)
isResizing = false
}
}
}
})()
* {
margin: 0;
padding : 0;
}
#mydiv {
position: absolute; /* NECESSARY */
background-color: whitesmoke;
box-sizing: border-box;
text-align: center;
/* border: 1px solid #222; */
height: 200px;
width: 200px;
/* resize: both; /* CSS RESIZE */
overflow: hidden; /* CSS RESIZE */
}
#mydivheader {
/* padding: 10px; */
cursor: move;
background-color: dodgerblue;
color: #fff;
}
#content {
color: #000;
margin: 0px;
background-color: whitesmoke;
}
/* ::-webkit-resizer {
position: absolute;
height: 20px;
width: 20px;
border-top-left-radius: 25px;
background-color: #dd0;
z-index: 2;
} */
.resizer {
position: absolute;
height: 20px;
width: 20px;
background-color: #dd0;
z-index: 2;
}
.resizer.nw {
top: -1px;
left: -1px;
cursor: nw-resize;
border-bottom-right-radius: 25px;
}
.resizer.ne {
top: -1px;
right: -1px;
cursor: ne-resize;
border-bottom-left-radius: 25px;
}
.resizer.sw {
bottom: -1px;
left: -1px;
cursor: sw-resize;
border-top-right-radius: 25px;
}
.resizer.se {
bottom: -1px;
right: -1px;
cursor: se-resize;
border-top-left-radius: 25px;
}
<div id="mydiv">
<div class='resizer nw'></div>
<div class='resizer ne'></div>
<div class='resizer sw'></div>
<div class='resizer se'></div>
<div id="mydivheader">Click here to move
<div id='content'>
<div id='image-container'><img height='auto' width='100%' src='https://picsum.photos/600' /></div>
</div>
</div>
</div>
Well if you want to make it nice and easy you could use jQuery to help it resize would probably be the easiest way. Then after you learn how to do it with jQuery you could do it with pure js.
So, you want the resize handle to appear on all four corners? That'll require some bounds checking.
You can modify the offset check in drag to account for any corner and handle the drag as a resize event instead. The code somewhat works for top-left and bottom-right resizing, but doe not work too well with the opposite corners. This is a start.
This is a start:
const cursor = document.querySelector('#cursor');
const cornerThreshold = 4;
const dragStart = e => {
const [ horz, vert ] = getDirection(e, cornerThreshold);
const bounds = e.target.getBoundingClientRect();
const cursor = getCursorType(e);
if (cursor === 'grab') {
e.target.dataset.isDragging = true;
} else {
e.target.dataset.isResizing = true;
}
e.target.dataset.startWidth = bounds.width;
e.target.dataset.startHeight = bounds.height;
e.target.dataset.originX = e.clientX;
e.target.dataset.originY = e.clientY;
e.target.dataset.offsetX = e.clientX - e.target.offsetLeft;
e.target.dataset.offsetY = e.clientY - e.target.offsetTop;
e.target.dataset.dirHorz = horz;
e.target.dataset.dirVert = vert;
e.target.style.zIndex = 999;
};
const dragEnd = e => {
delete e.target.dataset.isDragging;
delete e.target.dataset.offsetX;
delete e.target.dataset.offsetY;
delete e.target.dataset.originX;
delete e.target.dataset.originY;
delete e.target.dataset.startWidth;
delete e.target.dataset.startHeight;
delete e.target.dataset.dirHorz;
delete e.target.dataset.dirVert;
delete e.target.dataset.resizeDirection;
e.target.style.removeProperty('z-index');
e.target.style.removeProperty('cursor');
};
const drag = e => {
e.target.style.cursor = getCursorType(e);
cursor.textContent = `(${e.clientX}, ${e.clientY})`;
if (e.target.dataset.isDragging) {
e.target.style.left = `${e.clientX - parseInt(e.target.dataset.offsetX, 10)}px`;
e.target.style.top = `${e.clientY - parseInt(e.target.dataset.offsetY, 10)}px`;
} else if (e.target.dataset.isResizing) {
const bounds = e.target.getBoundingClientRect();
const startWidth = parseInt(e.target.dataset.startWidth, 10);
const startHeight = parseInt(e.target.dataset.startWidth, 10);
const deltaX = e.clientX - parseInt(e.target.dataset.originX, 10);
const deltaY = e.clientY - parseInt(e.target.dataset.originY, 10);
const originX = parseInt(e.target.dataset.originX, 10);
const originY = parseInt(e.target.dataset.originY, 10);
const dirHorz = parseInt(e.target.dataset.dirHorz, 10);
const dirVert = parseInt(e.target.dataset.dirVert, 10);
if (dirHorz < 0) {
e.target.style.left = `${originX + deltaX}px`;
e.target.style.width = `${startWidth - deltaX}px`
} else if (dirHorz > 0) {
e.target.style.width = `${startWidth + deltaX}px`;
}
if (dirVert < 0) {
e.target.style.top = `${originY + deltaY}px`;
e.target.style.height = `${startHeight - deltaY}px`;
} else if (dirVert > 0) {
e.target.style.height = `${startHeight + deltaY}px`;
}
}
};
const focus = e => { };
const unfocus = e => { e.target.style.removeProperty('cursor'); };
const getDirection = (e, threshold) => {
const bounds = e.target.getBoundingClientRect();
const offsetX = e.clientX - e.target.offsetLeft;
const offsetY = e.clientY - e.target.offsetTop;
const isTop = offsetY <= threshold;
const isLeft = offsetX <= threshold;
const isBottom = offsetY > (bounds.height - threshold);
const isRight = offsetX > (bounds.width - threshold);
if (isTop && isLeft) return [ -1, -1 ];
else if (isTop && isRight) return [ -1, 1 ];
else if (isBottom && isLeft) return [ 1, -1 ];
else if (isBottom && isRight) return [ 1, 1 ];
else return [ 0, 0 ];
};
const getCursorType = (e) => {
if (e.target.dataset.isDragging) {
return 'grabbing';
} else {
const [ horz, vert ] = getDirection(e, cornerThreshold);
const isTop = vert === -1;
const isLeft = horz === -1;
const isBottom = vert === 1;
const isRight = horz === 1;
if ((isTop && isLeft) || (isBottom && isRight)) return 'nwse-resize';
if ((isTop && isRight) || (isBottom && isLeft)) return 'nesw-resize';
}
return 'grab';
};
document.querySelectorAll('.draggable').forEach(draggable => {
draggable.addEventListener('mousedown', dragStart);
draggable.addEventListener('mouseup', dragEnd);
draggable.addEventListener('mousemove', drag);
draggable.addEventListener('mouseenter', focus);
draggable.addEventListener('mouseleave', unfocus);
});
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.container {
position: relative;
width: 60%;
height: 60%;
border: thin solid grey;
}
.square {
position: absolute;
height: 2em;
width: 2em;
}
.color-red { background: red; }
.color-blue { background: blue; }
.color-green { background: green; }
#square-1 { top: 10px; left: 10px; }
#square-2 { top: 50px; left: 50px; }
#square-3 { top: 100px; left: 100px; }
<div class="container">
<div id="square-1" class="square color-red draggable resizable"></div>
<div id="square-2" class="square color-blue draggable resizable"></div>
<div id="square-3" class="square color-green draggable resizable"></div>
</div>
<br />
<div>Cursor: <span id="cursor">(0, 0)</span></div>

Collision detection using pure jQuery is not giving desired output

I am trying to develop a very simple game where the ship (red box) will move left-right when user clicks on playground.
There are some moving walls (black boxes) as obstacles that the ship should avoid colliding with.
If any collision happens, the walls will stop moving and a text will be printed out in console.
I have succeeded to get this as close as I can. But its working sometime, not always. You can see it in the code below, try to collide with wall. Sometime it will stop them and print text, sometime it will just ignore the collision as if nothing happens.
I have no clue why this is happening.
Here is the code.
$('document').ready(function() {
var $totalHeight = $('.inner').height(); //of walls
var $maxHeight = Math.ceil(Math.ceil($totalHeight / 3) - (Math.ceil($totalHeight / 3) * 30) / 100); //30% of total wall height
$('.wall').each(function(i, obj) {
$(this).height($maxHeight);
$('.wall.four').css({
'height': $wallGap
});
})
var $wallGap = Math.ceil($totalHeight / 3) - $maxHeight;
var $wallOneTop = 0;
var $wallTwoTop = $maxHeight + $wallGap;
var $wallThreeTop = ($maxHeight * 2) + ($wallGap * 2);
var $wallFourTop = -$('.wall.four').height() - $wallGap;
$('.wall.one').css({
'top': $wallOneTop
});
$('.wall.two').css({
'top': $wallTwoTop
});
$('.wall.three').css({
'top': $wallThreeTop
});
$('.wall.four').css({
'top': $wallFourTop
});
function moveWall(wallObj) {
var $currentTop = wallObj.position().top;
var $limitTop = $('.inner').height();
if ($currentTop >= $limitTop) {
var $rand = Math.floor(Math.random() * ($maxHeight - $wallGap + 1) + $wallGap);
wallObj.height($rand);
var $top = -(wallObj.height());
} else {
var $top = (wallObj.position().top) + 5;
}
var $collide = checkCollision(wallObj);
wallObj.css({
'top': $top
});
return $collide;
}
var $wallTimer = setInterval(function() {
$('.wall').each(function(i, obj) {
var $status = moveWall($(this));
if ($status == true) {
clearInterval($wallTimer);
}
})
}, 40);
function checkCollision(wallObj) {
var $ship = $('.ship');
var $shipWidth = $ship.width();
var $shipHeight = $ship.height();
var $shipLeft = $ship.position().left;
var $shipRight = $shipLeft + $shipWidth;
var $shipTop = $ship.position().top;
var $shipBottom = $shipTop + $shipHeight;
var $wall = wallObj;
var $wallWidth = wallObj.width();
var $wallHeight = wallObj.height();
var $wallLeft = wallObj.position().left;
var $wallRight = $wallLeft + $wallWidth;
var $wallTop = wallObj.position().top;
var $wallBottom = $wallTop + $wallHeight;
if (
$shipLeft >= $wallRight ||
$shipRight <= $wallLeft ||
$shipTop >= $wallBottom ||
$shipBottom <= $wallTop
) {
return false;
} else {
console.log("dhumm!");
return true;
}
}
$('.outer .inner').click(function() {
var $ship;
$ship = $('.ship');
$shipLeft = $ship.position().left;
$shipRight = $shipLeft + $ship.width();
$inner = $('.inner');
$innerLeft = $inner.position().left;
$innerRight = $innerLeft + $inner.width();
if (($shipLeft < $inner.width() - $ship.width())) {
$ship.animate({
"left": $inner.width() - $ship.width()
}, 500, "linear");
} else if (($shipRight >= $inner.width())) {
$ship.animate({
"left": '0'
}, 500, "linear");
}
});
});
.outer {
background: #fff;
border: 20px solid #efefef;
width: 400px;
height: 600px;
display: inline-block;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
overflow: hidden;
}
.outer .inner {
background: #fff;
height: 100%;
width: 100%;
margin: auto;
position: relative;
overflow: hidden;
}
.outer .inner .wall {
width: 5px;
position: absolute;
left: 50%;
transform: translateX(-50%);
background: #000;
}
.outer .inner .ship {
width: 15px;
height: 15px;
background: red;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<div class="wall one"></div>
<div class="wall two"></div>
<div class="wall three"></div>
<div class="wall four"></div>
<div class="ship"></div>
</div>
</div>
As freefomn-m already said.
Check for collision in the animation cycle of the ship, not the walls.
For this I use the second type of parameters for jQuery's .animate method
.animate( properties, options )
I use the "progress" option to check the collision in every movement cycle of the ship.
console.clear();
$('document').ready(function() {
var collided = false;
var collidedWith = null;
var $ship = $('.ship');
var $walls = $('.wall')
var $totalHeight = $('.inner').height(); //of walls
var $maxHeight = Math.ceil(Math.ceil($totalHeight / 3) - (Math.ceil($totalHeight / 3) * 30) / 100); //30% of total wall height
$('.wall').each(function(i, obj) {
$(this).height($maxHeight);
$('.wall.four').css({
'height': $wallGap
});
})
var $wallGap = Math.ceil($totalHeight / 3) - $maxHeight;
var $wallOneTop = 0;
var $wallTwoTop = $maxHeight + $wallGap;
var $wallThreeTop = ($maxHeight * 2) + ($wallGap * 2);
var $wallFourTop = -$('.wall.four').height() - $wallGap;
$('.wall.one').css({
'top': $wallOneTop
});
$('.wall.two').css({
'top': $wallTwoTop
});
$('.wall.three').css({
'top': $wallThreeTop
});
$('.wall.four').css({
'top': $wallFourTop
});
function moveWall(wallObj) {
var $currentTop = wallObj.position().top;
var $limitTop = $('.inner').height();
if ($currentTop >= $limitTop) {
var $rand = Math.floor(Math.random() * ($maxHeight - $wallGap + 1) + $wallGap);
wallObj.height($rand);
var $top = -(wallObj.height());
} else {
var $top = (wallObj.position().top) + 5;
}
// var $collide = checkCollision(wallObj);
wallObj.css({
'top': $top
});
// return $collide;
}
var $wallTimer = setInterval(function() {
$walls.each(function(i, obj) {
moveWall($(this));
if (collided) {
clearInterval($wallTimer);
}
})
}, 40);
function checkCollision() {
var $shipWidth = $ship.width();
var $shipHeight = $ship.height();
var $shipLeft = $ship.position().left;
var $shipRight = $shipLeft + $shipWidth;
var $shipTop = $ship.position().top;
var $shipBottom = $shipTop + $shipHeight;
$('.wall').each(function(i) {
var $wall = $(this);
var $wallWidth = $wall.width();
var $wallHeight = $wall.height();
var $wallLeft = $wall.position().left;
var $wallRight = $wallLeft + $wallWidth;
var $wallTop = $wall.position().top;
var $wallBottom = $wallTop + $wallHeight;
if (
$shipLeft < $wallRight &&
$shipRight > $wallLeft &&
$shipTop < $wallBottom &&
$shipBottom > $wallTop
) {
console.log("dhumm!");
collided = true;
collidedWith = $wall
$wall.addClass('crashed')
$ship.addClass('crashed')
$ship.stop();
return false;
}
})
}
$('.outer .inner').click(function() {
var $ship;
$ship = $('.ship');
$shipLeft = $ship.position().left;
$shipRight = $shipLeft + $ship.width();
$inner = $('.inner');
$innerLeft = $inner.position().left;
$innerRight = $innerLeft + $inner.width();
if (($shipLeft < $inner.width() - $ship.width())) {
$ship.animate({
"left": $inner.width() - $ship.width()
}, {
"duration": 500,
"easing": "linear",
"progress": checkCollision,
});
} else if (($shipRight >= $inner.width())) {
$ship.animate({
"left": '0'
}, {
"duration": 500,
"easing": "linear",
"progress": checkCollision,
});
}
});
});
.outer {
background: #fff;
border: 20px solid #efefef;
width: 400px;
height: 600px;
display: inline-block;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
overflow: hidden;
}
.outer .inner {
background: #fff;
height: 100%;
width: 100%;
margin: auto;
position: relative;
overflow: hidden;
}
.outer .inner .wall {
width: 5px;
position: absolute;
left: 50%;
transform: translateX(-50%);
background: #000;
}
.outer .inner .wall.crashed {
background: red;
}
.outer .inner .ship {
width: 15px;
height: 15px;
background: orange;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.outer .inner .ship.crashed {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<div class="wall one"></div>
<div class="wall two"></div>
<div class="wall three"></div>
<div class="wall four"></div>
<div class="ship"></div>
</div>
</div>
As a recommendation how I would do this from scratch.
Use an update cycle that is called by either setInterval or setTimeout, or even better with requestAnimationFrame. The updatecycle would be responsible for the time progress and orchestrate the different objects. The structure would be like this.
jQuery(function($) { // same as $('document').ready()
var ship = ...;
var boundaries = ...;
var walls = ...;
var clickEvents = [];
document.addEventListener('click', function(e) {clickEvents.push(e)})
var handleEvents = function() {}
var setupWalls = function () {}
var setupShip= function () {}
var moveWalls = function () {}
var moveShip = function () {}
var checkCollision() {}
var setup = function() {
setupWalls();
setupShip();
// set the initial positions of the ships and the walls
}
var update = function() {
handleEvents();
moveWalls();
moveShips();
var collided = checkCollision();
if (!collided) {
setTimeout(update, 30);
}
}
setup();
update();
})

Draggable element gets stuck near edges

Dragging the element seems to make it get stuck randomly before touching the edges of its parent container. Would someone be able to spot why this is going on?
On a side note, I could not get the remembered position transferred to "updateDrag" correctly.
And no, I don't want any jQuery solution, like one created with jQuery UI.
let $container = document.getElementById('container');
let $element = document.getElementById('element');
let mousePosition;
let offset = [0, 0];
let isDown = false;
function initDrag(event) {
isDown = true;
// Element also remembers previous position wrong
// offset = [
// $element.offsetLeft - event.clientX,
// $element.offsetTop - event.clientY
// ];
offset = [
0,
0
];
}
function updateDrag(event) {
event.preventDefault();
if (isDown) {
mousePosition = {
x: event.clientX,
y: event.clientY
};
let diffY = mousePosition.y - offset[1];
let diffX = mousePosition.x - offset[0];
if (diffY >= 0 && diffY + $element.offsetHeight <= $container.offsetHeight) {
$element.style.top = (mousePosition.y + offset[1]) + 'px';
}
if (diffX >= 0 && diffX + $element.offsetWidth <= $container.offsetWidth) {
$element.style.left = (mousePosition.x + offset[0]) + 'px';
}
}
}
function haltDrag() {
isDown = false;
}
$element.addEventListener('mousedown', initDrag, false);
document.addEventListener('mouseup', haltDrag, false);
document.addEventListener('mousemove', updateDrag, false);
#container {
position: relative;
top: 10px;
left: 10px;
height: 300px;
width: 300px;
background-color: green;
}
#element {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: red;
color: blue;
}
<div id="container">
<div id="element"></div>
</div>

Full page view on single scroll move to next section

I have tried to create single scroll and move to next section, I have using javascript, It is not working fine, The window top distance not giving properly, I need to div fullscreen moved to next screen, Please without jquery, Please help
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;}
function wheel(event) {
var delta = 0;
if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
else if (event.detail) delta = -(event.detail)/3;
handle(delta);
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}
function handle(sentido) {
var inicial = document.body.scrollTop;
var time = 500;
var distance = 900;
animate({
delay: 0,
duration: time,
delta: function(p) {return p;},
step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);
}
});
}
function animate(opts) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = (timePassed / opts.duration);
if (progress > 1) {progress = 1;}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}
body{
width: 100%;
height: 100%;
margin:0;
padding:0;
}
.wrapper{
width: 100%;
height: 100%;
position: absolute;
}
section{
width: 100%;
height: 100%;
}
.pg1{
background: green;
}
.pg2{
background: blue;
}
.pg3{
background: yellow;
}
<div class="wrapper" id="myDiv">
<section class="pg1" id="sec1"></section>
<section class="pg2"></section>
<section class="pg3"></section>
</div>
Return the height of the element and store it in distance variable, instead of giving it a static 900.
From this:
var distance = 900;
To this:
var distance = document.getElementById('sec1').clientHeight;

Div goes to wrong position

I am editing the vertical slider I used from this color picker. It uses top to adjust the cursors position. I want to use transform translateY instead. When I do that, I apparently have to calculate it differently.
The original calculation is: (Line: #286)
hsv_barcursor.style.top = ((1 - color.hsv.v) * hsv_barHeight) + 'px';
My updated version is: (Line 43 at JSFiddle Below)
hsv_barcursor.style.transform = 'translateY(calc(' + (color.RND.hsv.v * 10) + '% - ' + cursorRadius + 'px))';
The position of my version is wrong.
Why doesn't the math for top work for tranlateY?
What's the correct math to use for translateY?
I'm not looking for JQuery answers, nor am I looking for html's input range.
JSFiddle
var luminenceBarWrapper = document.getElementById('luminenceBarWrapper'),
hsv_barBGLayer = document.getElementById('bar-bg'),
hsv_barcursor = document.getElementById('hsv-barcursor'),
hsv_barCursors = document.getElementById('hsv-barcursors'),
hsv_barHeight = hsv_barCursors.offsetHeight,
cursorRadius = hsv_barcursor.offsetHeight / 2,
startPoint,
currentTarget,
myColor = new Colors();
// Create Event Functions
var hsvDown = function(e) { // mouseDown callback
e.preventDefault();
if (e.target === hsv_barcursor) currentTarget = e.target.parentNode;
else if (e.target === hsv_barCursors) currentTarget = e.target;
else return;
startPoint = getOrigin(currentTarget);
window.addEventListener('mousemove', hsvMove);
hsvMove(e);
startRender();
},
hsvMove = function(e) { // mouseMove callback
myColor.setColor({
v: (hsv_barHeight - (e.clientY - startPoint.top)) / hsv_barHeight * 100
}, 'hsv');
};
// Initial Rendering
doRender(myColor.colors);
// Adde Events To Objects
luminenceBarWrapper.addEventListener('mousedown', hsvDown);
window.addEventListener('mouseup', function() {
window.removeEventListener('mousemove', hsvMove);
stopRender();
});
function doRender(color) {
hsv_barcursor.style.transform = 'translateY(calc(' + (color.RND.hsv.v * 10) + '% - ' + cursorRadius + 'px))';
//hsv_barcursor.style.top = ((1 - color.hsv.v) * hsv_barHeight) + 'px';
}
var renderTimer,
startRender = function(oneTime) {
renderTimer = window.setInterval(function() {
doRender(myColor.colors);
}, 13); // 1000 / 60); // ~16.666 -> 60Hz or 60fps
},
stopRender = function() {
window.clearInterval(renderTimer);
};
function getOrigin(elm) {
var box = (elm.getBoundingClientRect) ? elm.getBoundingClientRect() : {
top: 0,
left: 0
},
doc = elm && elm.ownerDocument,
body = doc.body,
win = doc.defaultView || doc.parentWindow || window,
docElem = doc.documentElement || body.parentNode,
clientTop = docElem.clientTop || body.clientTop || 0, // border on html or body or both
clientLeft = docElem.clientLeft || body.clientLeft || 0;
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
body {
position: absolute;
}
#bar-bg {
width: 15px;
height: 500px;
background-color: greenyellow;
}
#hsv-barcursors {
position: absolute;
right: -7.5px;
width: 30px;
top: 0;
height: 500px;
overflow: hidden;
cursor: pointer;
}
#hsv-barcursor {
position: absolute;
right: 7.5px;
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid black;
margin-bottom: 5px;
}
<script src="https://rawgit.com/PitPik/colorPicker/master/colors.js"></script>
<div id="luminenceBarWrapper">
<div id="bar-bg"></div>
<div id="hsv-barcursors" id="hsv_cursors">
<div id="hsv-barcursor"></div>
</div>
</div>
translateY(Npx) translates something downward if N > 0 therefore you need translate(0px) when the marker is up and translate(Npx) when the marker is down at the bottom of your component
Your variables are
color.RND.hsv.v which is 100 when the marker is up and 0 when the marker is down
hsv_barHeight is the height of your component
The first step is to invert the value of color.RND.hsv.v i.e. (100 - color.RND.hsv.v) next we will map it to the range [0,1] which is simply done by a simple division i.e. t = (100 - color.RND.hsv.v) / 100 we do this so that the height is linearly mapped with this value t to be in the range [0, height] i.e. (100 - color.RND.hsv.v) / 100 * hsv_barHeight which is the final equation
var luminenceBarWrapper = document.getElementById('luminenceBarWrapper'),
hsv_barBGLayer = document.getElementById('bar-bg'),
hsv_barcursor = document.getElementById('hsv-barcursor'),
hsv_barCursors = document.getElementById('hsv-barcursors'),
hsv_barHeight = hsv_barCursors.offsetHeight,
cursorRadius = hsv_barcursor.offsetHeight / 2,
startPoint,
currentTarget,
myColor = new Colors();
// Create Event Functions
var hsvDown = function(e) { // mouseDown callback
e.preventDefault();
if (e.target === hsv_barcursor) currentTarget = e.target.parentNode;
else if (e.target === hsv_barCursors) currentTarget = e.target;
else return;
startPoint = getOrigin(currentTarget);
window.addEventListener('mousemove', hsvMove);
hsvMove(e);
startRender();
},
hsvMove = function(e) { // mouseMove callback
myColor.setColor({
v: (hsv_barHeight - (e.clientY - startPoint.top)) / hsv_barHeight * 100
}, 'hsv');
};
// Initial Rendering
doRender(myColor.colors);
// Adde Events To Objects
luminenceBarWrapper.addEventListener('mousedown', hsvDown);
window.addEventListener('mouseup', function() {
window.removeEventListener('mousemove', hsvMove);
stopRender();
});
function doRender(color) {
hsv_barcursor.style.transform = 'translateY(' + (100 - color.RND.hsv.v) / 100 * (hsv_barHeight - cursorRadius) + 'px)';
//hsv_barcursor.style.top = ((1 - color.hsv.v) * hsv_barHeight) + 'px';
}
var renderTimer,
startRender = function(oneTime) {
renderTimer = window.setInterval(function() {
doRender(myColor.colors);
}, 13); // 1000 / 60); // ~16.666 -> 60Hz or 60fps
},
stopRender = function() {
window.clearInterval(renderTimer);
};
function getOrigin(elm) {
var box = (elm.getBoundingClientRect) ? elm.getBoundingClientRect() : {
top: 0,
left: 0
},
doc = elm && elm.ownerDocument,
body = doc.body,
win = doc.defaultView || doc.parentWindow || window,
docElem = doc.documentElement || body.parentNode,
clientTop = docElem.clientTop || body.clientTop || 0, // border on html or body or both
clientLeft = docElem.clientLeft || body.clientLeft || 0;
return {
left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
};
}
body {
position: absolute;
}
#bar-bg {
width: 15px;
height: 500px;
background-color: greenyellow;
}
#hsv-barcursors {
position: absolute;
right: -7.5px;
width: 30px;
top: 0;
height: 500px;
overflow: hidden;
cursor: pointer;
}
#hsv-barcursor {
position: absolute;
right: 7.5px;
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid black;
margin-bottom: 5px;
}
<script src="https://rawgit.com/PitPik/colorPicker/master/colors.js"></script>
<div id="luminenceBarWrapper">
<div id="bar-bg"></div>
<div id="hsv-barcursors" id="hsv_cursors">
<div id="hsv-barcursor"></div>
</div>
</div>

Categories