im writing a website on which pictures, ordered in a grid, are shown. I want to make it possible to drag them around with the mouse and zoom in and out with the mouse wheel. This already works so far. here is what my code looks like:
var clicked = [0,0];
var pos = [0,0]; // <-- This ist the position of the image(s)
var dragging = false
var zoom = 1;
//this function is for zooming in and out
window.onmousewheel = function(event)
{
if (event.deltaY > 0)
{
zoom *= 0.9;
}
else
{
zoom *= 1.1;
}
update(0, 0);
}
window.onmousedown = function(event)
{
clicked = [event.clientX, event.clientY];
dragging = true;
}
window.onmousemove = function(event)
{
if (dragging == false){return;}
update((event.clientX-clicked[0]),(event.clientY-clicked[1]))
}
window.onmouseup = function(event)
{
pos = [pos[0] + (event.clientX-clicked[0]), pos[1] + (event.clientY-clicked[1])];
dragging = false;
}
function update(addX, addY) //<-- this function just updades the position of the images by using the zoom and pos variable and the addX and addY parameter
All of this works very fine. But it has one Bug: When i'm start draging while the mouse is directly over one of the images, then when i release the mouse the mouseup event is not triggered an so everything is still moving until you click again with your mouse. What i also do not like is that if you are dragging while the mouse is over one of the images, it shows this standard chrome browser image moving thing.
My Idea for solving this problems was, making a div with opacity: 0; in the front over everything, which fits the whole screen. looks like this:
(css)
#controller
{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
height:100%;
width:100%;
z-index: 999;
opacity: 0;
}
(html)
<div id="controller"></div>
And now it works fine. I also can drag when i start with the mouse direct over an image. But then i realized that now i can not make any click event or an simple css :hover over one of the images anymore, obviously because the invisible div is now in the front :(
Has anyone of you an idea how two solve this problem?
Put the onmouseup inside onmousedown:
window.onmousedown = function(event)
{
clicked = [event.clientX, event.clientY];
dragging = true;
window.onmouseup = function(event)
{
pos = [pos[0] + (event.clientX-clicked[0]), pos[1] + (event.clientY-clicked[1])];
dragging = false;
}
}
Related
Whenever the user starts dragging an element with draggable="true", the element has a translucent copy of the element you are dragging. Here is the example from W3Schools:
stop starting animation
Right side of the photo is important. That is the animation you get when you start dragging an element.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_ondrag
I have tried to use event.preventDefault(). However, the problem here is that this prevents onDrag from going at all while the element is moving and I need the data (mouse position and such) from onDrag.
It seems there are posts out there for how to stop the animation when you drop it but not start.
Just going off the example on the W3Schools site, I want the drag information without the ondragstart animation.
So if I modify the code by adding a preventDefault() on the ondragstart function:
function dragStart(event) {
console.log(event);
event.preventDefault(); //stops animation in right side of photo, but then won't let ondrag fire
event.dataTransfer.setData("Text", event.target.id);
}
function dragging(event) {
console.log(event);
document.getElementById("demo").innerHTML = "The p element is being dragged";
}
The animation you get when dragging goes away. However (as shown by my console.log) lines, the ondrag won't fire with this preventDefault on ondragstart. This is the information I need.
preventDefault inside ondrag doesn't stop that animation. Is this even possible?
SOLUTION
If anyone is wondering, I found what I needed to do in this case. You can set the image in javascript to a transparent one:
How to remove drag(Ghost) image?
so drag is still technically running but that ghostly image is gone. Wasn't thinking of right search terms.
In this case i would go for a different approach:
https://codepen.io/deibl31/pen/oNeXmPE?editors=1111
// HTML
<div id="myDiv">
</div>
// CSS
#myDiv {
position: absolute;
height: 100px;
width: 100px;
background: black;
color: white;
}
// JS
let myDiv = document.getElementById('myDiv');
let mouseDown = false;
let divPos = {x: 0, y: 0};
myDiv.addEventListener('mousedown', (event) => {
mouseDown = true;
});
window.addEventListener('mousemove', (event) => {
if (mouseDown) {
divPos.x = event.clientX;
divPos.y = event.clientY;
}
});
window.addEventListener('mouseup', (event) => {
if (mouseDown) {
myDiv.style.top = divPos.y + 'px';
myDiv.style.left = divPos.x + 'px';
}
mouseDown = false;
});
If anyone is wondering, I found what I needed to do in this case. You can set the image in JavaScript to a transparent one:
How to remove drag(Ghost) image?
so drag is still technically running but that ghostly image is gone. Wasn't thinking of right search terms.
I'm stuck at finding a solution to my problem.
Let's assume we have fixed-sized area with scrollbars. We need to place an iframe inside so we can preview it by either using the scrollbars or by dragging it. To prevent iframe capturing mouse events, I've put absolute positioned transparent div above it.
<div style="" id="scrolling_container">
<div id="drag_div"></div>
<div id="frame_div">
<iframe id="page_iframe" src="http://www.bbc.com/" scrolling="auto" frameborder="0"></iframe>
</div>
</div>
Then I used some code that transforms mouse dragging into div scrolling.
var draggableContainer = document.getElementById("drag_div");
var scrollingContainer = document.getElementById("scrolling_container");
draggableContainer.removeEventListener('mousedown', draggableContainer.md, 0);
window.removeEventListener('mouseup', draggableContainer.mu, 0);
window.removeEventListener('mousemove', draggableContainer.mm, 0);
var pushed = 0;
draggableContainer.addEventListener('mousedown',
draggableContainer.md = function(e) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
e.stopPropagation();
draggableContainer.style.cursor = "move";
}, 0
);
window.addEventListener('mouseup',
draggableContainer.mu = function() {
pushed = 0;
draggableContainer.style.cursor = "pointer";
}, 0
);
window.addEventListener('mousemove',
draggableContainer.mm = function(e) {
if (pushed) {
var offsetLeft = - lastClientX + (lastClientX=e.clientX),
offsetTop = - lastClientY + (lastClientY=e.clientY);
scrollingContainer.scrollLeft -= offsetLeft;
scrollingContainer.scrollTop -= offsetTop;
}
}, 0
);
Please take a look at the demo: jsFiddle
The problem is, overlay div is not stretched across the whole iframe, it's only spread to visible div area:
Screenshot
It works fine though if I delete this
#scrolling_container {
position: relative;
}
But I need it to be like that because otherwise overlay div overlaps scrollbars and I can no longer use them.
Is there any cross-browser solution that prevents iframe from capturing mouse events so I could get rid of overlay div?
You can disable any mouse interaction with the iframe if you give it the pointer-events:none; property in CSS.
#drag_div {
background:transparent;
position:relative;
width:100%;
height:480px; /* your iframe height */
top:480px; /* your iframe height */
margin-top:-480px; /* your iframe height */
}
probably check this link
Disable mouse scroll wheel zoom on embedded Google Maps
I'm trying to create a dragbar so users can stretch the height or width of an element on my page (not interested in using HTML resize).
It seems like I'm pretty close, but I can't figure out why
1) the moveable bar is jumping all over the page
2) the adjustable div is flickering as the size changes (or sometimes disappearing completely).
You can see the demo at http://jsfiddle.net/dYUz7/
Here's the source
var elem = $('.layout');
var resizeBar = $('.resize-bar',elem),
adjustableWrapper = $('.layout-container-wrapper',elem),
posDir = 'Left',
pos = 'X';
if($(elem).hasClass('layout-updown')){
posDir = 'Top';
pos = 'Y';
}
var startPos = resizeBar[0]['offset'+posDir], i = resizeBar[0]['offset'+posDir];
resizeBar.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
console.log(event);
$(document).on('mousemove', mousemove);
$(document).on('mouseup', mouseup);
});
function mousemove(event) {
i = event['page'+pos] - startPos;
if(pos==='X') return changeSizeWidth(i,event.offsetX);
return changeSizeHeight(i,event.offsetY);
}
function changeSizeWidth(i,width){
resizeBar.css({left : i +'px'});
adjustableWrapper.css({'width': width +'px'});
console.log(adjustableWrapper.css('width'));
}
function changeSizeHeight(i,height){
resizeBar.css({top : i +'px'});
adjustableWrapper.css({'height': height +'px'});
console.log(adjustableWrapper.css('height'));
}
function mouseup() {
$(document).unbind('mousemove', mousemove);
$(document).unbind('mouseup', mouseup);
}
Please don't respond with suggestions for using libraries, I have jQuery in the sample, but I'm using angular in the project, and am trying to not add a bunch of other libraries at this point.
I ended up getting this working by changing the move from the move-bar element to the element which needs to grow or shrink.
The css is a bit messed up, but here's an updated jsfiddle of the result
http://jsfiddle.net/dYUz7/2/
function changeSizeWidth(left){
adjustableWrapper.css({'width': left +'px'});
}
without jquery
basically what I am looking for is the ability to see if the mouse is over a div when a countdown finishes
if the user is over the div then perform action for that div
onmouseover only triggers when the mouse crosses the threshold of the div, if the mouse hasn't moved it wouldn't trigger, so that wouldn't work
I need to determine if the mouse is currently over a div at a specific point in time, if it has moved or not from the starting point
all of my hunting has only found onmousover, and nothing to see if the mouse just happens to be there to begin with
I don't have the javascript skills to determine overall coords of div, then map mouse coords and see if it fits there... which is what I believe I need to do
After reading the second answer (the one with millions of a elements) on this SO question, I've came up with this method works without moving the mouse on page load, without involving millions of elements.
HTML
<div id=t></div>
CSS
#t {
/* for illustrative purposes */
width: 10em;
height: 5em;
background-color: #0af;
}
#t:hover {
border-top-style: hidden;
}
JavaScript
document.addEventListener('click', function () {
var c = window.getComputedStyle(document.getElementById('t')).getPropertyValue('border-top-style');
if (c === 'hidden') {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
As stated earlier, bind to the finish event of your countdown instead of the click event on the document.
You may also use any CSS style that's changed on :hover, I chose border-top-style as it is conspicuous. If you're using a border, choose something else.
Here's a jsFiddle.
set a flag to true onmouseover and to false onmouseleave. when countdown finishes if flag is true then it is over element.
HTML
<div id="div-name">the section of the code i am working with has a countdown timer, when it reaches 0 i need to know if the mouse is over a specific box</div>
<button id="notification" onclick="javascript: letsCountIt(5);">click to start countdown</button>
JS
window.ev = false;
document.getElementById('div-name').onmouseover = function () {
window.ev = true;
console.log(window.ev);
}
document.getElementById('div-name').onmouseout = function () {
window.ev = false;
console.log(window.ev);
}
window.letsCountIt = function (cdtimer) {
cdtimer--;
document.getElementById('notification').innerHTML = cdtimer;
if (cdtimer == 0) {
if (window.ev === true) {
alert('over');
} else {
alert('not over');
}
} else {
setTimeout(function(){letsCountIt(cdtimer);}, 1000);
}
}
Look into document.elementFromPoint . When you pass an x,y to elementFromPoint, it will return whatever element (or <body>, if no other specific element) is at that point. You can easily check if this element is the element you want.
The problem then is finding out what point your mouse is at. How to get the mouse position without events (without moving the mouse)? seems to say - don't. At least use mouseMove to track the cursor. The linked question gives examples of how to do so. (Look to the lower scoring answers, as the higher ones only got points for being snarky.)
Just want to say that, I think jQuery's mouseenter and mouseleave events would make this a lot easier, but if you can't use them, maybe this will help you.
Depending on how your page is laid out, this may not be too difficult. You can get the position of your element using the following. Quoting from another answer
element.offsetLeft and element.offsetTop are the pure javascript
properties for finding an element's position with respect to its
offsetParent; being the nearest parent element with a position of
relative or absolute
So, if your element is positioned relatively to the body, so far so good (We don't need to adjust anything).
Now, if we attach an event to the document mousemove event, we can get the current coordinates of the mouse:
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
}, false);
Now we just need to determine if the mouse falls within the element. To do that we need the height and width of the element. Quoting from another answer
You should use the .offsetWidth and .offsetHeight properties. Note
they belong to the element, not .style.
For example:
var element = document.getElementById('element');
var height = element.offsetHeight;
var width = element.offsetWidth;
Now we have all the information we need, and just need to determine if the mouse falls within the element. We might use something like this:
var onmove = function(e) {
var minX = element.offsetLeft;
var maxX = minX + element.offsetWidth;
var minY = element.offsetTop;
var maxY = minY + element.offsetHeight;
if(e.clientX >= minX && e.clientX <= maxX)
//good horizontally
if(e.clientY >= minY && e.clientY <= maxY)
//good vertically
}
This code works, but the mouse has to be moved once after page load.
var coords;
var getMouseCoordinates = function (e) {
'use strict';
return {
x: e.clientX,
y: e.clientY
};
};
document.addEventListener('mousemove', function (e) {
coords = getMouseCoordinates(e);
}, false);
document.addEventListener('click', function () {
var divCoords = document.getElementById('t').getBoundingClientRect();
if (coords.x >= divCoords.left && coords.x <= divCoords.right && coords.y >= divCoords.top && coords.y <= divCoords.bottom) {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
You wouldn't bind to the click event of document, but rather the finish event of your countdown.
Here's an example. Try clicking in the output window.
You don't need any coordinates or mouse events, if you know a selector for that element:
if (document.querySelector('#elementSelector:hover')) {
alert('I like it when you touch me!');
}
I have made something like a drag-and-drop element with JS.
function Draggable(elm) {
this.d = elm;
this.style.position = "absolute";
elm.onselectstart = elm.ondragstart = function() { return false; }
elm.addEventListener('mousedown', this._start.bindAsEventListener(this), false);
}
Draggable.prototype._start = function (event) {
this.deltaX = event.clientX;
this.deltaY = event.clientY;
if (!this.dm) {
this.dm = document.createElement("div");
this.dm.setAttribute("class", "dragger");
this.dm.onmousemove = this._move.bindAsEventListener(this);
this.dm.onmouseup = this._stop.bindAsEventListener(this);
this.dm.onselectstart = RetFalse;
this.dm.ondragstart = RetFalse;
}
document.body.appendChild(this.dm);
this.lastX = this.lastY = 0;
this.ondragstart();
return false;
}
Draggable.prototype._move = function (event) {
var newx = (event.clientX - this.deltaX);
var newy = (event.clientY - this.deltaY);
if (newx < this.x0) newx = this.x0;
if (newx > this.x1) newx = this.x1;
if (newy < this.y0) newy = this.y0;
if (newy > this.y1) newy = this.y1;
this.d.style.left = newx + "px";
this.d.style.top = newy + "px";
if (window.getSelection) window.getSelection().removeAllRanges(); else document.selection.empty();
return false;
}
Draggable.prototype._stop = function (event) {
document.body.removeChild(this.dm);
return false;
}
The "dragger" is transparent DIV that fills the whole page, to prevent the dragged target from losing capture when mouse moves too fast. (If I could capture the mouse, I would need it.)
.dragger {
cursor:move;
position:absolute;
width:100%;height:100%;
left:0px;top:0px;
margin:0px;padding:0px;
z-index:32767;
background: transparent;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
}
However, if I:
Press left mouse button on the draggable element
Drag it outside the client area (outside the brower window)
Release mouse button
The element will lose the capture, so that if I move the cursor back,
without having receive a mouse-up event, the element follows the cursor everywhere.
(until you click to make a mouse-up again.)
Just now, I saw it perfectly done on this website: (www.box.net)
Even if you release mouse button outside the browser window, the blue selecting box can still resize when the cursor moves, and disappear when button is released.
But I cannot receive any mousemove or mouseup when cursor is outside.
What API can I use to capture the mouse?
As you can see, I'm using Chrome Browser.
It is said that there's no API like HTMLElement.setCapture in non-IE browser.
This page uses jQuery, but what does jQuery use?
What is the raw javascript Code to do that?
Instead of creating a big, transparent element (dm), bind your mouse events to window.
It gets mouse events everywhere on the page; during dragging you'll keep getting mousemove events even if the cursor goes outside the window, as well as a mouseup if you release the mouse button outside the window.
P.S. If you call .preventDefault() on the mousedown event, the browser won’t select any text and you won’t have to clear the selection on mousemove.
Although it is a little outdated (FF now supports setCapture), I found this article to be extraordinarily helpful. The basis of the fix goes something like this:
var dragTarget = element.setCapture ? element : document; // setCapture fix
I've set up this little example. The javascript is copied straight from a webpage I'm building for a client where it works perfect*. Unfortunately I haven't been able to find a fix for draggable content inside an iframe, so it will still appear broken in Chrome if viewed at jsFiddle, Codepen, etc. You'll have to trust me that it works (or try it out yourself). If anyone knows of a fix for this iframe issue, please share.
*in Chrome, Safari and FF, I haven't tested in Opera or IE yet