Dragging DIV with JavaScript mouse events moves to quickly - javascript

Im trying to move the #frame-slider-thumb across the image. I had it working by just keeping track of the diff in mouseX position. But the problem was that if the thumb wasn't at 0 to begin with it would jump back to 0. Thus I added the curr variable in the logic to add the diff from its current position. Now it moves much to quickly though. I'm not sure why. Any help much appreciated.
Heres a codepen.
HTML
<div id="frame-slider">
<img id="frame-slider-background" src="http://imagej.1557.x6.nabble.com/file/n5009735/OCT_pre_segmented.png" alt="" />
<div id="frame-slider-track">
<div id="frame-slider-thumb">
<div class="top-half"></div>
<div class="bottom-half"></div>
</div>
</div>
</div>
JS
var mouseStartPosition = {};
var thumb = document.getElementById('frame-slider-thumb');
window.addEventListener("mousedown", mousedownThumb);
function mousedownThumb(e) {
mouseStartPosition.x = e.pageX;
// add listeners for mousemove, mouseup
window.addEventListener("mousemove", mousemoveThumb);
window.addEventListener("mouseup", mouseupThumb);
}
function mousemoveThumb(e) {
var curr = isNaN(parseFloat(thumb.style.left)) ? 0 : parseFloat(thumb.style.left);
var diff = -1 * (mouseStartPosition.x - e.pageX);
var newLeft = curr + diff;
thumb.style.left = newLeft + 'px';
}
function mouseupThumb(e) {
window.removeEventListener("mousemove", mousemoveThumb);
window.removeEventListener("mouseup", mouseupThumb);
}
CSS
html,
body {
width: 100%;
height: 100%;
}
#frame-slider {
height: 150px;
width: 50%;
position: relative;
}
#frame-slider-background {
width: 100%;
max-height: 100%;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-user-drag: none;
user-drag: none;
-webkit-touch-callout: none;
}
#frame-slider-track {
height: 100%;
width: 100%;
position: absolute;
top: 0;
}
#frame-slider-thumb {
position: absolute;
left: 0;
margin-left: -4px;
width: 8px;
height: 100%;
cursor: pointer;
}
#frame-slider-thumb .top-half {
background-color: rgba(0, 0, 255, 0.7);
height: 50%;
}
#frame-slider-thumb .bottom-half {
background-color: rgba(255, 0, 0, 0.7);
height: 50%;
}

Fixed by adding a thumbStart position to mousedownThumb. Basically diff isn't the difference in position from the last mousemove event, its the difference from the last mousemove event and the mousedown event.
var mouseStartPosition = {};
var thumbStart;
var thumb = document.getElementById('frame-slider-thumb');
window.addEventListener("mousedown", mousedownThumb);
function mousedownThumb(e) {
mouseStartPosition.x = e.pageX;
thumbStart = isNaN(parseFloat(thumb.style.left)) ? 0 : parseFloat(thumb.style.left);
// add listeners for mousemove, mouseup
window.addEventListener("mousemove", mousemoveThumb);
window.addEventListener("mouseup", mouseupThumb);
}
function mousemoveThumb(e) {
var diff = -1 * (mouseStartPosition.x - e.pageX);
var newLeft = thumbStart + diff;
thumb.style.left = newLeft + 'px';
}
function mouseupThumb(e) {
window.removeEventListener("mousemove", mousemoveThumb);
window.removeEventListener("mouseup", mouseupThumb);
}

Related

Click event does not work with custom cursor

I am trying to create a custom cursor on a website (a blurry yellow spot). I created a div in HTML for the custom cursor and styled it in CSS. I gave the 'cursor: none' property to the body tag to hide the default cursor. I also put 'pointer-events: none' on the custom cursor div. Still, click events are not (or hardly) working on buttons (for example I cannot close a pop-up window with the close button). When I remove 'cursor: none', everything works fine, but the default cursor returns beside the yellow spot. Could you please help me in solving this? How could I remove the default cursor without affecting click events? Thank you in advance.
// move yellow spot as cursor
const moveCursor = (e) => {
const mouseY = e.clientY;
const mouseX = e.clientX;
const yellowSpot = document.querySelector(".yellow-spot");
yellowSpot.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`;
}
window.addEventListener('mousemove', moveCursor);
document.querySelector("input[type=button]").addEventListener("click", () => {
console.log("Button clicked");
});
*,
body {
cursor: none !important;
}
.yellow-spot {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 1.625rem;
height: 1.625rem;
border-radius: 50%;
background: #ffeb77;
box-shadow: 0 0 15px 5px #ffeb77;
pointer-events: none;
}
<div class="yellow-spot"></div>
<input type="button" value="Click Me">
The issue is that the actual cursor is at the top-left of the yellow spot, not in the middle, so it's easy to miss things when trying to click on them. You can see that if you remove the cursor: none rule:
// move yellow spot as cursor
const moveCursor = (e) => {
const mouseY = e.clientY;
const mouseX = e.clientX;
const yellowSpot = document.querySelector(".yellow-spot");
yellowSpot.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`;
}
window.addEventListener('mousemove', moveCursor);
document.querySelector("input[type=button]").addEventListener("click", () => {
console.log("Button clicked");
});
*,
body {
/* cursor: none !important; */
}
.yellow-spot {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 1.625rem;
height: 1.625rem;
border-radius: 50%;
background: #ffeb77;
box-shadow: 0 0 15px 5px #ffeb77;
pointer-events: none;
}
<div class="yellow-spot"></div>
<input type="button" value="Click Me">
To fix it, center the yellow spot over the cursor rather than moving it to the top-left (I also changed how the yellow spot is moved, but that's not the important thing):
const yellowSpot = document.querySelector('.yellow-spot');
// move the yellow spot to the mouse position
document.addEventListener('mousemove', function(e) {
// Make sure the *center* of the yellow spot is where the
// cursor is, not the top left
const {clientWidth, clientHeight} = yellowSpot;
yellowSpot.style.left = ((e.pageX - (clientWidth / 2)) + 'px');
yellowSpot.style.top = (e.pageY - (clientHeight / 2)) + 'px';
});
*,
body {
cursor: none !important;
}
.yellow-spot {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 1.625rem;
height: 1.625rem;
border-radius: 50%;
background: #ffeb77;
box-shadow: 0 0 15px 5px #ffeb77;
pointer-events: none;
}
<div class="yellow-spot"></div>
<button onclick="alert('test')">Click me</button>
Here's a version with the cursor showing so you can see how it's centered in the yellow spot now:
const yellowSpot = document.querySelector('.yellow-spot');
// move the yellow spot to the mouse position
document.addEventListener('mousemove', function(e) {
// Make sure the *center* of the yellow spot is where the
// cursor is, not the top left
const {clientWidth, clientHeight} = yellowSpot;
yellowSpot.style.left = ((e.pageX - (clientWidth / 2)) + 'px');
yellowSpot.style.top = (e.pageY - (clientHeight / 2)) + 'px';
});
*,
body {
/*cursor: none !important;*/
}
.yellow-spot {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 1.625rem;
height: 1.625rem;
border-radius: 50%;
background: #ffeb77;
box-shadow: 0 0 15px 5px #ffeb77;
pointer-events: none;
}
<div class="yellow-spot"></div>
<button onclick="alert('test')">Click me</button>

Problems with moving a div by cursor if I move it too fast

to specify my question I wrote an standalone example of my problem. I want to precisely move a div inside a wrapping container (only in x-direction), like a trackbar. The wrapping div should specify the space for the slider.
My script works, if I slowly move the cursor. But if I move the cursor too fast I kind of loose the slider div somewhere inside the container. Especially in the right and left corner.
How can I improve the code to have a stable solution, without the need of librarys? I know that there is a kind of simple solution with jQuery, but I would be very happy if we could find a way in plain javascript.
var x_mouse_position;
var x_offset;
var isDown = false;
var new_slider_left_position;
var container = document.getElementById("container");
var slider = document.getElementById("slider");
slider.addEventListener('mousedown', function (e) {
isDown = true;
x_offset = slider.offsetLeft - e.clientX;
}, true);
document.addEventListener('mouseup', function () {
isDown = false;
}, true);
document.addEventListener('mousemove', function (event) {
if (isDown) {
x_mouse_position = event.clientX;
new_slider_left_position = x_mouse_position + x_offset;
if (new_slider_left_position >= 0 && new_slider_left_position <= container.offsetWidth - slider.offsetWidth) {
slider.style.left = new_slider_left_position + 'px';
}
}
}, true);
html,
body {
height: 100%;
width: 100%;
}
body {
background-color: antiquewhite;
display: flex;
justify-content: center;
align-items: center;
}
#container {
position: relative;
width: 400px;
height: 30px;
background-color: cornflowerblue;
border-radius: 5px;
overflow: hidden;
}
#slider {
position: absolute;
top: 0;
left: 0;
box-sizing: border-box;
border: 1px solid black;
width: 50px;
height: 100%;
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.2);
cursor: move;
}
<div id="container">
<div id="slider"></div>
</div>

Follow mouse on Hover of Div but only on Div

Not sure how to do this but I have the first part setup right via the codepen here
Not sure how to stop it from occurring unless you hover the black div. Basically I'm looking to have the normal mouse functionality until you hover this black div than fire the script/function. I'm also trying to achieve this without using any libraries and just JS.
Code Below
document.addEventListener("mousemove", function() {
myFunction(event);
});
var mouse;
var cursor = document.getElementById("cursor");
function myFunction(e) {
mouseX = e.clientX;
mouseY = e.clientY;
cursor.style.left = (mouseX - 55) + "px";
cursor.style.top = (mouseY - 55) + "px";
}
body {
background: #FFFDFA;
}
#cursor {
height: 100px;
width: 100px;
position: absolute;
backface-visibility: hidden;
z-index: 9999999;
cursor: none;
}
div {
background: black;
width: 200px;
height: 100px;
margin: 30px;
cursor: none;
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor"></img>
<div>
</div>
You can simply add the event listener to the div element. You also need to disable pointerEvents on the cursor element so that the mouse doesn't register as on top of the cursor rather than the div.
document.getElementById("div").addEventListener("mousemove", function() {
myFunction(event);
});
var mouse;
var cursor = document.getElementById("cursor");
function myFunction(e) {
mouseX = e.clientX;
mouseY = e.clientY;
cursor.style.left = (mouseX - 55) + "px";
cursor.style.top = (mouseY - 55) + "px";
}
body {
background: #FFFDFA;
}
#cursor {
height: 100px;
width: 100px;
position: absolute;
backface-visibility: hidden;
z-index: 9999999;
pointer-events: none; /* pointer-events: none is needed */
cursor: none;
}
div {
background: black;
width: 200px;
height: 100px;
margin: 30px;
cursor: none;
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor"></img>
<div id="div"></div> <!--add id-->
EDIT: If you want the cursor to disappear on mouseout:
document.getElementById("div").addEventListener("mousemove", function() {
myFunction(event);
});
var mouse;
var cursor = document.getElementById("cursor");
function myFunction(e) {
mouseX = e.clientX;
mouseY = e.clientY;
cursor.style.left = (mouseX - 55) + "px";
cursor.style.top = (mouseY - 55) + "px";
}
body {
background: #FFFDFA;
}
#cursor {
height: 100px;
width: 100px;
position: absolute;
backface-visibility: hidden;
z-index: 9999999;
pointer-events: none; /* pointer-events: none is needed */
cursor: none;
}
div {
background: black;
width: 200px;
height: 100px;
margin: 30px;
cursor: none;
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor" hidden></img>
<div id="div" onmouseenter="cursor.hidden = false" onmouseleave="cursor.hidden=true"></div> <!--make cursor invisible on leave and visible on enter-->

mousedown and touchstart not registering on mobile devices

I have created the following simple image comparison slider - modified from the version on w3schools (I know my mistake to use their code).
This all works fine on a desktop but when I try to use it on a mobile, nothing happens - it doesn't even register the console.log on the mousedown/touchstart (when I press on the slider button with my finger).
I was wondering if anyone could spot anything obvious with why it isn't working on mobile devices
(() => {
$.fn.imageComparisonSlider = function() {
var returnValue = this.each((index, item) => {
var $container = $(this);
var $overlay = $container.find('.image-comparison-slider__bottom-image');
var $slider = $('<span class="image-comparison-slider__slider"></span>');
var $window = $(window);
var touchStarted = false;
var width = $container.outerWidth();
$container.prepend($slider);
$container.on('mousedown touchstart', '.image-comparison-slider__slider', event => {
event.preventDefault();
console.log('touchstart');
touchStarted = true;
});
$window.on("mousemove touchmove", windowEvent => {
if (touchStarted) {
// get the cursor's x position:
let pos = getCursorPos(windowEvent);
// prevent the slider from being positioned outside the image:
if (pos < 0) pos = 0;
if (pos > width) pos = width;
// execute a function that will resize the overlay image according to the cursor:
slide(pos);
}
});
$window.on('mouseup touchend', event => {
event.preventDefault();
touchStarted = false;
});
function getCursorPos(e) {
var thisEvent = e || window.event;
// calculate the cursor's x coordinate, relative to the image
return thisEvent.pageX - $container.offset().left;
}
function slide(x) {
// set the width of the overlay
$overlay.width(width - x);
// position the slider
$slider[0].style.left = x + 'px';
}
function resetSlider() {
$overlay.width('50%');
$slider[0].style.left = $overlay.width() + 'px'
width = $container.outerWidth();
}
});
return returnValue;
};
})($);
$('.image-comparison-slider__container').imageComparisonSlider();
.image {
display: block;
width: 100%;
}
.image-comparison-slider__title {
text-align: center;
}
.image-comparison-slider__container,
.image-comparison-slider__image-holder {
position: relative;
}
.image-comparison-slider__bottom-image {
position: absolute;
overflow: hidden;
top: 0;
right: 0;
bottom: 0;
z-index: 1;
width: 50%;
}
.image-comparison-slider__caption {
position: absolute;
padding: 1rem;
color: white;
background: rgba(0, 0, 0, 0.6);
z-index: 2;
white-space: nowrap;
}
.image-comparison-slider__top-image .image-comparison-slider__caption {
top: 0;
left: 0;
}
.image-comparison-slider__bottom-image .image-comparison-slider__caption {
bottom: 0;
right: 0;
}
.image-comparison-slider__image {
display: block;
z-index: 1;
}
.image-comparison-slider__bottom-image .image {
position: absolute;
right: 0;
top: 0;
height: 100%;
width: auto;
}
.image-comparison-slider__slider {
position: absolute;
z-index: 3;
cursor: ew-resize;
/*set the appearance of the slider:*/
width: 50px;
height: 50px;
background-color: rgba(255, 96, 38, 0.8);
border-radius: 50%;
top: 50%;
left: 50%;
display: flex;
justify-content: center;
align-items: center;
transform: translate(-50%, -50%);
}
.image-comparison-slider__slider:after {
content: "< >";
color: white;
font-weight: bold;
font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-comparison-slider__container">
<div class="image-comparison-slider__image-holder image-comparison-slider__top-image">
<img src="https://www.fillmurray.com/g/400/300" alt="A test image 1" class="image">
<div class="image-comparison-slider__caption">Left Image</div>
</div>
<div class="image-comparison-slider__image-holder image-comparison-slider__bottom-image">
<img src="https://www.fillmurray.com/400/300" alt="A test image 2" class="image">
<div class="image-comparison-slider__caption">Right Image</div>
</div>
</div>
Fiddle link for code
Ok have managed to fix this - the touch wasn't registering because of the transform so I changed that and just used negative margin as the button was a fixed size.
I then had to fix the thisEvent.pageX for android - so did a check with isNaN and then set it to e.originalEvent.touches[0].pageX if it was true.
Working version:
(() => {
$.fn.imageComparisonSlider = function() {
var returnValue = this.each((index, item) => {
var $container = $(this);
var $overlay = $container.find('.image-comparison-slider__bottom-image');
var $slider = $('<span class="image-comparison-slider__slider"></span>');
var $window = $(window);
var touchStarted = false;
var width = $container.outerWidth();
$container.prepend($slider);
$container.on('mousedown touchstart', '.image-comparison-slider__slider', event => {
event.preventDefault();
console.log('touchstart');
touchStarted = true;
});
$window.on("mousemove touchmove", windowEvent => {
if (touchStarted) {
// get the cursor's x position:
let pos = getCursorPos(windowEvent);
// prevent the slider from being positioned outside the image:
if (pos < 0) pos = 0;
if (pos > width) pos = width;
// execute a function that will resize the overlay image according to the cursor:
slide(pos);
}
});
$window.on('mouseup touchend', event => {
event.preventDefault();
touchStarted = false;
});
function getCursorPos(e) {
var thisEvent = e || window.event;
let xVal = thisEvent.pageX;
if (isNaN(xVal)) {
xVal = e.originalEvent.touches[0].pageX;
}
// calculate the cursor's x coordinate, relative to the image
return xVal - $container.offset().left;
}
function slide(x) {
// set the width of the overlay
$overlay.width(width - x);
// position the slider
$slider[0].style.left = x + 'px';
}
function resetSlider() {
$overlay.width('50%');
$slider[0].style.left = $overlay.width() + 'px'
width = $container.outerWidth();
}
});
return returnValue;
};
})($);
$('.image-comparison-slider__container').imageComparisonSlider();
.image {
display: block;
width: 100%;
}
.image-comparison-slider__title {
text-align: center;
}
.image-comparison-slider__container,
.image-comparison-slider__image-holder {
position: relative;
}
.image-comparison-slider__bottom-image {
position: absolute;
overflow: hidden;
top: 0;
right: 0;
bottom: 0;
z-index: 1;
width: 50%;
}
.image-comparison-slider__caption {
position: absolute;
padding: 1rem;
color: white;
background: rgba(0, 0, 0, 0.6);
z-index: 2;
white-space: nowrap;
}
.image-comparison-slider__top-image .image-comparison-slider__caption {
top: 0;
left: 0;
}
.image-comparison-slider__bottom-image .image-comparison-slider__caption {
bottom: 0;
right: 0;
}
.image-comparison-slider__image {
display: block;
z-index: 1;
}
.image-comparison-slider__bottom-image .image {
position: absolute;
right: 0;
top: 0;
height: 100%;
width: auto;
}
.image-comparison-slider__slider {
position: absolute;
z-index: 3;
cursor: ew-resize;
width: 50px;
height: 50px;
background-color: rgba(255, 96, 38, 0.8);
border-radius: 50%;
top: 50%;
left: 50%;
display: flex;
justify-content: center;
align-items: center;
margin: -25px 0 0 -25px;
}
.image-comparison-slider__slider:after {
content: "< >";
color: white;
font-weight: bold;
font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-comparison-slider__container">
<div class="image-comparison-slider__image-holder image-comparison-slider__top-image">
<img src="https://www.fillmurray.com/g/400/300" alt="A test image 1" class="image">
<div class="image-comparison-slider__caption">Left Image</div>
</div>
<div class="image-comparison-slider__image-holder image-comparison-slider__bottom-image">
<img src="https://www.fillmurray.com/400/300" alt="A test image 2" class="image">
<div class="image-comparison-slider__caption">Right Image</div>
</div>
</div>

why mouse cursor and red line not same position when add zoom 0.5 in to body tag?

why mouse cursor and red line not same position when add zoom 0.5 in to body tag ?
When use on zoom 1; it's work good,
How can i do work on zoom 0.5 (except zoom 1;) ?
https://jsfiddle.net/ksfqgv0p/6/
var isResizing = false;
$(function () {
var container = $('#container'),
left = $('#left'),
handle = $('#handle');
container.on('mousemove', function (e) {
isResizing = true;
});
container.on('mouseout', function (e) {
isResizing = false;
});
$(document).on('mousemove', function (e) {
if (!isResizing)
return;
left.css('width', e.clientX - container.offset().left);
handle.css('margin-left', e.clientX - container.offset().left);
});
});
The problem is that e.clientX returns mouse position on screen not on your object, so then this value is applied to width attribute it is 2x smaller than it must be, so you need to divide this value by zoom level to get correct mouse position on that zoomed out object.
Like this:
left.css('width', ((e.clientX/$('body').css('zoom')) - container.offset().left));
handle.css('margin-left', ((e.clientX/$('body').css('zoom')) - container.offset().left));
Here's jsFiddle
var isResizing = false;
$(function () {
var container = $('#container'),
left = $('#left'),
handle = $('#handle');
container.on('mousemove', function (e) {
isResizing = true;
});
container.on('mouseout', function (e) {
isResizing = false;
});
$(document).on('mousemove', function (e) {
if (!isResizing)
return;
console.log(container.offset().left);
console.log(e.clientX);
left.css('width', ((e.clientX/$('body').css('zoom')) - container.offset().left));
handle.css('margin-left', ((e.clientX/$('body').css('zoom')) - container.offset().left));
});
});
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#container {
width: 100%;
height: 500px;
/* Disable selection so it doesn't get annoying when dragging. */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
}
#container #left {
position: absolute;
width: 750px;
height: 100%;
background-image: url("http://www.pilsnertop.com/wp-content/uploads/2015/12/Dog-Header3.jpg");
overflow: hidden;
background-repeat: no-repeat;
z-index: 9;
}
#container #right {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 100%;
background-image: url("http://www.twitrcovers.com/wp-content/uploads/2014/06/Dog-Butterfly-l.jpg");
overflow: hidden;
background-repeat: no-repeat;
}
#container #handle {
background: red;
height: 500px;
margin-left: 742px;
top: 0;
bottom: 0;
width: 8px;
cursor: w-resize;
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="
width: 100%;
height: 100%;
margin: 0;
padding: 0;
zoom:0.5;
"
>
<div id="container">
<!-- Left side -->
<div id="left">
<!-- Actual resize handle -->
<div id="handle"></div> This is the right side's content!
This is the left side's content! </div>
<!-- Right side -->
<div id="right">
</div>
</div>
</body>

Categories

Resources