I want to implement a draggable map containing certain elements.
--> See JSFiddle: https://jsfiddle.net/7ndx7s25/7/
By use of mousedown, mousemove and mouseup I achieved the dragging.
However I am facing problems:
When pressing the mouse button down and then moving outside the window I do not get a mouseup event. Reentering the window (having released the mouse button long ago) my map still thinks the button is down and misbehaves accordingly.
When there are objects on the map, I do not get mousemove events while moving through these objects. Therefore the map hangs and jumps as I enter and leave such an object.
While over such objects I still want to have a move mouse cursor. I could change the cursor style on each object (in the Fiddle I did this for Object 1 as an example), but this doesn't seem like a good way. Is there a more elegant solution?
You need e.g. mouseout to catch when leaving the canvas, though that event will also fire when the cursor move over the other elements.
One easy fix is to simply add a class to canvas, that set pointer-events: none on those.
With that class you can control the cursor as well, and avoid setting it with the script.
Stack snippet
updateInfo = function() {
document.getElementById('info').innerHTML =
'Position = ' + JSON.stringify(position) +
'<br />dragInfo = ' + JSON.stringify(dragInfo);
};
const canvas = document.getElementsByTagName('canvas')[0];
let position = { x: 0, y : 0 };
let dragInfo = null;
updateInfo();
canvas.addEventListener('mousedown', function(e) {
dragInfo = {
startEvent: {
x: e.clientX,
y: e.clientY,
},
startPosition: position
};
canvas.classList.add('dragging');
updateInfo();
});
canvas.addEventListener('mousemove', function(e) {
if (dragInfo === null) return;
position = {
x: dragInfo.startPosition.x - (e.clientX - dragInfo.startEvent.x),
y: dragInfo.startPosition.y - (e.clientY - dragInfo.startEvent.y)
};
updateInfo();
});
canvas.addEventListener('mouseup', function(e) {
dragInfo = null;
canvas.classList.remove('dragging');
updateInfo();
});
canvas.addEventListener('mouseout', function(e) {
dragInfo = null;
canvas.classList.remove('dragging');
updateInfo();
});
* {
user-select: none;
font-family: monospace;
}
canvas {
background: black;
border: 1px solid red;
}
.dragging {
cursor: move;
}
.obj {
position: absolute;
width: 50px;
height: 50px;
background: green;
color: white;
text-align: center;
line-height: 50px;
font-weight: bold;
}
.dragging ~ .obj {
pointer-events: none;
}
<div id="myMap-ish">
<canvas width="500" height="300"></canvas>
<div class="obj" style="left: 30px; top: 35px">1</div>
<div class="obj" style="left: 175px; top: 79px">2</div>
<div class="obj" style="left: 214px; top: 145px">3</div>
<div class="obj" style="left: 314px; top: 215px">4</div>
</div>
<div id="info"></div>
Another option could be to use mouseleave, on the outer wrapper, the myMap-ish element, which could be combined with the above added class to simply cursor handling.
The main difference between mouseout and mouseleave is that the latter won't fire when hovering children, as shown in below sample, so we don't need to toggle pointer-events as we did in the first sample.
Note, to simply use mouseleave in the first sample, on canvas, will have the same issue mouseout has, since the "other element" aren't children of the canvas.
Stack snippet
updateInfo = function() {
document.getElementById('info').innerHTML =
'Position = ' + JSON.stringify(position) +
'<br />dragInfo = ' + JSON.stringify(dragInfo);
};
const canvas = document.getElementById('myMap-ish');
let position = { x: 0, y : 0 };
let dragInfo = null;
updateInfo();
canvas.addEventListener('mousedown', function(e) {
dragInfo = {
startEvent: {
x: e.clientX,
y: e.clientY,
},
startPosition: position
};
canvas.style.cursor = 'move';
document.querySelectorAll('.obj')[0].style.cursor = 'move'; // TODO for all objects
updateInfo();
});
canvas.addEventListener('mousemove', function(e) {
if (dragInfo === null) return;
position = {
x: dragInfo.startPosition.x - (e.clientX - dragInfo.startEvent.x),
y: dragInfo.startPosition.y - (e.clientY - dragInfo.startEvent.y)
};
updateInfo();
});
canvas.addEventListener('mouseup', function(e) {
dragInfo = null;
canvas.style.cursor = 'default';
document.querySelectorAll('.obj')[0].style.cursor = 'default'; // TODO for all objects
updateInfo();
});
canvas.addEventListener('mouseleave', function(e) {
dragInfo = null;
canvas.style.cursor = 'default';
document.querySelectorAll('.obj')[0].style.cursor = 'default'; // TODO for all objects
updateInfo();
});
* {
user-select: none;
font-family: monospace;
}
canvas {
background: black;
border: 1px solid red;
}
.obj {
position: absolute;
width: 50px;
height: 50px;
background: green;
color: white;
text-align: center;
line-height: 50px;
font-weight: bold;
}
<div id="myMap-ish">
<canvas width="500" height="300"></canvas>
<div class="obj" style="left: 30px; top: 35px">1</div>
<div class="obj" style="left: 175px; top: 79px">2</div>
<div class="obj" style="left: 214px; top: 145px">3</div>
<div class="obj" style="left: 314px; top: 215px">4</div>
</div>
<div id="info"></div>
Related
The following code always shows the coordinates of the cursor below the cursor:
function showCoords(e) {
var x = event.clientX;
var y = event.clientY;
var coor = "(" + x + ", " + y + ")";
document.getElementById("box").innerHTML = coor;
var bx = document.getElementById("box");
bx.style.left = e.pageX - 50;
bx.style.top = e.pageY + 20;
}
function clearCoords() {
document.getElementById("box").innerHTML = "";
}
div.relative {
position: relative;
width: 400px;
height: 300px;
border: 1px solid black;
}
div.abs {
position: absolute;
top: 100px;
right: 50px;
width: 200px;
height: 100px;
background-color: yellow;
}
<body onmousemove="showCoords(event)">
<div class="relative">
<div class="abs" onmousemove="showCoords(event)" onmouseout="clearCoords()"></div>
</div>
<div id="box" style="width:100px; height:30px; position:absolute"></div>
</body>
I only want the coordinates to be visible when the mouse pointer is hovering over the yellow rectangle.
If I change <body onmousemove="showCoords(event)"> to <body>, the coordinates are never visible.
How do I get the coordinates be visible only when hovering over the yellow rectangle?
Move the onmousemove listener from the body to the element you want to listen on - div.abs in this case.
I'd recommend not using the onmousemove attribute, in favour of using an entirely javascript solution - just to keep javascript-y things together. Something like (untested)
var listenOn = document.querySelector(".abs");
listenOn.addEventListener("mousemove", ShowCoords);
I have made a simple image cropper, where you move the green box (the area to crop) over the red box (the original image). Here it is:
var crop = document.querySelector(".image .crop");
crop.addEventListener("drag", function() {
var mouseoffset = [event.clientX, event.clientY];
crop.style.left = mouseoffset[0] + "px";
crop.style.top = mouseoffset[1] + "px";
});
crop.addEventListener("dragend", function() {
var mouseoffset = [event.clientX, event.clientY];
crop.style.left = mouseoffset[0] + "px";
crop.style.top = mouseoffset[1] + "px";
});
.image {
position: relative;
width: 400px;
height: 400px;
overflow: hidden;
background: #C00;
}
.image .crop {
position: absolute;
width: 150px;
height: 150px;
background: rgba(64,168,36,1);
}
<div class="image">
<div class="crop" draggable="true"></div>
</div>
But there is a problem: you can notice a pale green box when dragging. I can hide it with pointer-events: none, but this renders the box undraggable. Is there any way I can hide this pale green box while still being able to drag the crop area?
There might be a way to adapt what you have going on with drag events to achieve that result, but I wasn't able to get it working. Here's something doing about the same thing but with mousedown, mouseup, and mousemove.
var crop = document.querySelector(".image .crop");
crop.addEventListener("mousedown", function(event) {
document.onmousemove = function(event) {
moveBox(event);
};
document.onmouseup = function(event) {
stopMoving(event);
}
});
function moveBox(event) {
event.preventDefault();
var mouseoffset = [event.clientX, event.clientY];
crop.style.left = mouseoffset[0] + "px";
crop.style.top = mouseoffset[1] + "px";
}
function stopMoving(event) {
document.onmousemove = null;
document.onmouseup = null;
}
.image {
position: relative;
width: 400px;
height: 400px;
overflow: hidden;
background: #C00;
}
.image .crop {
position: absolute;
width: 150px;
height: 150px;
background: rgba(64, 168, 36, 1);
}
<div class="image">
<div class="crop" draggable="true"></div>
</div>
Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.
How to fix it? (the white holes)
I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.
Any help appreciated :)
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
tile.hover (
function() { //hover-in
$(this).css("background-color","red");
},
function() { //hover-out
}
);
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
With your design one way would be to iterate over the first to your current hovered element and fill it, which would lead no spaces. That said you may want to consider using the HTML5 Canvas and drawing a rectangle from 0 to your mouse position, which will perform significantly faster.
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
tile.hover (
function() { //hover-in
var self = this;
$("#line").children().each(function(){
$(this).css("background-color","red");
if(this == self) return false;
});
},
function() { //hover-out
}
);
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
Edit
Below is an example doing the same task but using the HTML 5 Canvas:
$("#line").mousemove(function(e){
var canvas = $(this)[0];
var ctx = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect()
var x = e.clientX - rect.left;
ctx.fillStyle="red";
ctx.fillRect(0, 0, x, canvas.height);
});
#line{ background-color: #ddd; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="line" width=500 height=50 ></canvas>
This is another approach with nextUntil to select siblings..
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
line.on( 'mouseover', function(ev){
$('.tile').first().nextUntil( $('.tile').eq(ev.pageX) ).css("background-color","red");
});
line.on( 'mouseleave', function(ev){
$('.tile').css("background-color","#ddd");
});
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
Another solution makes use of jQuery's mousemove method. This allows the bar to go both forward and backwards, simply following the cursors position.
This detects movement inside of the div, then I calculate the position of the cursor within the div as a percentage and apply it as the width of the red bar.
$( ".bar" ).mousemove(function( event ) {
var xCord = event.pageX;
xPercent = (xCord + $('.pct').width()) / $( document ).width() * 100;
$('.pct').width(xPercent+'%');
});
.bar{
background:'#999999';
width:50%;
height:50px;
}
.pct{
height:100%;
background:red;
width:0%;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<div class="bar" style="background:#999999">
<div class="pct"></div>
</div>
I want to create a polymer element for drawing shapes. This element have a canvas and a paper-dropdown-menu in its local dom. The idea is to draw using mouse on the canvas and once the drawing action is done, the dropdown-menu will show up next to the shape so one can select the name. My main problem here is: how to display the paper-dropdown-menu relative to the mouse position ?
As the user moves their mouse around over an element, the mousemove event is fired. You can listen to these events while the user is "drawing" and keep track of the mouse position:
var canvas = document.querySelector('.canvas');
var position = document.querySelector('.position');
canvas.addEventListener('mousemove', function(e) {
position.innerText =
'client x: ' + e.clientX +
' client y: ' + e.clientY;
});
.canvas {
background-color: grey;
width: 100px;
height: 100px;
}
<div class="canvas"></div>
<span class="position"></span>
The user will somehow stop drawing, and you can use the last mousemove event to figure out where to render the dropdown (via inline absolute positioning). In the following demo, the "dropdown" appears whenever a click occurs inside the canvas:
var canvas = document.querySelector('.canvas');
var position = document.querySelector('.position');
var dropdown = document.querySelector('.dropdown');
var lastPosition = {x: -100, y: -100};
canvas.addEventListener('mousemove', function(e) {
position.innerText =
'client x: ' + e.clientX +
' client y: ' + e.clientY;
lastPosition.x = e.clientX;
lastPosition.y = e.clientY;
});
canvas.addEventListener('click', function(e) {
dropdown.style.left = lastPosition.x + 'px';
dropdown.style.top = lastPosition.y + 'px';
});
.canvas {
background-color: grey;
width: 100px;
height: 100px;
}
.dropdown {
background-color: red;
height: 40px;
position: absolute;
top: -100px;
left: -100px;
width: 20px;
}
<div class="canvas"></div>
<span class="position"></span>
<div class="dropdown"></div>
I'm trying to drag elements along a line. They should push each other, not cross over or under.
To avoid having a shady element float around on drag, I drag a sub-div which then affects the position of the outer one. Works fine except when you release the mouse which triggers the last drag-event with clientX equal to 0 (see CodePen)!
var b = document.querySelector('.box');
var bi = document.querySelector('.box-inner');
var b2 = document.querySelector('.box2');
bi.addEventListener('dragstart', function() {
console.log("dragstart")
}, false);
bi.addEventListener('drag', function(event) {
const bLeft = event.clientX;
const b2Left = b2.offsetLeft;
b.style.left = bLeft + "px";
if (b2Left - 50 <= bLeft) {
b2.style.left = (bLeft + 50) + "px";
}
console.log("drag", event.clientX, event.target.offsetParent.offsetLeft, b2.offsetLeft);
}, false);
bi.addEventListener('dragend', function() {
console.log("dragend")
}, false);
.box {
width: 50px;
height: 50px;
background-color: hotpink;
position: absolute;
top: 0;
left: 0;
}
.box-inner {
width: 100%;
height: 100%;
}
.box2 {
width: 50px;
height: 50px;
background-color: rebeccapurple;
position: absolute;
left: 200px;
top: 0;
}
<div class="box">
<div class="box-inner" draggable="true"></div>
</div>
<div class="box2"></div>
Why is this and what can I do to avoid resetting it?
By default, data/elements cannot be dropped in other elements. To allow a drop, you must prevent the default handling of the element when dragover.
document.addEventListener("dragover", function(event) {
// prevent default to allow drop
event.preventDefault();
}, false);
I just ignore the last event. I don't know why it emits.
// in `drag` event handler
if (event.screenX === 0) {
return;
}
Notice you should use screenX here. When the user zoom in the page, clientX would be a positive value but not zero.