'pointerup' event not firing on desktop, works fine on mobile - javascript

I'm trying to come up with a cross-device code that handles pointer events.
I'm running this code successfully on Chrome/Android (using USB debugging), but the Chrome desktop just acts up and keeps firing pointermove after the mouse has been released.
(Another problem is that the moves are not as smooth as on the mobile)
Playable demo
These SO posts don't solve my problem:
event-listener-with-pointerup-not-firing-when-activated-from-touchscreen
pointerup-event-does-not-fire-for-mouse-actions-on-a-link-when-pointermove-has-b

The "pointerup" Event is assigned to the #canvas, but such event will never occur because the mouse is actually above the generated DIV circle.
Since your circles are just visual helpers, set in CSS
.dot {
/* ... */
pointer-events: none;
}
Also, make sure to use Event.preventDefault() on "pointerdown".
Regarding the other strategies for a seamless experience, both on desktop and on mobile (touch):
assign only the "pointerdown" Event to a desired Element (canvas in your case)
use the window object for all the other events
Edited example:
const canvas = document.getElementById('canvas');
function startTouch(ev) {
ev.preventDefault();
const dot = document.createElement('div');
dot.classList.add('dot');
dot.id = ev.pointerId;
dot.style.left = `${ev.pageX}px`;
dot.style.top = `${ev.pageY}px`;
document.body.append(dot);
}
function moveTouch(ev) {
const dot = document.getElementById(ev.pointerId);
if (!dot) return;
dot.style.left = `${ev.pageX}px`;
dot.style.top = `${ev.pageY}px`;
}
function endTouch(ev) {
const dot = document.getElementById(ev.pointerId);
if (!dot) return;
removeDot(dot);
}
function removeDot(dot) {
dot.remove();
}
canvas.addEventListener('pointerdown', startTouch);
addEventListener('pointermove', moveTouch);
addEventListener('pointerup', endTouch);
addEventListener('pointercancel', endTouch);
.dot {
background-color: deeppink;
width: 2rem;
height: 2rem;
border-radius: 50%;
transform: translate(-50%, -50%);
position: absolute;
pointer-events: none; /* ADD THIS! */
}
#canvas {
height: 50vh;
background-color: black;
touch-action: none;
}
body {
margin: 0;
}
<div id="canvas"></div>
The code needs also this improvement:
Don't query the DOM inside a pointermove event
Using CSS vars
As per the comments section here's a viable solution that uses custom properties CSS variables and JS's CSSStyleDeclaration.setProperty() method.
Basically the --x and --y CSS properties values are updated from the pointerdown/move event handlers to reflect the current clientX and clientY values:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
const canvas = document.getElementById('canvas');
const pointersDots = (parent) => {
const elParent = typeof parent === "string" ? el(parent) : parent;
const dots = new Map();
const moveDot = (elDot, {clientX: x,clientY: y}) => {
elDot.style.setProperty("--x", x);
elDot.style.setProperty("--y", y);
};
const onDown = (ev) => {
ev.preventDefault();
const elDot = elNew("div", { className: "dot" });
moveDot(elDot, ev);
elParent.append(elDot);
dots.set(ev.pointerId, elDot);
};
const onMove = (ev) => {
if (dots.size === 0) return;
const elDot = dots.get(ev.pointerId);
moveDot(elDot, ev);
};
const onUp = (ev) => {
if (dots.size === 0) return;
const elDot = dots.get(ev.pointerId);
elDot.remove();
dots.delete(ev.pointerId);
};
canvas.addEventListener('pointerdown', onDown);
addEventListener('pointermove', onMove);
addEventListener('pointerup', onUp);
addEventListener('pointercancel', onUp);
};
// Init: Pointers helpers
pointersDots("#canvas");
* {
margin: 0;
}
.dot {
--x: 0;
--y: 0;
pointer-events: none;
position: absolute;
width: 2rem;
height: 2rem;
border-radius: 50%;
background-color: deeppink;
transform: translate(-50%, -50%);
left: calc(var(--x) * 1px);
top: calc(var(--y) * 1px);
}
#canvas {
margin: 10vh;
height: 80vh;
background-color: black;
touch-action: none;
}
<div id="canvas"></div>

Related

Disable javascript (custom cursor) on touch devices

Is it possible to a piece of javascript on mobile/tablet devices only? I'd like to do something a bit better than display: none and it makes sense to stop the script from running if it's not required?
Basically I have a custom cursor effect, that is only required when it follows the cursor on desktop with a mouse/trackpad.
This is the script I have:
var cursor = document.querySelector('.cursor-outer');
var cursorinner = document.querySelector('.cursor');
var a = document.querySelectorAll('a');
var moveCursor = true;
var radiusOfCursor = parseInt(getComputedStyle(cursor).getPropertyValue('width')) / 2; // radiusOfCursor = (width_of_cursor / 2).
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
cursorinner.style.left = x + 'px';
cursorinner.style.top = y + 'px';
if (!moveCursor) return;
cursor.style.marginLeft = `calc(${e.clientX}px - ${radiusOfCursor}px)`;
cursor.style.marginTop = `calc(${e.clientY}px - ${radiusOfCursor}px)`;
moveCursor = false;
setTimeout(() => {
moveCursor = true;
}, 32) // The wait time. I chose 95 because it seems to work just fine for me.
});
/* Centre pointer after stopping */
function mouseMoveEnd() {
cursor.style.marginLeft = `calc(${cursorinner.style.left} - ${radiusOfCursor}px)`;
cursor.style.marginTop = `calc(${cursorinner.style.top} - ${radiusOfCursor}px)`;
}
var x;
document.addEventListener('mousemove', function() {
if (x) clearTimeout(x);
x = setTimeout(mouseMoveEnd, 10);
}, false);
/* End */
document.addEventListener('mousedown', function() {
cursor.classList.add('click');
cursorinner.classList.add('cursorinnerhover');
});
document.addEventListener('mouseup', function() {
cursor.classList.remove('click');
cursorinner.classList.remove('cursorinnerhover');
});
a.forEach(item => {
item.addEventListener('mouseover', () => {
cursor.classList.add('hover');
});
item.addEventListener('mouseleave', () => {
cursor.classList.remove('hover');
});
});
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
cursorinner.classList.add(interaction);
});
item.addEventListener("mouseleave", () => {
cursorinner.classList.remove(interaction);
});
});
* {
cursor: none;
}
.cursor-outer {
border: 2px solid black;
border-radius: 100%;
box-sizing: border-box;
height: 32px;
pointer-events: none;
position: fixed;
top: 16px;
left: 16px;
transform: translate(-50%, -50%);
transition: height .12s ease-out, margin .12s ease-out, opacity .12s ease-out, width .12s ease-out;
width: 32px;
z-index: 100;
}
.cursor {
background-color: black;
border-radius: 100%;
height: 4px;
opacity: 1;
position: fixed;
transform: translate(-50%, -50%);
pointer-events: none;
transition: height .12s, opacity .12s, width .12s;
width: 4px;
z-index: 100;
}
<div class="cursor-outer"></div>
<div class="cursor"></div>
Thanks in advance!
Option #1
You can use something similar to this to determine if a device is touch-enabled:
isTouchDevice = () => {
return ( 'ontouchstart' in window ) ||
( navigator.maxTouchPoints > 0 ) ||
( navigator.msMaxTouchPoints > 0 );
};
This is adapted from Patrick H. Lauke's Detecting touch article on Mozilla.
Then just: if (isTouchDevice()) { /* Do touch screen stuff */}
Option #2
But maybe a pure CSS approach could work better in your situation, like:
#media (hover: none) {
.cursor {
pointer-events: none;
}
}
Option #3
If you don't mind using a third-party library, then Modernizr is really great for detecting things like this in the user's environment. Specifically, Modernizr.pointerevents will confirm if touchscreen is being used.

Remove the ability to hold down a keyboard key

I have a small page. Circles appear here, when you click on them they disappear.
I added here the possibility that in addition to clicking on the LMB, you can also click on a keyboard key, in my case it is "A".
But I noticed the problem that if you hold down the "A" button, then drive in circles, then the need for clicks disappears, and this is the main goal.
Can I somehow disable the ability to hold this button so that only clicking on it works?
I tried pasting this code, but all animations stopped working for me.
var down = false;
document.addEventListener('keydown', function () {
if(down) return;
down = true;
// your magic code here
}, false);
document.addEventListener('keyup', function () {
down = false;
}, false);
Get error:
"message": "Uncaught ReferenceError: mouseOverHandler is not defined"
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const keyDownHandler = (evt) => {
if(evt.keyCode === 65 && focusedEl) focusedEl.click();
}
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>
You can check the repeat property of the event, which
… is true if the given key is being held down such that it is automatically repeating.
(but notice the compatibility notes on auto-repeat handling)
const keyDownHandler = (evt) => {
if (!evt.repeat && evt.keyCode === 65) {
// ^^^^^^^^^^^
focusedEl?.click();
}
}
//create circle
var clickEl = document.getElementById("clicks");
var spawnRadius = document.getElementById("spawnRadius");
var spawnArea = spawnRadius.getBoundingClientRect();
const circleSize = 95; // Including borders
function createDiv(id, color) {
let div = document.createElement('div');
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#ebc6df', '#ebc6c9', '#e1c6eb', '#c6c9eb', '#c6e8eb', '#e373fb', '#f787e6', '#cb87f7', '#87a9f7', '#87f7ee'];
randomColor = colors[Math.floor(Math.random() * colors.length)];
div.style.borderColor = randomColor;
}
else {
div.style.borderColor = color;
}
// Randomly position circle within spawn area
div.style.top = `${Math.floor(Math.random() * (spawnArea.height - circleSize))}px`;
div.style.left = `${Math.floor(Math.random() * (spawnArea.width - circleSize))}px`;
div.classList.add("circle", "animation");
// Add click handler
let clicked = false;
div.addEventListener('mouseover', mouseOverHandler );
div.addEventListener('mouseout', mouseOutHandler );
div.addEventListener('click', (event) => {
if (clicked) { return; } // Only allow one click per circle
clicked = true;
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => { spawnRadius.removeChild(div); }, 220);
});
spawnRadius.appendChild(div);
}
let i = 0;
const rate = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`);
}, rate);
let focusedEl = null;
const mouseOutHandler = (evt) => focusedEl = null;
const mouseOverHandler = (evt) => focusedEl = evt.currentTarget;
document.addEventListener('keydown', keyDownHandler );
window.focus();
html, body {
width: 100%;
height: 100%;
margin: 0;
background: #0f0f0f;
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
background-color: #0f0f0f;
border: 3px solid #000;
position: absolute;
}
#spawnRadius {
top: 55%;
height: 250px;
width: 500px;
left: 50%;
white-space: nowrap;
position: absolute;
transform: translate(-50%, -50%);
background: #0f0f0f;
border: 2px solid #ebc6df;
}
#keyframes Animation {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
opacity: 0;
}
}
<html>
<body>
<div id="spawnRadius"></div>
</body>
</html>

Why is the distance between first and last element decreasing?

I'm trying to make an image slider. But as you can see the distance between the first and last element is not consistent. If you keep on dragging to left, the distance decreases and if you keep on dragging to right, the distance increases. Looks like the code is behaving differently on different zoom levels (sometimes?) and hence distance between every elements is changing at times.
//project refers to placeholder rectangular divs
projectContainer = document.querySelector(".project-container")
projects = document.querySelectorAll(".project")
elementAOffset = projects[0].offsetLeft;
elementBOffset = projects[1].offsetLeft;
elementAWidth = parseInt(getComputedStyle(projects[0]).width)
margin = (elementBOffset - (elementAOffset + elementAWidth))
LeftSideBoundary = -(elementAWidth)
RightSideBoundary = (elementAWidth * (projects.length)) + (margin * (projects.length))
RightSidePosition = RightSideBoundary - elementAWidth;
initialPosition = 0; //referring to mouse
mouseIsDown = false
projectContainer.addEventListener("mousedown", e => {
mouseIsDown = true
initialPosition = e.clientX;
})
projectContainer.addEventListener("mouseup", e => {
mouseExit(e)
})
projectContainer.addEventListener("mouseleave", e => {
mouseExit(e);
})
function mouseExit(e) {
mouseIsDown = false
//updates translateX value of transform
projects.forEach(project => {
var style = window.getComputedStyle(project)
project.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
project.style.transform = 'translateX(' + (project.currentTranslationX) + 'px)'
})
}
projectContainer.addEventListener("mousemove", e => {
if (!mouseIsDown) { return };
// adds mousemovement to translateX
projects.forEach(project => {
project.style.transform = 'translateX(' + ((project.currentTranslationX ?? 0) + (e.clientX - initialPosition)) + 'px)'
shiftPosition(e, project)
})
})
//teleports div if it hits left or right boundary to make an infinite loop
function shiftPosition(e, project) {
projectStyle = window.getComputedStyle(project)
projectTranslateX = (new WebKitCSSMatrix(projectStyle.webkitTransform)).m41
//projectVisualPosition is relative to the left border of container div
projectVisualPosition = project.offsetLeft + projectTranslateX
if (projectVisualPosition <= LeftSideBoundary) {
project.style.transform = "translateX(" + ((RightSidePosition - project.offsetLeft)) + "px)"
updateTranslateX(e);
}
if (projectVisualPosition >= RightSidePosition) {
newPosition = -1 * (project.offsetLeft + elementAWidth)
project.style.transform = "translateX(" + newPosition + "px)"
updateTranslateX(e);
}
}
function updateTranslateX(e) {
projects.forEach(project => {
style = window.getComputedStyle(project)
project.currentTranslationX = (new WebKitCSSMatrix(style.webkitTransform)).m41
project.style.transform = 'translateX(' + (project.currentTranslationX) + 'px)'
initialPosition = e.clientX
})
}
*, *::before, *::after{
margin:0px;
padding:0px;
box-sizing: border-box;
font-size:0px;
user-select: none;
}
.project-container{
font-size: 0px;
position: relative;
width:1500px;
height:400px;
background-color: rgb(15, 207, 224);
margin:auto;
margin-top:60px;
white-space: nowrap;
overflow: hidden;
padding-left:40px;
padding-right:40px;
}
.project{
font-size:100px;
margin:40px;
display: inline-block;
height:300px;
width:350px;
background-color:red;
border: black 3px solid;
user-select: none;
}
<div class="project-container">
<div class="project">1</div>
<div class="project">2</div>
<div class="project">3</div>
<div class="project">4</div>
<div class="project">5</div>
<div class="project">6</div>
<div class="project">7</div>
<div class="project">8</div>
</div>
I'm not sure exactly how you would go about fixing your implementation. I played around with it for a while and discovered a few things; dragging more quickly makes the displacement worse, and the displacement seems to happen mainly when the elements are teleported at each end of the container.
I would guess that the main reason for this is that you are looping over all the elements and spacing them individually. Mouse move events generally happen under 20ms apart, and you are relying on all the DOM elements being repainted with their new transform positions before the next move is registered.
I did come up with a different approach using absolutely placed elements and the IntersectionObserver API, which is now supported in all modern browsers. The idea here is basically that when each element intersects with the edge of the container, it triggers an array lookup to see if the next element in the sequence is on the correct end and moves it there if not. Elements are only ever spaced by a static variable, while the job of sliding them is passed up to a new parent wrapper .project-slider.
window.addEventListener('DOMContentLoaded', () => {
// Style variables
const styles = {
width: 350,
margin: 40
};
const space = styles.margin*2 + styles.width;
// Document variables
const projectContainer = document.querySelector(".project-container");
const projectSlider = document.querySelector(".project-slider");
const projects = Array.from(document.querySelectorAll(".project"));
// Mouse interactions
let dragActive = false;
let prevPos = 0;
projectContainer.addEventListener('mousedown', e => {
dragActive = true;
prevPos = e.clientX;
});
projectContainer.addEventListener('mouseup', () => dragActive = false);
projectContainer.addEventListener('mouseleave', () => dragActive = false);
projectContainer.addEventListener('mousemove', e => {
if (!dragActive) return;
const newTrans = projectSlider.currentTransX + e.clientX - prevPos;
projectSlider.style.transform = `translateX(${newTrans}px)`;
projectSlider.currentTransX = newTrans;
prevPos = e.clientX;
});
// Generate initial layout
function init() {
let workingLeft = styles.margin;
projects.forEach((project, i) => {
if (i === projects.length - 1) {
project.style.left = `-${space - styles.margin}px`;
} else {
i !== 0 && (workingLeft += space);
project.style.left = `${workingLeft}px`;
};
});
projectSlider.currentTransX = 0;
};
// Intersection observer
function observe() {
const callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Find intersecting edge
const { left } = entry.boundingClientRect;
const isLeftEdge = left < projectContainer.clientWidth - left;
// Test and reposition next element
const targetIdx = projects.findIndex(project => project === entry.target);
let nextIdx = null;
const nextEl = () => projects[nextIdx];
const targetLeft = parseInt(entry.target.style.left);
const nextLeft = () => parseInt(nextEl().style.left);
if (isLeftEdge) {
nextIdx = targetIdx === 0 ? projects.length-1 : targetIdx - 1;
nextLeft() > targetLeft && (nextEl().style.left = `${targetLeft - space}px`);
} else {
nextIdx = targetIdx === projects.length-1 ? 0 : targetIdx + 1;
nextLeft() < targetLeft && (nextEl().style.left = `${targetLeft + space}px`);
};
};
});
};
const observer = new IntersectionObserver(callback, {root: projectContainer});
projects.forEach(project => observer.observe(project));
};
init();
observe();
});
*, *::before, *::after{
margin:0px;
padding:0px;
box-sizing: border-box;
font-size:0px;
user-select: none;
}
.project-container {
font-size: 0px;
width: 100%;
height: 400px;
background-color: rgb(15, 207, 224);
margin:auto;
margin-top:60px;
white-space: nowrap;
overflow: hidden;
}
.project-slider {
position: relative;
}
.project {
font-size:100px;
display: block;
position: absolute;
top: 40px;
height:300px;
width:350px;
background-color:red;
border: black 3px solid;
user-select: none;
}
<div class="project-container">
<div class="project-slider">
<div class="project">1</div>
<div class="project">2</div>
<div class="project">3</div>
<div class="project">4</div>
<div class="project">5</div>
<div class="project">6</div>
<div class="project">7</div>
<div class="project">8</div>
</div>
</div>
There is still an issue here which is how to resize the elements for smaller screens, and on browser resizes. You would have to add another event listener for window resizes which resets the positions and styles at certain breakpoints, and also determine the style variables programmatically when the page first loads. I believe this would still have been a partial issue with the original implementation so you'd have to address it at some point either way.

How to change the cursor icon when dragging in HTML5?

I need to set the icon for cursor when a user is dragging DIV (red div in the following example).
I have tried several attempt, including using CSS cursor:move and event.dataTransfer.dropEffect with no success, as the icon always show up a "crossed circle".
Any ideas how to solve this issue using HTML5 drag-and-drop API?
http://jsbin.com/hifidunuqa/1/
<script>
window.app = {
config: {
canDrag: false,
cursorOffsetX: null,
cursorOffsetY: null
},
reset: function () {
this.config.cursorOffsetX = null;
this.config.cursorOffsetY = null;
},
start: function () {
document.getElementById('target').addEventListener('dragstart', function (event) {
console.log('+++++++++++++ dragstart')
this.config.cursorOffsetX = event.offsetX;
this.config.cursorOffsetY = event.offsetY;
this.adjustPostion(event);
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.dropEffect = 'move';
}.bind(this));
document.getElementById('target').addEventListener('drag', function (event) {
console.log('+++++++++++++ drag')
this.adjustPostion(event);
}.bind(this));
document.getElementById('target').addEventListener('dragend', function (event) {
console.log('+++++++++++++ dragend')
this.reset();
}.bind(this));;
},
adjustPostion: function (event) {
if (event.pageX <= 0 || event.pageY <= 0) {
console.log('skipped');
return;
}
var elm = document.getElementById('target');
elm.style.left = (event.pageX - this.config.cursorOffsetX) + 'px';
elm.style.top = (event.pageY - this.config.cursorOffsetY) + 'px';
console.log(event.pageX);
console.log(event.pageY);
}
};
</script>
use mousedown and mousemove
window.app = {
dragging: false,
config: {
canDrag: false,
cursorOffsetX: null,
cursorOffsetY: null
},
reset: function () {
this.config.cursorOffsetX = null;
this.config.cursorOffsetY = null;
},
start: function () {
document.getElementById('target').addEventListener('mousedown', function (event) {
console.log('+++++++++++++ dragstart');
this.dragging = true;
this.config.cursorOffsetX = event.offsetX;
this.config.cursorOffsetY = event.offsetY;
this.adjustPostion(event);
}.bind(this));
document.getElementById('target').addEventListener('mousemove', function (event) {
if (this.dragging) {
console.log('+++++++++++++ drag');
event.target.style.cursor = 'move';
this.adjustPostion(event);
}
}.bind(this));
document.getElementById('target').addEventListener('mouseup', function (event) {
console.log('+++++++++++++ dragend');
this.dragging = false;
event.target.style.cursor = 'pointer';
this.reset();
}.bind(this));
},
adjustPostion: function (event) {
if (event.clientX <= 0 || event.clientY <= 0) {
console.log('skipped');
return;
}
var elm = document.getElementById('target');
elm.style.left = (event.clientX - this.config.cursorOffsetX) + 'px';
elm.style.top = (event.clientY - this.config.cursorOffsetY) + 'px';
console.log(event.pageX);
console.log(event.pageY);
}
};
#target {
position: absolute;
top: 100px;
left: 100px;
width: 400px;
height: 400px;
background-color: red;
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
user-select: none;
}
#ui1 {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 400px;
background-color: blue;
z-index: 100;
}
#ui2 {
position: absolute;
top: 50px;
left: 550px;
width: 100px;
height: 400px;
background-color: green;
z-index: 100;
}
<!-- simulate -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body onload="window.app.start();">
<div id="ui1"></div>
<div id="ui2"></div>
<div id="target"></div>
</body>
</html>
Do you actually need the Drag API? I found that I was using the Drag API because I was having trouble with the reliability of mouse events (mouseups not being captured, for example).
The Drag API is only for drag-and-drop functionality, and, if you're simply fiddling with the reliability of your clicking and pointing events, a new API, .setPointerCapture is made to handle these cases more effectively. Here's the minimal viable way to achieve this:
el.onpointerdown = ev => {
el.onpointermove = pointerMove
el.setPointerCapture(ev.pointerId)
}
pointerMove = ev => {
console.log('Dragged!')
}
el.onpointerUp = ev => {
el.onpointermove = null
el.releasePointerCapture(ev.pointerId)
}
Beautifully, you will maintain full control over your cursor's display style.
I didn't care about a particular cursor, I just wanted to get rid of the "crossed circle" one. My solution was to include dragover event (with following function) to all elements, that already had dragenter, dragstart and dragend events.
function dragover(event)
{
event.dataTransfer.dropEffect = "move";
event.preventDefault();
}
Adding event.dataTransfer.setData(); should solve the problem. Once the element is recognized as draggable the browser will add a move cursor automatically once you drag. Of course, you will have to remove all other cursor: move declarations to see the cursor changing while dragging.
Minimal example:
document.getElementById('target').addEventListener('dragstart', function (event) {
event.dataTransfer.setData( 'text/plain', '' );
}.bind(this));
If you still want to change the icon (e.g. to use a custom drag icon), you could access the element style using event.target.style.cursor.
For more info see MDN Drag & Drop and MDN Recommended Drag Types

Using two of the same javascripts

I've been trying to create a page with several before and after images (Using a slider to swap between the two).
However when I add the second piece of JavaScript code, it breaks the page. Even if I try to amend the (var) code to be unique from the previous script
In all honesty I don't quite understand what the JavaScript is doing which is why I'm probably unable to Google the solution. Any help would be appreciated, if you could try to explain in as much detail what I need to do and explain any specific terms that would help me develop further.
You can see all my code on the link (and below): http://codepen.io/sn0wm0nkey/pen/DakbA
var inkbox = document.getElementById("inked-painted");
var colorbox = document.getElementById("colored");
var fillerImage = document.getElementById("inked");
inkbox.addEventListener("mousemove",trackLocation,false);
inkbox.addEventListener("touchstart",trackLocation,false);
inkbox.addEventListener("touchmove",trackLocation,false);
function trackLocation(e)
{
var rect = inked.getBoundingClientRect();
var position = ((e.pageX - rect.left) / inked.offsetWidth)*100;
if (position <= 100) { colorbox.style.width = position+"%"; }
}
/* -----second JavaScript code---- */
var inkbox1 = document.getElementById("inked1-painted");
var colorbox1 = document.getElementById("colored1");
var fillerImage1 = document.getElementById("inked1");
inkbox1.addEventListener("mousemove",trackLocation,false);
inkbox1.addEventListener("touchstart",trackLocation,false);
inkbox1.addEventListener("touchmove",trackLocation,false);
function trackLocation(e1)
{
var rect1 = inked.getBoundingClientRect();
var position1 = ((e1.pageX - rect1.left) / inked1.offsetWidth)*100;
if (position1 <= 100) { colorbox1.style.width = position1+"%"; }
}
body { background: #113; }
div#inked-painted {
position: relative; font-size: 0;
-ms-touch-action: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
}
div#inked-painted img {
width: 100%; height: auto;
}
div#colored {
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/colored-panel.jpg);
position: absolute;
top: 0; left: 0; height: 100%;
width: 50%;
background-size: cover;
}
div#inked-painted:hover {
cursor: col-resize;
}
/*-------- second css sheet --------- */
div#inked1-painted {
position: relative; font-size: 0;
-ms-touch-action: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
}
div#inked1-painted img {
width: 100%; height: auto;
}
div#colored1 {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 50%;
background-size: cover;
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/colored-panel.jpg);
}
div#inked1-painted:hover {
cursor: col-resize;
}
<Div>
<div id="inked-painted">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/inked-panel.png" id="inked" alt>
<div id="colored"></div>
</div>
<p></p>
<div>
<div id="inked1-painted">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/inked-panel.png" id="inked1" alt>
<div id="colored1"></div>
</div>
Howard's solution works but can be improved even more to remove duplication.
Use classes instead of Ids
Find the elements inside the div that is receiving the mousemove instead of passing them in
Don't duplicate the CSS
function onMouseMove(e) {
var inked = this.getElementsByTagName("img")[0];
var colorbox = this.querySelector('.colored');
var rect = inked.getBoundingClientRect();
var position = ((e.pageX - rect.left) / inked.offsetWidth) * 100;
if (position <= 100) {
colorbox.style.width = position + "%";
}
}
function trackLocation(el) {
el.addEventListener("mousemove", onMouseMove, false);
el.addEventListener("touchstart", onMouseMove, false);
el.addEventListener("touchmove", onMouseMove, false);
}
var wrappers = document.querySelectorAll('.inked-painted');
for (var i = 0; i < wrappers.length; i++) {
trackLocation(wrappers[i]);
}
div.inked-painted {
position: relative;
font-size: 0;
-ms-touch-action: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
}
div.inked-painted img {
width: 100%;
height: auto;
}
.colored {
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/colored-panel.jpg);
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 50%;
background-size: cover;
}
div.inked-painted:hover {
cursor: col-resize;
}
<div class="inked-painted">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/inked-panel.png" />
<div class="colored"></div>
</div>
<p></p>
<div class="inked-painted">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/inked-panel.png" />
<div class="colored"></div>
</div>
First, Java != JavaScript. They are two very different languages.
Second, your issue is that your second function is named the same as your first function. The second one essentially overwrites the first one, so the first doesn't exist any longer. Simply use a different name for your second function, and your code works just fine.
However, it would be better to find a way to reuse your first function, instead of having two almost identical functions.
Here is what you are doing with your JavaScript how it is currently written.
Declare and assign variables inkbox, colorbox, fillerImage
Add event handlers
Create a function in the global scope by the name of trackLocation
Declare and assign variables inkbox1, colorbox1, fillerImage1
Add event handlers
Overwrite the trackLocation function in the global scope
All of this is being done synchronously, just as I have it listed here. So, when an event fires on inkbox, it calls the new function that overwrote the original.
Another problem that I see (unless you omitted some code) is you have some variables that are not defined, which will cause a problem within your function.
function trackLocation (e) {
// inked is undefined
var rect = inked.getBoundingClientRect();
// inked is undefined
var position = ((e.pageX - rect.left) / inked.offsetWidth)*100;
if (position <= 100) { colorbox.style.width = position+"%"; }
}
You'll need to rewrite your function to accept local variables like this:
function trackLocation (e, inked, colorbox) {
var rect = inked.getBoundingClientRect();
var position = ((e.pageX - rect.left) / inked.offsetWidth)*100;
if (position <= 100) { colorbox.style.width = position+"%"; }
}
Now this one function can be reused in all of your event handlers, like this:
function trackLocation (e, inked, colorbox) {
var rect = inked.getBoundingClientRect();
var position = ((e.pageX - rect.left) / inked.offsetWidth)*100;
if (position <= 100) { colorbox.style.width = position+"%"; }
}
var inkbox = document.getElementById("inked-painted");
var colorbox = document.getElementById("colored");
var fillerImage = document.getElementById("inked");
inkbox.addEventListener("mousemove", function (e) { trackLocation(e, inkbox, colorbox); });
inkbox.addEventListener("touchstart", function (e) { trackLocation(e, inkbox, colorbox); });
inkbox.addEventListener("touchmove", function (e) { trackLocation(e, inkbox, colorbox); });
var inkbox1 = document.getElementById("inked1-painted");
var colorbox1 = document.getElementById("colored1");
var fillerImage1 = document.getElementById("inked1");
inkbox1.addEventListener("mousemove", function (e) { trackLocation(e, inkbox1, colorbox1); });
inkbox1.addEventListener("touchstart", function (e) { trackLocation(e, inkbox1, colorbox1); });
inkbox1.addEventListener("touchmove", function (e) { trackLocation(e, inkbox1, colorbox1); });

Categories