Scrolling child div scrolls the window, how do I stop that? - javascript

I have a div, with a scroll bar, When it reaches the end, my page starts scrolling. Is there anyway I can stop this behavior ?

You can inactivate the scrolling of the whole page by doing something like this:
<div onmouseover="document.body.style.overflow='hidden';" onmouseout="document.body.style.overflow='auto';"></div>

Found the solution.
http://jsbin.com/itajok
This is what I needed.
And this is the code.
http://jsbin.com/itajok/edit#javascript,html
Uses a jQuery Plug-in.
Update due to deprecation notice
From jquery-mousewheel:
The old behavior of adding three arguments (delta, deltaX, and deltaY)
to the event handler is now deprecated and will be removed in later
releases.
Then, event.deltaY must now be used:
var toolbox = $('#toolbox'),
height = toolbox.height(),
scrollHeight = toolbox.get(0).scrollHeight;
toolbox.off("mousewheel").on("mousewheel", function (event) {
var blockScrolling = this.scrollTop === scrollHeight - height && event.deltaY < 0 || this.scrollTop === 0 && event.deltaY > 0;
return !blockScrolling;
});
Demo

The selected solution is a work of art. Thought it was worthy of a plugin....
$.fn.scrollGuard = function() {
return this
.on( 'wheel', function ( e ) {
var event = e.originalEvent;
var d = event.wheelDelta || -event.detail;
this.scrollTop += ( d < 0 ? 1 : -1 ) * 30;
e.preventDefault();
});
};
This has been an ongoing inconvenience for me and this solution is so clean compared to other hacks I've seen. Curious to know how more about how it works and how widely supported it would be, but cheers to Jeevan and whoever originally came up with this. BTW - stackoverflow answer editor needs this!
UPDATE
I believe this is better in that it doesn't try to manipulate the DOM at all, only prevents bubbling conditionally...
$.fn.scrollGuard2 = function() {
return this
.on( 'wheel', function ( e ) {
var $this = $(this);
if (e.originalEvent.deltaY < 0) {
/* scrolling up */
return ($this.scrollTop() > 0);
} else {
/* scrolling down */
return ($this.scrollTop() + $this.innerHeight() < $this[0].scrollHeight);
}
})
;
};
Works great in chrome and much simpler than other solutions... let me know how it fares elsewhere...
FIDDLE

You could use a mouseover event on the div to disable the body scrollbar and then a mouseout event to activate it again?
E.g. The HTML
<div onmouseover="disableBodyScroll();" onmouseout="enableBodyScroll();">
content
</div>
And then the javascript like so:
var body = document.getElementsByTagName('body')[0];
function disableBodyScroll() {
body.style.overflowY = 'hidden';
}
function enableBodyScroll() {
body.style.overflowY = 'auto';
}

As answered here, most modern browsers now support the overscroll-behavior: none; CSS property, that prevents scroll chaining. And that's it, just one line!

Here's a cross-browser way to do this on the Y axis, it works on desktop and mobile. Tested on OSX and iOS.
var scrollArea = this.querySelector(".scroll-area");
scrollArea.addEventListener("wheel", function() {
var scrollTop = this.scrollTop;
var maxScroll = this.scrollHeight - this.offsetHeight;
var deltaY = event.deltaY;
if ( (scrollTop >= maxScroll && deltaY > 0) || (scrollTop === 0 && deltaY < 0) ) {
event.preventDefault();
}
}, {passive:false});
scrollArea.addEventListener("touchstart", function(event) {
this.previousClientY = event.touches[0].clientY;
}, {passive:false});
scrollArea.addEventListener("touchmove", function(event) {
var scrollTop = this.scrollTop;
var maxScroll = this.scrollHeight - this.offsetHeight;
var currentClientY = event.touches[0].clientY;
var deltaY = this.previousClientY - currentClientY;
if ( (scrollTop >= maxScroll && deltaY > 0) || (scrollTop === 0 && deltaY < 0) ) {
event.preventDefault();
}
this.previousClientY = currentClientY;
}, {passive:false});

I wrote resolving for this issue
var div;
div = document.getElementsByClassName('selector')[0];
div.addEventListener('mousewheel', function(e) {
if (div.clientHeight + div.scrollTop + e.deltaY >= div.scrollHeight) {
e.preventDefault();
div.scrollTop = div.scrollHeight;
} else if (div.scrollTop + e.deltaY <= 0) {
e.preventDefault();
div.scrollTop = 0;
}
}, false);

If I understand your question correctly, then you want to prevent scrolling of the main content when the mouse is over a div (let's say a sidebar). For that, the sidebar may not be a child of the scrolling container of the main content (which was the browser window), to prevent the scroll event from bubbling up to its parent.
This possibly requires some markup changes in the following manner:
<div id="wrapper">
<div id="content">
</div>
</div>
<div id="sidebar">
</div>
See it's working in this sample fiddle and compare that with this sample fiddle which has a slightly different mouse leave behavior of the sidebar.
See also scroll only one particular div with browser's main scrollbar.

this disables the scrolling on the window if you enter the selector element.
works like charms.
elements = $(".selector");
elements.on('mouseenter', function() {
window.currentScrollTop = $(window).scrollTop();
window.currentScrollLeft = $(window).scrollTop();
$(window).on("scroll.prevent", function() {
$(window).scrollTop(window.currentScrollTop);
$(window).scrollLeft(window.currentScrollLeft);
});
});
elements.on('mouseleave', function() {
$(window).off("scroll.prevent");
});

You can inactivate the scrolling of the whole page by doing something like this but display the scrollbar!
<div onmouseover="document.body.style.overflow='hidden'; document.body.style.position='fixed';" onmouseout="document.body.style.overflow='auto'; document.body.style.position='relative';"></div>

$this.find('.scrollingDiv').on('mousewheel DOMMouseScroll', function (e) {
var delta = -e.originalEvent.wheelDelta || e.originalEvent.detail;
var scrollTop = this.scrollTop;
if((delta < 0 && scrollTop === 0) || (delta > 0 && this.scrollHeight - this.clientHeight - scrollTop === 0)) {
e.preventDefault();
}
});

Based on ceed's answer, here is a version that allows nesting scroll guarded elements. Only the element the mouse is over will scroll, and it scrolls quite smoothly. This version is also re-entrant. It can be used multiple times on the same element and will correctly remove and reinstall the handlers.
jQuery.fn.scrollGuard = function() {
this
.addClass('scroll-guarding')
.off('.scrollGuard').on('mouseenter.scrollGuard', function() {
var $g = $(this).parent().closest('.scroll-guarding');
$g = $g.length ? $g : $(window);
$g[0].myCst = $g.scrollTop();
$g[0].myCsl = $g.scrollLeft();
$g.off("scroll.prevent").on("scroll.prevent", function() {
$g.scrollTop($g[0].myCst);
$g.scrollLeft($g[0].myCsl);
});
})
.on('mouseleave.scrollGuard', function() {
var $g = $(this).parent().closest('.scroll-guarding');
$g = $g.length ? $g : $(window);
$g.off("scroll.prevent");
});
};
One easy way to use is to add a class, such as scroll-guard, to all the elements in the page that you allow scrolling on. Then use $('.scroll-guard').scrollGuard() to guard them.

If you apply an overflow: hidden style it should go away
edit: actually I read your question wrong, that will only hide the scroll bar but I don't think that's what you are looking for.

I couldn't get any of the answers to work in Chrome and Firefox, so I came up with this amalgamation:
$someElement.on('mousewheel DOMMouseScroll', scrollProtection);
function scrollProtection(event) {
var $this = $(this);
event = event.originalEvent;
var direction = (event.wheelDelta * -1) || (event.detail);
if (direction < 0) {
if ($this.scrollTop() <= 0) {
return false;
}
} else {
if ($this.scrollTop() + $this.innerHeight() >= $this[0].scrollHeight) {
return false;
}
}
}

Related

Creating a simple "smooth scroll" (with javascript vanilla)

I have been trying to make a simple "smoothscroll" function using location.href that triggers on the mousewheel. The main problem is that the EventListener(wheel..) gets a bunch of inputs over the span of ca. 0,9 seconds which keeps triggering the function. "I only want the function to run once".
In the code below I have tried to remove the eventlistener as soon as the function runs, which actually kinda work, the problem is that I want it to be added again, hence the timed function at the bottom. This also kinda work but I dont want to wait a full second to be able to scroll and if I set it to anything lover the function will run multiple times.
I've also tried doing it with conditions "the commented out true or false variables" which works perfectly aslong as you are only scrolling up and down but you cant scroll twice or down twice.
window.addEventListener('wheel', scrolltest, true);
function scrolltest(event) {
window.removeEventListener('wheel', scrolltest, true);
i = event.deltaY;
console.log(i);
if (webstate == 0) {
if (i < 0 && !upexecuted) {
// upexecuted = true;
location.href = "#forside";
// downexecuted = false;
} else if (i > 0 && !downexecuted) {
// downexecuted = true;
location.href = "#underside";
// upexecuted = false;
}
}
setTimeout(function(){ window.addEventListener('wheel', scrolltest, true); }, 1000);
}
I had hoped there was a way to stop the wheel from constantly produce inputs over atleast 0.9 seconds.
"note: don't know if it can help in some way but when the browser is not clicked (the active window) the wheel will registre only one value a nice 100 for down and -100 for up"
What you're trying to do is called "debouncing" or "throttling". (Those aren't exactly the same thing, but you can look up the difference in case it's going to matter to you.) Functions for this are built into libraries like lodash, but if using a library like that is too non-vanilla for what you have in mind, you can always define your own debounce function: https://www.geeksforgeeks.org/debouncing-in-javascript/
You might also want to look into requestanimationframe.
a different approach
okey after fiddeling with this for just about 2 days i got fustrated and started over. no matter what i did the browsers integrated "glide-scroll" was messing up the event trigger. anyway i decided to animate the scrolling myself and honestly it works better than i had imagined: here is my code if anyone want to do this:
var body = document.getElementsByTagName("BODY")[0];
var p1 = document.getElementById('page1');
var p2 = document.getElementById('page2');
var p3 = document.getElementById('page3');
var p4 = document.getElementById('page4');
var p5 = document.getElementById('page5');
var whatpage = 1;
var snap = 50;
var i = 0;
// this part is really just to read what "page" you are on if you update the site. if you add more pages you should remember to add it here too.
window.onload = setcurrentpage;
function setcurrentpage() {
if (window.pageYOffset == p1.offsetTop) {
whatpage = 1;
} else if (window.pageYOffset == p2.offsetTop) {
whatpage = 2;
} else if (window.pageYOffset == p3.offsetTop) {
whatpage = 3;
} else if (window.pageYOffset == p4.offsetTop) {
whatpage = 4;
} else if (window.pageYOffset == p5.offsetTop) {
whatpage = 5;
}
}
// this code is designet to automaticly work with any "id" you have aslong as you give it a variable called p"number" fx p10 as seen above.
function smoothscroll() {
var whatpagenext = whatpage+1;
var whatpageprev = whatpage-1;
var currentpage = window['p'+whatpage];
var nextpage = window['p'+whatpagenext];
var prevpage = window['p'+whatpageprev];
console.log(currentpage);
if (window.pageYOffset > currentpage.offsetTop + snap && window.pageYOffset < nextpage.offsetTop - snap){
body.style.overflowY = "hidden";
i++
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset <= nextpage.offsetTop + snap && window.pageYOffset >= nextpage.offsetTop - snap) {
i=0;
window.scrollTo(0, nextpage.offsetTop);
whatpage += 1;
body.style.overflowY = "initial";
}
} else if (window.pageYOffset < currentpage.offsetTop - snap && window.pageYOffset > prevpage.offsetTop + snap){
body.style.overflowY = "hidden";
i--
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset >= prevpage.offsetTop - snap && window.pageYOffset <= prevpage.offsetTop + snap) {
i=0;
window.scrollTo(0, prevpage.offsetTop);
whatpage -= 1;
body.style.overflowY = "initial";
}
}
}
to remove the scrollbar completely just add this to your stylesheet:
::-webkit-scrollbar {
width: 0px;
background: transparent;
}

How to remove jank when setting an element to a fixed position using JavaScript

I have a webpage that when scrolled down, the text freezes when it reaches the last paragraph of text but the images keep on scrolling. I've got the implementation working but there is a lot of jank when scrolling with a mouse wheel, not so much if I click and drag the scroll bar.
Are there any optimizations I can make to this code to make work as intended or is there a different way to accomplish the same task?
window.addEventListener('scroll', function (e) {
window.requestAnimationFrame(keepTextStationary);
//keepTextStationary(); // Less janky, but still horrible
});
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && document.documentElement.scrollTop > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
}
Here is the site so you can see the problem.
https://bowerbankninow.azurewebsites.net/exhibitions/oscar-perry-the-pheasant
You are causing layout trashing every time you call getBoundingClientRect. Try debouncing your scroll events:
var lastScrollY = 0;
var ticking = false;
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && lastScrollY > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
ticking = false;
}
function onScroll() {
lastScrollY = document.documentElement.scrollTop;
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(keepTextStationary);
ticking = true;
}
}
window.addEventListener('scroll', onScroll );
See this article for in-depth explanation: https://www.html5rocks.com/en/tutorials/speed/animations/
You dont.
Relocations / styling in javascript take place after the CSS has been loaded. Bad practise. What you can do, is make it animated to make it look less horrible.
Why is pure CSS not an option ?

Smooth scrolling jquery plugin resets scroll start point on refresh. Is there a way to fix this?

I came across this very easy to use and implement jquery plugin for enabling smooth scrolling on a website to help with the look of parallax effects.
Now to implement it I made a .js script which is just
$(document).ready(function(){
// $fn.scrollSpeed(step, speed, easing);
jQuery.scrollSpeed(100, 800);
});
as per the instructions. The whole plugin obviously has it's own .js file which I guess I'll include the contents of,
// Custom scrolling speed with jQuery
// Source: github.com/ByNathan/jQuery.scrollSpeed
// Version: 1.0.2
(function($) {
jQuery.scrollSpeed = function(step, speed, easing) {
var $document = $(document),
$window = $(window),
$body = $('html, body'),
option = easing || 'default',
root = 0,
scroll = false,
scrollY,
scrollX,
view;
if (window.navigator.msPointerEnabled)
return false;
$window.on('mousewheel DOMMouseScroll', function(e) {
var deltaY = e.originalEvent.wheelDeltaY,
detail = e.originalEvent.detail;
scrollY = $document.height() > $window.height();
scrollX = $document.width() > $window.width();
scroll = true;
if (scrollY) {
view = $window.height();
if (deltaY < 0 || detail > 0)
root = (root + view) >= $document.height() ? root : root += step;
if (deltaY > 0 || detail < 0)
root = root <= 0 ? 0 : root -= step;
$body.stop().animate({
scrollTop: root
}, speed, option, function() {
scroll = false;
});
}
if (scrollX) {
view = $window.width();
if (deltaY < 0 || detail > 0)
root = (root + view) >= $document.width() ? root : root += step;
if (deltaY > 0 || detail < 0)
root = root <= 0 ? 0 : root -= step;
$body.stop().animate({
scrollLeft: root
}, speed, option, function() {
scroll = false;
});
}
return false;
}).on('scroll', function() {
if (scrollY && !scroll) root = $window.scrollTop();
if (scrollX && !scroll) root = $window.scrollLeft();
}).on('resize', function() {
if (scrollY && !scroll) view = $window.height();
if (scrollX && !scroll) view = $window.width();
});
};
jQuery.easing.default = function (x,t,b,c,d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
};
})(jQuery);
Now my issue is that everytime I refresh my page: http://danceforovariancancer.com.au
and either click one of my navbar links or if I've refreshed when I was half way down the page, it resets the scroll start position and rushes the page up to the top before you can scroll anywhere. Can I replace a number in either of these .js files with something like current scrollTop or?
Cheers
The plug-in apparently keeps track of the current scroll top offset in the root variable, which it initialises to 0 when you call jQuery.scrollSpeed on page load.
So I propose to change the following line, near the top of that function:
var ...
root = 0,
by:
var ...
root = $window.scrollTop(),
After further analysis, this plug-in has some other things to improve:
It captures the resize event to set the view variable, but that is useless since the rest of the code also sets that variable before using it.
It defines several variables in the scrollSpeed scope which are better scoped to the mousewheel event handler, as they have no use elsewhere
It keeps track of the scroll offset in the root variable, also in the scroll event handler, but it is better to just request it on the spot whenever it is needed. This makes the scroll event handler unnecessary.
It keeps track of whether a scrolling animation is ongoing in the scroll variable, but it's value is never read, nor exposed. So I suggest to remove it. Animation can be detected by $('html,body').is(':animated');
It has very similar code for horizontal and vertical scrolling, so it is pity this is not done in one code block.
Taking it all together, the improved version of the plug-in becomes much shorter, and looks like this:
(function($) {
jQuery.scrollSpeed = function(step, speed, easing) {
var $d = $(document),
$w = $(window),
$body = $('html, body')
root = 0;
if (window.navigator.msPointerEnabled) { return false }
$w.on('mousewheel DOMMouseScroll', function(e) {
var maxY = $d.height() - $w.height(),
animation = {};
animation[maxY > 0 ? 'scrollTop' : 'scrollLeft'] = root =
Math.min(maxY > 0 ? maxY : Math.max(0, $d.width() - $w.width()),
Math.max(0,
($body.is(':animated') ? root : maxY > 0 ? $d.scrollTop() : $d.scrollLeft())
+ Math.sign(-e.originalEvent.wheelDeltaY || e.originalEvent.detail) * step));
$body.stop().animate(animation, speed, easing || 'default');
return false;
});
};
jQuery.easing.default = function (x,t,b,c,d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
};
})(jQuery);
var $document = $(document),
$window = $(window),
$body = $('html, body'),
option = easing || 'default',
root = 0,
scroll = false,
scrollY = $document.height() > $window.height(),
scrollX = $document.width() > $window.width(),
view;
Take a look at scrollY and scrollX vars. The original jQuery.scrollSpeed plugin does not reset now at the top.

jScrollPane scrolling on element drag

I am trying to scroll by highlighting text and dragging down. Now, as you are probably aware, this is standard, default behavior for a standard overflow: auto element, however I am trying to do it with some fancy scrollbars courtesy of jQuery jScrollPane by Kelvin Luck.
I have created a fiddle here: DEMO
basically as you can see, highlighting and scrolling works in the top box (the default overflow: auto box) but in the second it doesn't and, to compound matters, once you reach the bottom it INVERTS your selection!
So, my question(s) is(are) this(these): is there a way to fix this? If so, how?
UPDATE
I have been working on this quite a bit and have found a slight solution using setTimeout()
however, it doesn't work as intended and if anybody is willing to help I have forked it to a new fiddle here: jsFiddle
the code itself is:
pane = $('#scrolldiv2');
pane.jScrollPane({animateEase: 'linear'});
api = pane.data('jsp');
$('#scrolldiv2').on('mousedown', function() {
$(this).off().on('mousemove', function(e) {
rel = $(this).relativePosition();
py = e.pageY - rel.y;
$t = $(this);
if (py >= $(this).height() - 20) {
scroll = setTimeout(scrollBy, 400, 20);
}
else if (py < 20) {
scroll = setTimeout(scrollBy, 400, -20);
}
else {
clearTimeout(scroll);
}
})
}).on('mouseup', function() {
$(this).off('mousemove');
clearTimeout(scroll);
})
var scrollBy = function(v) {
if (api.getContentPositionY < 20 & v == -20) {
api.scrollByY(v + api.getContentPositionY);
clearTimeout(scroll);
} else if (((api.getContentHeight - $t.height()) - api.getContentPositionY) < 20 & v == 20) {
api.scrollByY((api.getContentHeight - $t.height()) - api.getContentPositionY);
clearTimeout(scroll);
} else {
api.scrollByY(v, true)
scroll = setTimeout(scrollBy, 400, v)
}
}
$.fn.extend({
relativePosition: function() {
var t = this.get(0),
x, y;
if (t.offsetParent) {
x = t.offsetLeft;
y = t.offsetTop;
while ((t = t.offsetParent)) {
x += t.offsetLeft;
y += t.offsetTop;
}
}
return {
x: x,
y: y
}
},
})​
You just have to scroll down/up depending on how close the mouse is to the end of the div; is not as good as the native solution but it gets the job done ( http://jsfiddle.net/PWYpu/25/ )
$('#scrolldiv2').jScrollPane();
var topScroll = $('#scrolldiv2').offset().top,
endScroll = topScroll + $('#scrolldiv2').height(),
f = ($('#scrolldiv2').height() / $('#scrolldiv2 .jspPane').height())*5 ,
selection = false,
_prevY;
$(document).mousemove(function(e){
var mY;
var delta = _prevY - e.pageY;
if((e.pageY < endScroll && (mY = ((e.pageY - endScroll + 80)/f)) > 0) ||
(e.pageY > topScroll && (mY = (e.pageY - (topScroll + 80))/f) < 0)){
if(selection && (delta > 10 || delta < -10) )
$('#scrolldiv2').data('jsp').scrollByY(mY, false) ;
}
})
$('#scrolldiv2').mousedown(function(e){_prevY = e.pageY; selection = true ;})
$(window).mouseup(function(){selection = false ;})​
BTW, the reason it inverts the selection is because it reached the end of the document, just put some white space down there and problem solved.
I really hate to say it, I know it's an issue even I ran into with the update to this plugin, but in the old plugin (seen here) it works just fine with basic call. So I just reverted my copy.

How to determine if hidden/overflow text is at top or bottom of element

I'd like to expand on Shog9's answer in
How to determine from javascript if an html element has overflowing content
And I'd like to know if the text that is hidden is at the top or at the bottom (or both or none) of the containing element.
What's the best way to go about that?
You can combine scrollLeft and scrollTop with Shog's answer.
Specifically:
// Author: Shog9
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
// Modified to check if the user has scrolled right or down.
function checkOverflow(el)
{
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
// check scroll location
var isScrolledRight = el.scrollLeft > 0;
var isScrolledDown = el.scrollTop > 0;
el.style.overflow = curOverflow;
return isOverflowing;
}
I could not see the forest through the trees. Joel's code snippet var isScrolledDown = el.scrollTop > 0; made me realize how to do it. I used two functions:
function HasTopOverflow(el) {
return el.scrollTop;
}
function HasBottomOverflow(el) {
var scrollTop = el.scrollTop,
clientHeight = el.clientHeight,
scrollHeight = Math.max(el.scrollHeight, clientHeight);
return (scrollTop + clientHeight) < scrollHeight;
}
Haven't tested if it'll work on IE6+ yet, but FF works.
If there are any bugs, please let me know.

Categories

Resources