Binding to the scroll wheel when over a div - javascript

I'm creating an image editor in the browser and I've got the code for all of my controls done. Now I'd like to map hot keys and mouse buttons. The keyboard is easy, but the mouse is not.
I need to detect when the mouse is over the canvas div and when the mouse wheel is moved above it. The mouse over part is not hard, its binding to the mouse wheel that I'm having trouble with.
I tried jQuery.scroll but that only seams to work if the div under the wheel is set to scroll itself. My canvas is not. It's offset is controlled via my scripts.
Things to note:
I'm using jQuery as my base.
I'm not acually scrolling anything, I'm trying to bind and event to the scroll wheel without actually scrolling.
Structure
<div id="pageWrap">
[page head stuff...]
<div id="canvas">
[the guts of the canvas go here; lots of various stuff...]
<div>
[page body and footer stuff...]
</div>

A very easy implementation would look like:
$(document).ready(function(){
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta/120 > 0) {
$(this).text('scrolling up !');
}
else{
$(this).text('scrolling down !');
}
});
});​
http://www.jsfiddle.net/5t2MN/5/

Important Update 01/2015 - mousewheel event deprecated:
In the meantime the mousewheel event is deprecated and replaced by wheel.
MDN Docs for mousewheel say:
Do not use this wheel event.
This interface is non-standard and deprecated. It was used in non-Gecko browsers only. Instead use the standard wheel event.
Now you should use something like:
// This function checks if the specified event is supported by the browser.
// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
var el = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
$(document).ready(function() {
// Check which wheel event is supported. Don't use both as it would fire each event
// in browsers where both events are supported.
var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';
// Now bind the event to the desired element
$('#foo').on(wheelEvent, function(e) {
var oEvent = e.originalEvent,
delta = oEvent.deltaY || oEvent.wheelDelta;
// deltaY for wheel event
// wheelData for mousewheel event
if (delta > 0) {
// Scrolled up
} else {
// Scrolled down
}
});
});
P.S.
For the comment from Connell Watkins - "Could you explain the division by 120?",
there are some details on MSDN:
The onmousewheel event is the only event that exposes the wheelDelta property. This property indicates the distance that the wheel button has rotated, expressed in multiples of 120. A positive value indicates that the wheel button has rotated away from the user. A negative value indicates that the wheel button has rotated toward the user.
I left out the delta / 120 part in my method as there's no benefit IMO. Scrolling up is delta > 0 and down delta < 0. Simple.

Have you tried mousewheel plugin?
http://www.ogonek.net/mousewheel/jquery-demo.html

A simple example for bind mouse wheel with jquery....
<!DOCTYPE html>
<html>
<head>
<title>Mouse Wheel</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
<style type='text/css'>
body { text-align: center; }
#res
{
margin-top: 200px;
font-size: 128px;
font-weight: bold;
}
</style>
<script type='text/javascript'>
$(document).ready(function(){
var num = 0;
$(document).bind('mousewheel',function(e){
if (e.wheelDelta == "120")
{
$("#res").text(++num);
}
else
{
$("#res").text(--num);
}
});
});
</script>
</head>
<body>
<div id="res">0</div>
</body>
</html>

The e.wheelDelta didn't work for me.
This worked:
$(document).ready(function(){
$('#foo').bind('mousewheel',function(e){
if (e.originalEvent.wheelDelta == 120){
//mouse up
}
else
{
//mouse down
}
});
});

Related

Detecting hover or mouseover on smartphone browser

I have an alphabetical scrolling bar (ASB) in my app, which most smartphones have in their Contacts app.
Now, I have no problem to scroll to specific item when my finger touchstart touchend click etc.. on the ASB.
But, I have problem on capturing hover or mouseover event on my smartphone.
I have tried touchstart touchswipe touchend mouseenter mousemove or hover with no lucks.
Here's the Fiddle or Codepen to play around on your mobile.
Any suggestion is appreciated.
TL;DR; touchmove, touchstart and touchend are the events that made this possible.
I've found that people keep telling me that it's not possible on non-native app to provide the functionality of hover event on smartphone.
But, the modern smartphone browsers have actually provided the functionalities. I realized that the solution is literally lying in a very simple place. And with few tweaks, I've figured how I can simulate this behavior to cross-platform even though it's a bit cheating.
So, Most oftouchevents are passing the arguments that have the needed information where the user touches on the screen.
E.g
var touch = event.originalEvent.changedTouches[0];
var clientY = touch.clientY;
var screenY = touch.screenY;
And since I know the height of every button on my ASB, I can just calculate where the user hovers the element on.
Here's the CodePen to try it easier on mobile touch devices. (Please note this only works on touch devices, you can still use chrome on toggled device mode)
And this is my final code,
var $startElem, startY;
function updateInfo(char) {
$('#info').html('Hover is now on "' + char + '"');
}
$(function() {
var strArr = "#abcdefghijklmnopqrstuvwxyz".split('');
for (var i = 0; i < strArr.length; i++) {
var $btn = $('<a />').attr({
'href': '#',
'class': 'btn btn-xs'
})
.text(strArr[i].toUpperCase())
.on('touchstart', function(ev) {
$startElem = $(this);
var touch = ev.originalEvent.changedTouches[0];
startY = touch.clientY;
updateInfo($(this).text());
})
.on('touchend', function(ev) {
$startElem = null;
startY = null;
})
.on('touchmove', function(ev) {
var touch = ev.originalEvent.changedTouches[0];
var clientY = touch.clientY;
if ($startElem && startY) {
var totalVerticalOffset = clientY - startY;
var indexOffset = Math.floor(totalVerticalOffset / 22); // '22' is each button's height.
if (indexOffset > 0) {
$currentBtn = $startElem.nextAll().slice(indexOffset - 1, indexOffset);
if ($currentBtn.text()) {
updateInfo($currentBtn.text());
}
} else {
$currentBtn = $startElem.prevAll().slice(indexOffset - 1, indexOffset);
if ($currentBtn.text()) {
updateInfo($currentBtn.text());
}
}
}
});
$('#asb').append($btn);
}
});
#info {
border: 1px solid #adadad;
position: fixed;
padding: 20px;
top: 20px;
right: 20px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info">
No hover detected
</div>
<div id="asb" class="btn-group-vertical">
</div>
The hover event is triggered with click/touch events on mobile phone, because you can not simply hover an element on a touch screen.
You can demonstrate this behaviour by simply using the css hover and/or focus selectors to modify content, you can see, that before clicking elements remain the same, but after clicking they retain modified styles.
bind touchstart on a parent. Something like this will work:
$('body').bind('touchstart', function() {});
You don't need to do anything in the function, leave it empty. This will be enough to get hovers on touch, so a touch behaves more like :hover and less like :active.
Similar question How do I simulate a hover with a touch in touch enabled browsers?
The code you provided in your Fiddle or Codepen is working fine. So what's the fuss?
Well, in mostly air or touch-triggering gadgets like smartphones and tablets, you cannot simply use the hover thing function because you can't hover thing on it to make some events. You can only use the hover function when you are using for example a detachable keyboard for tablet (or something that uses mouse or finger scroller).

iOS: disable bounce scroll but allow normal scrolling

I don't want the content of my site sloshing around when the user hits the edge of a page. I just want it to stop.
The omni-present javascript solution I see everywhere is this:
$(document).bind(
'touchmove',
function(e) {
e.preventDefault();
}
);
But this prevents scrolling entirely. Is there way to just remove the bounce. Preferably with CSS or a meta tag as opposed JS, but anything that works will do.
I have to add another answer.
My first approach should work, but, there is an iOS bug, which still bumbs the whole page, even if e.stopPropagation.
mikeyUX find a workaround for this: https://stackoverflow.com/a/16898264/2978727
I wonder why he just get a few clicks for this great idea...
This is how I used his approach in my case:
var content = document.getElementById('scrollDiv');
content.addEventListener('touchstart', function(event) {
this.allowUp = (this.scrollTop > 0);
this.allowDown = (this.scrollTop < this.scrollHeight - this.clientHeight);
this.slideBeginY = event.pageY;
});
content.addEventListener('touchmove', function(event) {
var up = (event.pageY > this.slideBeginY);
var down = (event.pageY < this.slideBeginY);
this.slideBeginY = event.pageY;
if ((up && this.allowUp) || (down && this.allowDown)) {
event.stopPropagation();
}
else {
event.preventDefault();
}
});
Disable bouncing by prevent the default behaviour of the document:
document.addEventListener("touchmove", function(event){
event.preventDefault();
});
Allow scrolling by prevent that the touch reaches the document level (where you would prevent the scrolling):
var scrollingDiv = document.getElementById('scrollDiv');
scrollingDiv.addEventListener('touchmove', function(event){
event.stopPropagation();
});
Mind the difference between these two:
event.stopPropagation()
event.preventDefault()
StopPropagation should be your choice here !
Here is a very good explanation:
http://davidwalsh.name/javascript-events
Edit:
Same problem, same solution:
document.ontouchmove and scrolling on iOS 5
Edit2:
fixed typo in variable names
added brackets after methods
If apply to Desktop Browser, don't need any JavaScript codes, just few lines of CSS codes:
html {
height : 100%;
overflow: hidden;
}
body {
height : 100%;
overflow: auto;
}
I tried lots of different approaches I found here on stackoverflow, but iNoBounce was the thing that really worked for me:
https://github.com/lazd/iNoBounce
I just included it in my index.html:
<script src="inobounce.js"></script>
This library is solution for my scenarios. Easy way to use just include library and initialize where you want like these;
noBounce.init({
animate: true
});
If you want to prevent bouncing only on one element and not on the whole page you can do it like:
noBounce.init({
animate: true,
element: document.getElementById("content")
});
iOS 16 started support of css overscroll-behavior.
If you are targeting > iOS 16 devices (including its WKWebview), to prevent overscroll bounce, the solution is simple
add following CSS
html {
overscroll-behavior: none;
}
Tested in iOS 16 and above.
Found a code that worked to me, I believe it will work to you.
The solution is written here: http://apdevblog.com/optimizing-webkit-overflow-scrolling/
Basically, you need to have this js code:
document.addEventListener("DOMContentLoaded", ready, false);
document.addEventListener("touchmove", function (evt)
{
evt.preventDefault();
}, false);
function ready()
{
var container = document.getElementsByClassName("scrollable")[0];
var subcontainer = container.children[0];
var subsubcontainer = container.children[0].children[0];
container.addEventListener("touchmove", function (evt)
{
if (subsubcontainer.getBoundingClientRect().height > subcontainer.getBoundingClientRect().height)
{
evt.stopPropagation();
}
}, false);
}
And then, have your scrollable divs with the class="scrollable".
After trying these suggestions and reading several articles, the fix for me was to use the CSS property < overflow-x: hidden; > on the problematic element/container.

without jquery i need to find out if the mouse is over an element, not determine when it becomes over (in case it doesn't move to trigger onmouseover)

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!');
}

HTML5 dragleave fired when hovering a child element

The problem I'm having is that the dragleave event of an element is fired when hovering a child element of that element. Also, dragenter is not fired when hovering back the parent element again.
I made a simplified fiddle: http://jsfiddle.net/pimvdb/HU6Mk/1/.
HTML:
<div id="drag" draggable="true">drag me</div>
<hr>
<div id="drop">
drop here
<p>child</p>
parent
</div>
with the following JavaScript:
$('#drop').bind({
dragenter: function() {
$(this).addClass('red');
},
dragleave: function() {
$(this).removeClass('red');
}
});
$('#drag').bind({
dragstart: function(e) {
e.allowedEffect = "copy";
e.setData("text/plain", "test");
}
});
What it is supposed to do is notifying the user by making the drop div red when dragging something there. This works, but if you drag into the p child, the dragleave is fired and the div isn't red anymore. Moving back to the drop div also doesn't make it red again. It's necessary to move completely out of the drop div and drag back into it again to make it red.
Is it possible to prevent dragleave from firing when dragging into a child element?
2017 Update: TL;DR, Look up CSS pointer-events: none; as described in #H.D.'s answer below that works in modern browsers and IE11.
You just need to keep a reference counter, increment it when you get a dragenter, decrement when you get a dragleave. When the counter is at 0 - remove the class.
var counter = 0;
$('#drop').bind({
dragenter: function(ev) {
ev.preventDefault(); // needed for IE
counter++;
$(this).addClass('red');
},
dragleave: function() {
counter--;
if (counter === 0) {
$(this).removeClass('red');
}
}
});
Note: In the drop event, reset counter to zero, and clear the added class.
You can run it here
Is it possible to prevent dragleave from firing when dragging into a child element?
Yes.
#drop * {pointer-events: none;}
That CSS seem to be enough for Chrome.
While using it with Firefox, the #drop shouldn't have text nodes directly (else there's a strange issue where a element "leave it to itself"), so I suggest to leave it with only one element (e.g., use a div inside #drop to put everything inside)
Here's a jsfiddle solving the original question (broken) example.
I've also made a simplified version forked from the #Theodore Brown example, but based only in this CSS.
Not all browsers have this CSS implemented, though:
http://caniuse.com/pointer-events
Seeing the Facebook source code I could find this pointer-events: none; several times, however it's probably used together with graceful degradation fallbacks. At least it's so simple and solves the problem for a lot of environments.
It has been quite some time after this question is asked and a lot of solutions (including ugly hacks) are provided.
I managed to fix the same problem I had recently thanks to the answer in this answer and thought it may be helpful to someone who comes through to this page.
The whole idea is to store the evenet.target in ondrageenter everytime it is called on any of the parent or child elements. Then in ondragleave check if the current target (event.target) is equal to the object you stored in ondragenter.
The only case these two are matched is when your drag is leaving the browser window.
The reason that this works fine is when the mouse leaves an element (say el1) and enters another element (say el2), first the el2.ondragenter is called and then el1.ondragleave. Only when the drag is leaving/entering the browser window, event.target will be '' in both el2.ondragenter and el1.ondragleave.
Here is my working sample. I have tested it on IE9+, Chrome, Firefox and Safari.
(function() {
var bodyEl = document.body;
var flupDiv = document.getElementById('file-drop-area');
flupDiv.onclick = function(event){
console.log('HEy! some one clicked me!');
};
var enterTarget = null;
document.ondragenter = function(event) {
console.log('on drag enter: ' + event.target.id);
enterTarget = event.target;
event.stopPropagation();
event.preventDefault();
flupDiv.className = 'flup-drag-on-top';
return false;
};
document.ondragleave = function(event) {
console.log('on drag leave: currentTarget: ' + event.target.id + ', old target: ' + enterTarget.id);
//Only if the two target are equal it means the drag has left the window
if (enterTarget == event.target){
event.stopPropagation();
event.preventDefault();
flupDiv.className = 'flup-no-drag';
}
};
document.ondrop = function(event) {
console.log('on drop: ' + event.target.id);
event.stopPropagation();
event.preventDefault();
flupDiv.className = 'flup-no-drag';
return false;
};
})();
And here is a simple html page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Multiple File Uploader</title>
<link rel="stylesheet" href="my.css" />
</head>
<body id="bodyDiv">
<div id="cntnr" class="flup-container">
<div id="file-drop-area" class="flup-no-drag">blah blah</div>
</div>
<script src="my.js"></script>
</body>
</html>
With proper styling what I have done is to make the inner div (#file-drop-area) much bigger whenever a file is dragged into the screen so that the user can easily drop the files into the proper place.
Here, the simplest Cross-Browser solution (seriously):
jsfiddle <-- try dragging some file inside the box
You can do something like that:
var dropZone= document.getElementById('box');
var dropMask = document.getElementById('drop-mask');
dropZone.addEventListener('dragover', drag_over, false);
dropMask.addEventListener('dragleave', drag_leave, false);
dropMask.addEventListener('drop', drag_drop, false);
In a few words, you create a "mask" inside the dropzone, with width & height inherited, position absolute, that will just show when the dragover starts.
So, after showing that mask, you can do the trick by attaching the others dragleave & drop events on it.
After leaving or dropping, you just hide the mask again.
Simple and without complications.
(Obs.: Greg Pettit advice -- You must be sure that the mask hover the entire box, including the border)
This fairly simple solution is working for me so far, assuming your event is attached to each drag element individually.
if (evt.currentTarget.contains(evt.relatedTarget)) {
return;
}
The "right" way to solve this issue is to disable pointer events on child elements of the drop target (as in #H.D.'s answer). Here's a jsFiddle I created which demonstrates this technique. Unfortunately, this doesn't work in versions of Internet Explorer prior to IE11, since they didn't support pointer events.
Luckily, I was able to come up with a workaround which does work in old versions of IE. Basically, it involves identifying and ignoring dragleave events which occur when dragging over child elements. Because the dragenter event is fired on child nodes before the dragleave event on the parent, separate event listeners can be added to each child node which add or remove an "ignore-drag-leave" class from the drop target. Then the drop target's dragleave event listener can simply ignore calls which occur when this class exists. Here's a jsFiddle demonstrating this workaround. It is tested and working in Chrome, Firefox, and IE8+.
Update:
I created a jsFiddle demonstrating a combined solution using feature detection, where pointer events are used if supported (currently Chrome, Firefox, and IE11), and the browser falls back to adding events to child nodes if pointer event support isn't available (IE8-10).
if you are using HTML5, you can get the parent's clientRect:
let rect = document.getElementById("drag").getBoundingClientRect();
Then in the parent.dragleave():
dragleave(e) {
if(e.clientY < rect.top || e.clientY >= rect.bottom || e.clientX < rect.left || e.clientX >= rect.right) {
//real leave
}
}
here is a jsfiddle
A very simple solution is to use the pointer-events CSS property. Just set its value to none upon dragstart on every child element. These elements won't trigger mouse-related events anymore, so they won't catch the mouse over them and thus won't trigger the dragleave on the parent.
Don't forget to set this property back to auto when finishing the drag ;)
A simple solution is to add the css rule pointer-events: none to the child component to prevent the trigger of ondragleave. See example:
function enter(event) {
document.querySelector('div').style.border = '1px dashed blue';
}
function leave(event) {
document.querySelector('div').style.border = '';
}
div {
border: 1px dashed silver;
padding: 16px;
margin: 8px;
}
article {
border: 1px solid silver;
padding: 8px;
margin: 8px;
}
p {
pointer-events: none;
background: whitesmoke;
}
<article draggable="true">drag me</article>
<div ondragenter="enter(event)" ondragleave="leave(event)">
drop here
<p>child not triggering dragleave</p>
</div>
The problem is that the dragleave event is being fired when the mouse goes in front of the child element.
I've tried various methods of checking to see if the e.target element is the same as the this element, but couldn't get any improvement.
The way I fixed this problem was a bit of a hack, but works 100%.
dragleave: function(e) {
// Get the location on screen of the element.
var rect = this.getBoundingClientRect();
// Check the mouseEvent coordinates are outside of the rectangle
if(e.x > rect.left + rect.width || e.x < rect.left
|| e.y > rect.top + rect.height || e.y < rect.top) {
$(this).removeClass('red');
}
}
Very simple solution:
parent.addEventListener('dragleave', function(evt) {
if (!parent.contains(evt.relatedTarget)) {
// Here it is only dragleave on the parent
}
}
I was having the same issue and tried to use pk7s solution. It worked but it could be done a little bit better without any extra dom elements.
Basicly the idea is same - add an extra unvisible overlay over droppable area. Only lets do this without any extra dom elements. Here is the part were CSS pseudo-elements come to play.
Javascript
var dragOver = function (e) {
e.preventDefault();
this.classList.add('overlay');
};
var dragLeave = function (e) {
this.classList.remove('overlay');
};
var dragDrop = function (e) {
this.classList.remove('overlay');
window.alert('Dropped');
};
var dropArea = document.getElementById('box');
dropArea.addEventListener('dragover', dragOver, false);
dropArea.addEventListener('dragleave', dragLeave, false);
dropArea.addEventListener('drop', dragDrop, false);
CSS
This after rule will create a fully covered overlay for droppable area.
#box.overlay:after {
content:'';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 1;
}
Here is the full solution: http://jsfiddle.net/F6GDq/8/
I hope it helps anyone with the same problem.
You can fix it in Firefox with a little inspiration from the jQuery source code:
dragleave: function(e) {
var related = e.relatedTarget,
inside = false;
if (related !== this) {
if (related) {
inside = jQuery.contains(this, related);
}
if (!inside) {
$(this).removeClass('red');
}
}
}
Unfortunately it doesn't work in Chrome because relatedTarget appears not to exist on dragleave events, and I assume you're working in Chrome because your example did't work in Firefox. Here's a version with the above code implemented.
And here it goes, a solution for Chrome:
.bind('dragleave', function(event) {
var rect = this.getBoundingClientRect();
var getXY = function getCursorPosition(event) {
var x, y;
if (typeof event.clientX === 'undefined') {
// try touch screen
x = event.pageX + document.documentElement.scrollLeft;
y = event.pageY + document.documentElement.scrollTop;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return { x: x, y : y };
};
var e = getXY(event.originalEvent);
// Check the mouseEvent coordinates are outside of the rectangle
if (e.x > rect.left + rect.width - 1 || e.x < rect.left || e.y > rect.top + rect.height - 1 || e.y < rect.top) {
console.log('Drag is really out of area!');
}
})
Here's another solution using document.elementFromPoint:
dragleave: function(event) {
var event = event.originalEvent || event;
var newElement = document.elementFromPoint(event.pageX, event.pageY);
if (!this.contains(newElement)) {
$(this).removeClass('red');
}
}
Hope this works, here's a fiddle.
An alternate working solution, a little simpler.
//Note: Due to a bug with Chrome the 'dragleave' event is fired when hovering the dropzone, then
// we must check the mouse coordinates to be sure that the event was fired only when
// leaving the window.
//Facts:
// - [Firefox/IE] e.originalEvent.clientX < 0 when the mouse is outside the window
// - [Firefox/IE] e.originalEvent.clientY < 0 when the mouse is outside the window
// - [Chrome/Opera] e.originalEvent.clientX == 0 when the mouse is outside the window
// - [Chrome/Opera] e.originalEvent.clientY == 0 when the mouse is outside the window
// - [Opera(12.14)] e.originalEvent.clientX and e.originalEvent.clientY never get
// zeroed if the mouse leaves the windows too quickly.
if (e.originalEvent.clientX <= 0 || e.originalEvent.clientY <= 0) {
I know this is a old question but wanted to add my preference. I deal with this by adding class triggered css :after element at a higher z-index then your content. This will filter out all the garbage.
.droppable{
position: relative;
z-index: 500;
}
.droppable.drag-over:after{
content: "";
display:block;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
z-index: 600;
}
Then just add the drag-over class on your first dragenter event and none of the child elements trigger the event any longer.
dragEnter(event){
dropElement.classList.add('drag-over');
}
dragLeave(event){
dropElement.classList.remove('drag-over');
}
Not sure if this cross browser, but I tested in Chrome and it solves my problem:
I want to drag and drop a file over entire page, but my dragleave is fired when i drag over child element. My fix was to look at the x and y of mouse:
i have a div that overlays my entire page, when the page loads i hide it.
when you drag over document i show it, and when you drop on the parent it handles it, and when you leave the parent i check x and y.
$('#draganddrop-wrapper').hide();
$(document).bind('dragenter', function(event) {
$('#draganddrop-wrapper').fadeIn(500);
return false;
});
$("#draganddrop-wrapper").bind('dragover', function(event) {
return false;
}).bind('dragleave', function(event) {
if( window.event.pageX == 0 || window.event.pageY == 0 ) {
$(this).fadeOut(500);
return false;
}
}).bind('drop', function(event) {
handleDrop(event);
$(this).fadeOut(500);
return false;
});
I've stumbled into the same problem and here's my solution - which I think is much easier then above. I'm not sure if it's crossbrowser (might depend on even bubbling order)
I'll use jQuery for simplicity, but solution should be framework independent.
The event bubbles to parent either way so given:
<div class="parent">Parent <span>Child</span></div>
We attach events
el = $('.parent')
setHover = function(){ el.addClass('hovered') }
onEnter = function(){ setTimeout(setHover, 1) }
onLeave = function(){ el.removeClass('hovered') }
$('.parent').bind('dragenter', onEnter).bind('dragleave', onLeave)
And that's about it. :) it works because even though onEnter on child fires before onLeave on parent, we delay it slightly reversing the order, so class is removed first then reaplied after a milisecond.
I've written a little library called Dragster to handle this exact issue, works everywhere except silently doing nothing in IE (which doesn't support DOM Event Constructors, but it'd be pretty easy to write something similar using jQuery's custom events)
Just check if the dragged over element is a child, if it is, then don't remove your 'dragover' style class. Pretty simple and works for me:
$yourElement.on('dragleave dragend drop', function(e) {
if(!$yourElement.has(e.target).length){
$yourElement.removeClass('is-dragover');
}
})
I wrote a drag-and-drop module called drip-drop that fixes this weirdo behavior, among others. If you're looking for a good low-level drag-and-drop module you can use as the basis for anything (file upload, in-app drag-and-drop, dragging from or to external sources), you should check this module out:
https://github.com/fresheneesz/drip-drop
This is how you would do what you're trying to do in drip-drop:
$('#drop').each(function(node) {
dripDrop.drop(node, {
enter: function() {
$(node).addClass('red')
},
leave: function() {
$(node).removeClass('red')
}
})
})
$('#drag').each(function(node) {
dripDrop.drag(node, {
start: function(setData) {
setData("text", "test") // if you're gonna do text, just do 'text' so its compatible with IE's awful and restrictive API
return "copy"
},
leave: function() {
$(node).removeClass('red')
}
})
})
To do this without a library, the counter technique is what I used in drip-drop, tho the highest rated answer misses important steps that will cause things to break for everything except the first drop. Here's how to do it properly:
var counter = 0;
$('#drop').bind({
dragenter: function(ev) {
ev.preventDefault()
counter++
if(counter === 1) {
$(this).addClass('red')
}
},
dragleave: function() {
counter--
if (counter === 0) {
$(this).removeClass('red');
}
},
drop: function() {
counter = 0 // reset because a dragleave won't happen in this case
}
});
I found a simple solution to this problem so sharing it. It works well in my case.
jsfiddle try it.
You can actually achieve this only via the dragenter event and you don't even need to register a dragleave. All you need is to have a no-drop area around your dropzones and that's it.
You can also have nested dropzones and this works perfectly. Check this as well nested dropzones.
$('.dropzone').on("dragenter", function(e) {
e.preventDefault();
e.stopPropagation();
$(this).addClass("over");
$(".over").not(this).removeClass("over"); // in case of multiple dropzones
});
$('.dropzone-leave').on("dragenter", function(e) {
e.preventDefault();
e.stopPropagation();
$(".over").removeClass("over");
});
// UPDATE
// As mar10 pointed out, the "Esc" key needs to be managed,
// the easiest approach is to detect the key and clean things up.
$(document).on('keyup', function(e){
if (e.key === "Escape") {
$(".over").removeClass("over");
}
});
After spending so many hours I got that suggestion working exactly as intended. I wanted to provide a cue only when files were dragged over, and document dragover, dragleave was causing painful flickers on Chrome browser.
This is how I solved it, also throwing in proper cues for user.
$(document).on('dragstart dragenter dragover', function(event) {
// Only file drag-n-drops allowed, http://jsfiddle.net/guYWx/16/
if ($.inArray('Files', event.originalEvent.dataTransfer.types) > -1) {
// Needed to allow effectAllowed, dropEffect to take effect
event.stopPropagation();
// Needed to allow effectAllowed, dropEffect to take effect
event.preventDefault();
$('.dropzone').addClass('dropzone-hilight').show(); // Hilight the drop zone
dropZoneVisible= true;
// http://www.html5rocks.com/en/tutorials/dnd/basics/
// http://api.jquery.com/category/events/event-object/
event.originalEvent.dataTransfer.effectAllowed= 'none';
event.originalEvent.dataTransfer.dropEffect= 'none';
// .dropzone .message
if($(event.target).hasClass('dropzone') || $(event.target).hasClass('message')) {
event.originalEvent.dataTransfer.effectAllowed= 'copyMove';
event.originalEvent.dataTransfer.dropEffect= 'move';
}
}
}).on('drop dragleave dragend', function (event) {
dropZoneVisible= false;
clearTimeout(dropZoneTimer);
dropZoneTimer= setTimeout( function(){
if( !dropZoneVisible ) {
$('.dropzone').hide().removeClass('dropzone-hilight');
}
}, dropZoneHideDelay); // dropZoneHideDelay= 70, but anything above 50 is better
});
"dragleave" event is fired when mouse pointer exits the dragging area of the target container.
Which makes a lot of sense as in many cases only the parent may be droppable and not the descendants.
I think event.stopPropogation() should have handled this case but seems like it doesn't do the trick.
Above mentioned some solutions do seem to work for most of the cases, but fails in case of those children which does not support dragenter / dragleave events, such as iframe.
1 workaround is to check the event.relatedTarget and verify if it resides inside the container then ignore the dragleave event as I have done here:
function isAncestor(node, target) {
if (node === target) return false;
while(node.parentNode) {
if (node.parentNode === target)
return true;
node=node.parentNode;
}
return false;
}
var container = document.getElementById("dropbox");
container.addEventListener("dragenter", function() {
container.classList.add("dragging");
});
container.addEventListener("dragleave", function(e) {
if (!isAncestor(e.relatedTarget, container))
container.classList.remove("dragging");
});
You can find a working fiddle here!
Solved ..!
Declare any array for ex:
targetCollection : any[]
dragenter: function(e) {
this.targetCollection.push(e.target); // For each dragEnter we are adding the target to targetCollection
$(this).addClass('red');
},
dragleave: function() {
this.targetCollection.pop(); // For every dragLeave we will pop the previous target from targetCollection
if(this.targetCollection.length == 0) // When the collection will get empty we will remove class red
$(this).removeClass('red');
}
No need to worry about child elements.
You can use a timeout with a transitioning flag and listen on the top element. dragenter / dragleave from child events will bubble up to the container.
Since dragenter on the child element fires before dragleave of the container, we will set the flag show as transitioning for 1ms... the dragleave listener will check for the flag before the 1ms is up.
The flag will be true only during transitions to child elements, and will not be true when transitioning to a parent element (of the container)
var $el = $('#drop-container'),
transitioning = false;
$el.on('dragenter', function(e) {
// temporarily set the transitioning flag for 1 ms
transitioning = true;
setTimeout(function() {
transitioning = false;
}, 1);
$el.toggleClass('dragging', true);
e.preventDefault();
e.stopPropagation();
});
// dragleave fires immediately after dragenter, before 1ms timeout
$el.on('dragleave', function(e) {
// check for transitioning flag to determine if were transitioning to a child element
// if not transitioning, we are leaving the container element
if (transitioning === false) {
$el.toggleClass('dragging', false);
}
e.preventDefault();
e.stopPropagation();
});
// to allow drop event listener to work
$el.on('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
});
$el.on('drop', function(e) {
alert("drop!");
});
jsfiddle: http://jsfiddle.net/ilovett/U7mJj/
I had a similar problem — my code for hiding the dropzone on dragleave event for body was fired contatantly when hovering child elements making the dropzone flicker in Google Chrome.
I was able to solve this by scheduling the function for hiding dropzone instead of calling it right away. Then, if another dragover or dragleave is fired, the scheduled function call is cancelled.
body.addEventListener('dragover', function() {
clearTimeout(body_dragleave_timeout);
show_dropzone();
}, false);
body.addEventListener('dragleave', function() {
clearTimeout(body_dragleave_timeout);
body_dragleave_timeout = setTimeout(show_upload_form, 100);
}, false);
dropzone.addEventListener('dragover', function(event) {
event.preventDefault();
dropzone.addClass("hover");
}, false);
dropzone.addEventListener('dragleave', function(event) {
dropzone.removeClass("hover");
}, false);
I struggeled a LOT with this, even after reading through all of these answers, and thought I may share my solution with you, because I figured it may be one of the simpler approaches, somewhat different though. My thought was of simply omitting the dragleave event listener completely, and coding the dragleave behaviour with each new dragenter event fired, while making sure that dragenter events won't be fired unnecessarily.
In my example below, I have a table, where I want to be able to exchange table row contents with each other via drag & drop API. On dragenter, a CSS class shall be added to the row element into which you're currently dragging your element, to highlight it, and on dragleave, this class shall be removed.
Example:
Very basic HTML table:
<table>
<tr>
<td draggable="true" class="table-cell">Hello</td>
</tr>
<tr>
<td draggable="true" clas="table-cell">There</td>
</tr>
</table>
And the dragenter event handler function, added onto each table cell (aside dragstart, dragover, drop, and dragend handlers, which are not specific to this question, so not copied here):
/*##############################################################################
## Dragenter Handler ##
##############################################################################*/
// When dragging over the text node of a table cell (the text in a table cell),
// while previously being over the table cell element, the dragleave event gets
// fired, which stops the highlighting of the currently dragged cell. To avoid
// this problem and any coding around to fight it, everything has been
// programmed with the dragenter event handler only; no more dragleave needed
// For the dragenter event, e.target corresponds to the element into which the
// drag enters. This fact has been used to program the code as follows:
var previousRow = null;
function handleDragEnter(e) {
// Assure that dragenter code is only executed when entering an element (and
// for example not when entering a text node)
if (e.target.nodeType === 1) {
// Get the currently entered row
let currentRow = this.closest('tr');
// Check if the currently entered row is different from the row entered via
// the last drag
if (previousRow !== null) {
if (currentRow !== previousRow) {
// If so, remove the class responsible for highlighting it via CSS from
// it
previousRow.className = "";
}
}
// Each time an HTML element is entered, add the class responsible for
// highlighting it via CSS onto its containing row (or onto itself, if row)
currentRow.className = "ready-for-drop";
// To know which row has been the last one entered when this function will
// be called again, assign the previousRow variable of the global scope onto
// the currentRow from this function run
previousRow = currentRow;
}
}
Very basic comments left in code, such that this code suits for beginners too. Hope this will help you out! Note that you will of course need to add all the event listeners I mentioned above onto each table cell for this to work.
Here is another approach based on the timing of events.
The dragenter event dispatched from the child element can be captured by the parent element and it always occurs before the dragleave. The timing between these two events is really short, shorter than any possible human mouse action. So, the idea is to memorize the time when a dragenter happens and filter dragleave events that occurs "not too quickly" after ...
This short example works on Chrome and Firefox:
var node = document.getElementById('someNodeId'),
on = function(elem, evt, fn) { elem.addEventListener(evt, fn, false) },
time = 0;
on(node, 'dragenter', function(e) {
e.preventDefault();
time = (new Date).getTime();
// Drag start
})
on(node, 'dragleave', function(e) {
e.preventDefault();
if ((new Date).getTime() - time > 5) {
// Drag end
}
})

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

I have a little "floating tool box" - a div with position:fixed; overflow:auto.
Works just fine.
But when scrolling inside that box (with the mouse wheel) and reaching the bottom OR top, the parent element "takes over" the "scroll request" : The document behind the tool box scrolls.
- Which is annoying and not what the user "asked for".
I'm using jQuery and thought I could stop this behaviour with event.stoppropagation():
$("#toolBox").scroll( function(event){ event.stoppropagation() });
It does enter the function, but still, propagation happens anyway (the document scrolls)
- It's surprisingly hard to search for this topic on SO (and Google), so I have to ask:
How to prevent propagation / bubbling of the scroll-event ?
Edit:
Working solution thanks to amustill (and Brandon Aaron for the mousewheel-plugin here:
https://github.com/brandonaaron/jquery-mousewheel/raw/master/jquery.mousewheel.js
$(".ToolPage").bind('mousewheel', function(e, d)
var t = $(this);
if (d > 0 && t.scrollTop() === 0) {
e.preventDefault();
}
else {
if (d < 0 && (t.scrollTop() == t.get(0).scrollHeight - t.innerHeight())) {
e.preventDefault();
}
}
});
I am adding this answer for completeness because the accepted answer by #amustill does not correctly solve the problem in Internet Explorer. Please see the comments in my original post for details. In addition, this solution does not require any plugins - only jQuery.
In essence, the code works by handling the mousewheel event. Each such event contains a wheelDelta equal to the number of px which it is going to move the scrollable area to. If this value is >0, then we are scrolling up. If the wheelDelta is <0 then we are scrolling down.
FireFox: FireFox uses DOMMouseScroll as the event, and populates originalEvent.detail, whose +/- is reversed from what is described above. It generally returns intervals of 3, while other browsers return scrolling in intervals of 120 (at least on my machine). To correct, we simply detect it and multiply by -40 to normalize.
#amustill's answer works by canceling the event if the <div>'s scrollable area is already either at the top or the bottom maximum position. However, Internet Explorer disregards the canceled event in situations where the delta is larger than the remaining scrollable space.
In other words, if you have a 200px tall <div> containing 500px of scrollable content, and the current scrollTop is 400, a mousewheel event which tells the browser to scroll 120px further will result in both the <div> and the <body> scrolling, because 400 + 120 > 500.
So - to solve the problem, we have to do something slightly different, as shown below:
The requisite jQuery code is:
$(document).on('DOMMouseScroll mousewheel', '.Scrollable', function(ev) {
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.innerHeight(),
delta = (ev.type == 'DOMMouseScroll' ?
ev.originalEvent.detail * -40 :
ev.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
ev.stopPropagation();
ev.preventDefault();
ev.returnValue = false;
return false;
}
if (!up && -delta > scrollHeight - height - scrollTop) {
// Scrolling down, but this will take us past the bottom.
$this.scrollTop(scrollHeight);
return prevent();
} else if (up && delta > scrollTop) {
// Scrolling up, but this will take us past the top.
$this.scrollTop(0);
return prevent();
}
});
In essence, this code cancels any scrolling event which would create the unwanted edge condition, then uses jQuery to set the scrollTop of the <div> to either the maximum or minimum value, depending on which direction the mousewheel event was requesting.
Because the event is canceled entirely in either case, it never propagates to the body at all, and therefore solves the issue in IE, as well as all of the other browsers.
I have also put up a working example on jsFiddle.
All the solutions given in this thread don't mention an existing - and native - way to solve this problem without reordering DOM and/or using event preventing tricks. But there's a good reason: this way is proprietary - and available on MS web platform only. Quoting MSDN:
-ms-scroll-chaining property - specifies the scrolling behavior that occurs when a user hits the scroll limit during a manipulation. Property values:
chained - Initial value. The nearest scrollable parent element begins scrolling when the user hits a scroll limit during a manipulation. No bounce effect is shown.
none - A bounce effect is shown when the user hits a scroll limit during a manipulation.
Granted, this property is supported on IE10+/Edge only. Still, here's a telling quote:
To give you a sense of how popular preventing scroll chaining may be,
according to my quick http-archive search "-ms-scroll-chaining: none"
is used in 0.4% of top 300K pages despite being limited in
functionality and only supported on IE/Edge.
And now good news, everyone! Starting from Chrome 63, we finally have a native cure for Blink-based platforms too - and that's both Chrome (obviously) and Android WebView (soon).
Quoting the introducing article:
The overscroll-behavior property is a new CSS feature that controls
the behavior of what happens when you over-scroll a container
(including the page itself). You can use it to cancel scroll chaining,
disable/customize the pull-to-refresh action, disable rubberbanding
effects on iOS (when Safari implements overscroll-behavior), and more.[...]
The property takes three possible values:
auto - Default. Scrolls that originate on the element may propagate to
ancestor elements.
contain - prevents scroll chaining. Scrolls do not
propagate to ancestors but local effects within the node are shown.
For example, the overscroll glow effect on Android or the
rubberbanding effect on iOS which notifies the user when they've hit a
scroll boundary. Note: using overscroll-behavior: contain on the html
element prevents overscroll navigation actions.
none - same as contain but it also prevents overscroll effects within the node itself (e.g. Android overscroll glow or iOS rubberbanding).
[...] The best part is that using overscroll-behavior does not adversely
affect page performance like the hacks mentioned in the intro!
Here's this feature in action. And here's corresponding CSS Module document.
UPDATE: Firefox, since version 59, has joined the club, and MS Edge is expected to implement this feature in version 18. Here's the corresponding caniusage.
UPDATE 2: And now (Oct, 2022) Safari officially joined the club: since 16.0 version, overscroll-behavior is no longer behind the feature flag.
It's possible with the use of Brandon Aaron's Mousewheel plugin.
Here's a demo: http://jsbin.com/jivutakama/edit?html,js,output
$(function() {
var toolbox = $('#toolbox'),
height = toolbox.height(),
scrollHeight = toolbox.get(0).scrollHeight;
toolbox.bind('mousewheel', function(e, d) {
if((this.scrollTop === (scrollHeight - height) && d < 0) || (this.scrollTop === 0 && d > 0)) {
e.preventDefault();
}
});
});
I know it's quite an old question, but since this is one of top results in google... I had to somehow cancel scroll bubbling without jQuery and this code works for me:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
document.getElementById('a').onmousewheel = function(e) {
document.getElementById('a').scrollTop -= e. wheelDeltaY;
preventDefault(e);
}
EDIT: CodePen example
For AngularJS, I defined the following directive:
module.directive('isolateScrolling', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind('DOMMouseScroll', function (e) {
if (e.detail > 0 && this.clientHeight + this.scrollTop == this.scrollHeight) {
this.scrollTop = this.scrollHeight - this.clientHeight;
e.stopPropagation();
e.preventDefault();
return false;
}
else if (e.detail < 0 && this.scrollTop <= 0) {
this.scrollTop = 0;
e.stopPropagation();
e.preventDefault();
return false;
}
});
element.bind('mousewheel', function (e) {
if (e.deltaY > 0 && this.clientHeight + this.scrollTop >= this.scrollHeight) {
this.scrollTop = this.scrollHeight - this.clientHeight;
e.stopPropagation();
e.preventDefault();
return false;
}
else if (e.deltaY < 0 && this.scrollTop <= 0) {
this.scrollTop = 0;
e.stopPropagation();
e.preventDefault();
return false;
}
return true;
});
}
};
});
And then added it to the scrollable element (the dropdown-menu ul):
<div class="dropdown">
<button type="button" class="btn dropdown-toggle">Rename <span class="caret"></span></button>
<ul class="dropdown-menu" isolate-scrolling>
<li ng-repeat="s in savedSettings | objectToArray | orderBy:'name' track by s.name">
<a ng-click="renameSettings(s.name)">{{s.name}}</a>
</li>
</ul>
</div>
Tested on Chrome and Firefox. Chrome's smooth scrolling defeats this hack when a large mousewheel movement is made near (but not at) the top or bottom of the scroll region.
There are tons of questions like this out there, with many answers, but I could not find a satisfactory solution that did not involve events, scripts, plugins, etc. I wanted to keep it straight in HTML and CSS. I finally found a solution that worked, although it involved restructuring the markup to break the event chain.
1. Basic problem
Scrolling input (i.e.: mousewheel) applied to the modal element will spill over into an ancestor element and scroll it in the same direction, if some such element is scrollable:
(All examples are meant to be viewed on desktop resolutions)
https://jsfiddle.net/ybkbg26c/5/
HTML:
<div id="parent">
<div id="modal">
This text is pretty long here. Hope fully, we will get some scroll bars.
</div>
</div>
CSS:
#modal {
position: absolute;
height: 100px;
width: 100px;
top: 20%;
left: 20%;
overflow-y: scroll;
}
#parent {
height: 4000px;
}
2. No parent scroll on modal scroll
The reason why the ancestor ends up scrolling is because the scroll event bubbles and some element on the chain is able to handle it. A way to stop that is to make sure none of the elements on the chain know how to handle the scroll. In terms of our example, we can refactor the tree to move the modal out of the parent element. For obscure reasons, it is not enough to keep the parent and the modal DOM siblings; the parent must be wrapped by another element that establishes a new stacking context. An absolutely positioned wrapper around the parent can do the trick.
The result we get is that as long as the modal receives the scroll event, the event will not bubble to the "parent" element.
It should typically be possible to redesign the DOM tree to support this behavior without affecting what the end user sees.
https://jsfiddle.net/0bqq31Lv/3/
HTML:
<div id="context">
<div id="parent">
</div>
</div>
<div id="modal">
This text is pretty long here. Hope fully, we will get some scroll bars.
</div>
CSS (new only):
#context {
position: absolute;
overflow-y: scroll;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
3. No scroll anywhere except in modal while it is up
The solution above still allows the parent to receive scroll events, as long as they are not intercepted by the modal window (i.e. if triggered by mousewheel while the cursor is not over the modal). This is sometimes undesirable and we may want to forbid all background scrolling while the modal is up. To do that, we need to insert an extra stacking context that spans the whole viewport behind the modal. We can do that by displaying an absolutely positioned overlay, which can be fully transparent if necessary (but not visibility:hidden).
https://jsfiddle.net/0bqq31Lv/2/
HTML:
<div id="context">
<div id="parent">
</div>
</div>
<div id="overlay">
</div>
<div id="modal">
This text is pretty long here. Hope fully, we will get some scroll bars.
</div>
CSS (new on top of #2):
#overlay {
background-color: transparent;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Here's a plain JavaScript version:
function scroll(e) {
var delta = (e.type === "mousewheel") ? e.wheelDelta : e.detail * -40;
if (delta < 0 && (this.scrollHeight - this.offsetHeight - this.scrollTop) <= 0) {
this.scrollTop = this.scrollHeight;
e.preventDefault();
} else if (delta > 0 && delta > this.scrollTop) {
this.scrollTop = 0;
e.preventDefault();
}
}
document.querySelectorAll(".scroller").addEventListener("mousewheel", scroll);
document.querySelectorAll(".scroller").addEventListener("DOMMouseScroll", scroll);
As variant, to avoid performance issues with scroll or mousewheel handling, you can use code like below:
css:
body.noscroll {
overflow: hidden;
}
.scrollable {
max-height: 200px;
overflow-y: scroll;
border: 1px solid #ccc;
}
html:
<div class="scrollable">
...A bunch of items to make the div scroll...
</div>
...A bunch of text to make the body scroll...
js:
var $document = $(document),
$body = $('body'),
$scrolable = $('.scrollable');
$scrolable.on({
'mouseenter': function () {
// add hack class to prevent workspace scroll when scroll outside
$body.addClass('noscroll');
},
'mouseleave': function () {
// remove hack class to allow scroll
$body.removeClass('noscroll');
}
});
Example of work: http://jsbin.com/damuwinarata/4
Angular JS Directive
I had to wrap an angular directive. The following is a Mashup of the other answers here. tested on Chrome and Internet Explorer 11.
var app = angular.module('myApp');
app.directive("preventParentScroll", function () {
return {
restrict: "A",
scope: false,
link: function (scope, elm, attr) {
elm.bind('mousewheel', onMouseWheel);
function onMouseWheel(e) {
elm[0].scrollTop -= (e.wheelDeltaY || (e.originalEvent && (e.originalEvent.wheelDeltaY || e.originalEvent.wheelDelta)) || e.wheelDelta || 0);
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
}
}
}
});
Usage
<div prevent-parent-scroll>
...
</div>
Hopes this helps the next person that gets here from a Google search.
Using native element scroll properties with the delta value from the mousewheel plugin:
$elem.on('mousewheel', function (e, delta) {
// Restricts mouse scrolling to the scrolling range of this element.
if (
this.scrollTop < 1 && delta > 0 ||
(this.clientHeight + this.scrollTop) === this.scrollHeight && delta < 0
) {
e.preventDefault();
}
});
In case someone is still looking for a solution for this, the following plugin does the job http://mohammadyounes.github.io/jquery-scrollLock/
It fully addresses the issue of locking mouse wheel scroll inside a given container, preventing it from propagating to parent element.
It does not change wheel scrolling speed, user experience will not be affected. and you get the same behavior regardless of the OS mouse wheel vertical scrolling speed (On Windows it can be set to one screen or one line up to 100 lines per notch).
Demo: http://mohammadyounes.github.io/jquery-scrollLock/example/
Source: https://github.com/MohammadYounes/jquery-scrollLock
You can achieve this outcome with CSS, ie
.isolate-scrolling {
overscroll-behavior: contain;
}
This will only scroll the parent container if your mouse leaves the child element to the parent.
amustill's answer as a knockout handler:
ko.bindingHandlers.preventParentScroll = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
$(element).mousewheel(function (e, d) {
var t = $(this);
if (d > 0 && t.scrollTop() === 0) {
e.preventDefault();
}
else {
if (d < 0 && (t.scrollTop() == t.get(0).scrollHeight - t.innerHeight())) {
e.preventDefault();
}
}
});
}
};
the method above is not that natural, after some googling I find a more nice solution , and no need of jQuery. see [1] and demo [2].
var element = document.getElementById('uf-notice-ul');
var isMacWebkit = (navigator.userAgent.indexOf("Macintosh") !== -1 &&
navigator.userAgent.indexOf("WebKit") !== -1);
var isFirefox = (navigator.userAgent.indexOf("firefox") !== -1);
element.onwheel = wheelHandler; // Future browsers
element.onmousewheel = wheelHandler; // Most current browsers
if (isFirefox) {
element.scrollTop = 0;
element.addEventListener("DOMMouseScroll", wheelHandler, false);
}
// prevent from scrolling parrent elements
function wheelHandler(event) {
var e = event || window.event; // Standard or IE event object
// Extract the amount of rotation from the event object, looking
// for properties of a wheel event object, a mousewheel event object
// (in both its 2D and 1D forms), and the Firefox DOMMouseScroll event.
// Scale the deltas so that one "click" toward the screen is 30 pixels.
// If future browsers fire both "wheel" and "mousewheel" for the same
// event, we'll end up double-counting it here. Hopefully, however,
// cancelling the wheel event will prevent generation of mousewheel.
var deltaX = e.deltaX * -30 || // wheel event
e.wheelDeltaX / 4 || // mousewheel
0; // property not defined
var deltaY = e.deltaY * -30 || // wheel event
e.wheelDeltaY / 4 || // mousewheel event in Webkit
(e.wheelDeltaY === undefined && // if there is no 2D property then
e.wheelDelta / 4) || // use the 1D wheel property
e.detail * -10 || // Firefox DOMMouseScroll event
0; // property not defined
// Most browsers generate one event with delta 120 per mousewheel click.
// On Macs, however, the mousewheels seem to be velocity-sensitive and
// the delta values are often larger multiples of 120, at
// least with the Apple Mouse. Use browser-testing to defeat this.
if (isMacWebkit) {
deltaX /= 30;
deltaY /= 30;
}
e.currentTarget.scrollTop -= deltaY;
// If we ever get a mousewheel or wheel event in (a future version of)
// Firefox, then we don't need DOMMouseScroll anymore.
if (isFirefox && e.type !== "DOMMouseScroll") {
element.removeEventListener("DOMMouseScroll", wheelHandler, false);
}
// Don't let this event bubble. Prevent any default action.
// This stops the browser from using the mousewheel event to scroll
// the document. Hopefully calling preventDefault() on a wheel event
// will also prevent the generation of a mousewheel event for the
// same rotation.
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true; // IE events
e.returnValue = false; // IE events
return false;
}
[1] https://dimakuzmich.wordpress.com/2013/07/16/prevent-scrolling-of-parent-element-with-javascript/
[2] http://jsfiddle.net/dima_k/5mPkB/1/
This actually works in AngularJS.
Tested on Chrome and Firefox.
.directive('stopScroll', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind('mousewheel', function (e) {
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.height(),
delta = (e.type == 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
return false;
};
if (!up && -delta > scrollHeight - height - scrollTop) {
// Scrolling down, but this will take us past the bottom.
$this.scrollTop(scrollHeight);
return prevent();
} else if (up && delta > scrollTop) {
// Scrolling up, but this will take us past the top.
$this.scrollTop(0);
return prevent();
}
});
}
};
})
my jQuery plugin:
$('.child').dontScrollParent();
$.fn.dontScrollParent = function()
{
this.bind('mousewheel DOMMouseScroll',function(e)
{
var delta = e.originalEvent.wheelDelta || -e.originalEvent.detail;
if (delta > 0 && $(this).scrollTop() <= 0)
return false;
if (delta < 0 && $(this).scrollTop() >= this.scrollHeight - $(this).height())
return false;
return true;
});
}
I have a similar situation and here's how i solved it:
All my scrollable elements get the class scrollable.
$(document).on('wheel', '.scrollable', function(evt) {
var offsetTop = this.scrollTop + parseInt(evt.originalEvent.deltaY, 10);
var offsetBottom = this.scrollHeight - this.getBoundingClientRect().height - offsetTop;
if (offsetTop < 0 || offsetBottom < 0) {
evt.preventDefault();
} else {
evt.stopImmediatePropagation();
}
});
stopImmediatePropagation() makes sure not to scroll parent scrollable area from scrollable child area.
Here's a vanilla JS implementation of it:
http://jsbin.com/lugim/2/edit?js,output
New web dev here. This worked like a charm for me on both IE and Chrome.
static preventScrollPropagation(e: HTMLElement) {
e.onmousewheel = (ev) => {
var preventScroll = false;
var isScrollingDown = ev.wheelDelta < 0;
if (isScrollingDown) {
var isAtBottom = e.scrollTop + e.clientHeight == e.scrollHeight;
if (isAtBottom) {
preventScroll = true;
}
} else {
var isAtTop = e.scrollTop == 0;
if (isAtTop) {
preventScroll = true;
}
}
if (preventScroll) {
ev.preventDefault();
}
}
}
Don't let the number of lines fool you, it is quite simple - just a bit verbose for readability (self documenting code ftw right?)
Also I should mention that the language here is TypeScript, but as always, it is straightforward to convert it to JS.
We can simply use CSS.
Give a style to the child scroll container element.
style="overscroll-behavior: contain"
It doesn't trigger the parent's scroll event.
For those using MooTools, here is equivalent code:
'mousewheel': function(event){
var height = this.getSize().y;
height -= 2; // Not sure why I need this bodge
if ((this.scrollTop === (this.scrollHeight - height) && event.wheel < 0) ||
(this.scrollTop === 0 && event.wheel > 0)) {
event.preventDefault();
}
Bear in mind that I, like some others, had to tweak a value by a couple of px, that is what the height -= 2 is for.
Basically the main difference is that in MooTools, the delta info comes from event.wheel instead of an extra parameter passed to the event.
Also, I had problems if I bound this code to anything (event.target.scrollHeight for a bound function does not equal this.scrollHeight for a non-bound one)
Hope this helps someone as much as this post helped me ;)
Check out Leland Kwong's code.
Basic idea is to bind the wheeling event to the child element, and then use the native javascript property scrollHeight and the jquery property outerHeight of the child element to detect the end of the scroll, upon which return false to the wheeling event to prevent any scrolling.
var scrollableDist,curScrollPos,wheelEvent,dY;
$('#child-element').on('wheel', function(e){
scrollableDist = $(this)[0].scrollHeight - $(this).outerHeight();
curScrollPos = $(this).scrollTop();
wheelEvent = e.originalEvent;
dY = wheelEvent.deltaY;
if ((dY>0 && curScrollPos >= scrollableDist) ||
(dY<0 && curScrollPos <= 0)) {
return false;
}
});
I yoinked this from the chosen library: https://github.com/harvesthq/chosen/blob/master/coffee/chosen.jquery.coffee
function preventParentScroll(evt) {
var delta = evt.deltaY || -evt.wheelDelta || (evt && evt.detail)
if (delta) {
evt.preventDefault()
if (evt.type == 'DOMMouseScroll') {
delta = delta * 40
}
fakeTable.scrollTop = delta + fakeTable.scrollTop
}
}
var el = document.getElementById('some-id')
el.addEventListener('mousewheel', preventParentScroll)
el.addEventListener('DOMMouseScroll', preventParentScroll)
This works for me.
jQuery plugin with emulate natural scrolling for Internet Explorer
$.fn.mousewheelStopPropagation = function(options) {
options = $.extend({
// defaults
wheelstop: null // Function
}, options);
// Compatibilities
var isMsIE = ('Microsoft Internet Explorer' === navigator.appName);
var docElt = document.documentElement,
mousewheelEventName = 'mousewheel';
if('onmousewheel' in docElt) {
mousewheelEventName = 'mousewheel';
} else if('onwheel' in docElt) {
mousewheelEventName = 'wheel';
} else if('DOMMouseScroll' in docElt) {
mousewheelEventName = 'DOMMouseScroll';
}
if(!mousewheelEventName) { return this; }
function mousewheelPrevent(event) {
event.preventDefault();
event.stopPropagation();
if('function' === typeof options.wheelstop) {
options.wheelstop(event);
}
}
return this.each(function() {
var _this = this,
$this = $(_this);
$this.on(mousewheelEventName, function(event) {
var origiEvent = event.originalEvent;
var scrollTop = _this.scrollTop,
scrollMax = _this.scrollHeight - $this.outerHeight(),
delta = -origiEvent.wheelDelta;
if(isNaN(delta)) {
delta = origiEvent.deltaY;
}
var scrollUp = delta < 0;
if((scrollUp && scrollTop <= 0) || (!scrollUp && scrollTop >= scrollMax)) {
mousewheelPrevent(event);
} else if(isMsIE) {
// Fix Internet Explorer and emulate natural scrolling
var animOpt = { duration:200, easing:'linear' };
if(scrollUp && -delta > scrollTop) {
$this.stop(true).animate({ scrollTop:0 }, animOpt);
mousewheelPrevent(event);
} else if(!scrollUp && delta > scrollMax - scrollTop) {
$this.stop(true).animate({ scrollTop:scrollMax }, animOpt);
mousewheelPrevent(event);
}
}
});
});
};
https://github.com/basselin/jquery-mousewheel-stop-propagation/blob/master/mousewheelStopPropagation.js
The best solution I could find was listening to the scroll event on the window and set the scrollTop to the previous scrollTop if the child div was visible.
prevScrollPos = 0
$(window).scroll (ev) ->
if $('#mydiv').is(':visible')
document.body.scrollTop = prevScrollPos
else
prevScrollPos = document.body.scrollTop
There is a flicker in the background of the child div if you fire a lot of scroll events, so this could be tweaked, but it is hardly noticed and it was sufficient for my use case.
Don't use overflow: hidden; on body. It automatically scrolls everything to the top. There's no need for JavaScript either. Make use of overflow: auto;:
HTML Structure
<div class="overlay">
<div class="overlay-content"></div>
</div>
<div class="background-content">
lengthy content here
</div>
Styling
.overlay{
position: fixed;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0, 0, 0, 0.8);
.overlay-content {
height: 100%;
overflow: scroll;
}
}
.background-content{
height: 100%;
overflow: auto;
}
Play with the demo here.
There's also a funny trick to lock the parent's scrollTop when mouse hovers over a scrollable element. This way you don't have to implement your own wheel scrolling.
Here's an example for preventing document scroll, but it can be adjusted for any element.
scrollable.mouseenter(function ()
{
var scroll = $(document).scrollTop();
$(document).on('scroll.trap', function ()
{
if ($(document).scrollTop() != scroll) $(document).scrollTop(scroll);
});
});
scrollable.mouseleave(function ()
{
$(document).off('scroll.trap');
});
M.K. offered a great plugin in his answer. Plugin can be found here. However, for the sake of completion, I thought it'd be a good idea to put it together in one answer for AngularJS.
Start by injecting the bower or npm (whichever is preferred)
bower install jquery-scrollLock --save
npm install jquery-scroll-lock --save
Add the following directive. I am choosing to add it as an attribute
(function() {
'use strict';
angular
.module('app')
.directive('isolateScrolling', isolateScrolling);
function isolateScrolling() {
return {
restrict: 'A',
link: function(sc, elem, attrs) {
$('.scroll-container').scrollLock();
}
}
}
})();
And the important piece the plugin fails to document in their website is the HTML structure that it must follow.
<div class="scroll-container locked">
<div class="scrollable" isolate-scrolling>
... whatever ...
</div>
</div>
The attribute isolate-scrolling must contain the scrollable class and it all needs to be inside the scroll-container class or whatever class you choose and the locked class must be cascaded.
It is worth to mention that with modern frameworks like reactJS, AngularJS, VueJS, etc, there are easy solutions for this problem, when dealing with fixed position elements. Examples are side panels or overlaid elements.
The technique is called a "Portal", which means that one of the components used in the app, without the need to actually extract it from where you are using it, will mount its children at the bottom of the body element, outside of the parent you are trying to avoid scrolling.
Note that it will not avoid scrolling the body element itself. You can combine this technique and mounting your app in a scrolling div to achieve the expected result.
Example Portal implementation in React's material-ui: https://material-ui-next.com/api/portal/
There is ES 6 crossbrowser + mobile vanila js decision:
function stopParentScroll(selector) {
let last_touch;
let MouseWheelHandler = (e, selector) => {
let delta;
if(e.deltaY)
delta = e.deltaY;
else if(e.wheelDelta)
delta = e.wheelDelta;
else if(e.changedTouches){
if(!last_touch){
last_touch = e.changedTouches[0].clientY;
}
else{
if(e.changedTouches[0].clientY > last_touch){
delta = -1;
}
else{
delta = 1;
}
}
}
let prevent = function() {
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
return false;
};
if(selector.scrollTop === 0 && delta < 0){
return prevent();
}
else if(selector.scrollTop === (selector.scrollHeight - selector.clientHeight) && delta > 0){
return prevent();
}
};
selector.onwheel = e => {MouseWheelHandler(e, selector)};
selector.onmousewheel = e => {MouseWheelHandler(e, selector)};
selector.ontouchmove = e => {MouseWheelHandler(e, selector)};
}
I was searching for this for MooTools and this was the first that came up.
The original MooTools example would work with scrolling up, but not scrolling down so I decided to write this one.
MooTools 1.4.5: http://jsfiddle.net/3MzFJ/
MooTools 1.3.2: http://jsfiddle.net/VhnD4/
MooTools 1.2.6: http://jsfiddle.net/xWrw4/
var stopScroll = function (e) {
var scrollTo = null;
if (e.event.type === 'mousewheel') {
scrollTo = (e.event.wheelDelta * -1);
} else if (e.event.type === 'DOMMouseScroll') {
scrollTo = 40 * e.event.detail;
}
if (scrollTo) {
e.preventDefault();
this.scrollTo(0, scrollTo + this.scrollTop);
}
return false;
};
Usage:
(function)($){
window.addEvent('domready', function(){
$$('.scrollable').addEvents({
'mousewheel': stopScroll,
'DOMMouseScroll': stopScroll
});
});
})(document.id);

Categories

Resources