Change scroll direction at Anchor point - javascript

on my site I have 6 divs each div the same height and width of the browser window, so 5 are out of view, 3 left aligned then 3 more on top, as so....
When my visitors scroll, id like to scroll along to the 3rd div, then scroll up to the 4th, then continue scrolling horizontally. Is this possible with jQuery, and if so how can it be done?

Check this out. It allows you to scroll in different directions and set up "slides" like above
http://joelb.me/scrollpath/

Simple (maybe helpful) and not perfect:
var win = $(window),
doc = $(document),
bodyH = doc.height() - win.height(),
page4 = $('#page4');
win.scrollTop(bodyH);
$(document).on('DOMMouseScroll mousewheel', function(e, delta) {
delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120;
if(delta < 0) {
if(win.scrollLeft() > page4.offset().left && win.scrollTop() !== 0) {
win.scrollTop(win.scrollTop() + delta * 30);
} else {
win.scrollLeft(win.scrollLeft() - delta * 30);
}
} else {
if(win.scrollLeft() < page4.offset().left && (win.scrollTop() > 0 || win.scrollTop() === 0) && win.scrollTop() !== bodyH) {
win.scrollTop(win.scrollTop() + delta * 30);
} else {
win.scrollLeft(win.scrollLeft() - delta * 30);
}
}
e.preventDefault();
});
demo

Related

jquery touch screen menu

I'm making a parallax website and I have a menu on the top. The thing is, on touch screen devices when I click on a menu item it scroll to the page but when I scroll with my finger to another page the clicked button stay active!!
function redrawDotNav(){
var section1Top = 0;
// The top of each section is offset by half the distance to the previous section.
var section2Top = $('#Slide2').offset().top - (($('#Slide3').offset().top - $('#Slide2').offset().top) / 4);
var section3Top = $('#Slide3').offset().top - (($('#Slide4').offset().top - $('#Slide3').offset().top) / 2);
var section4Top = $('#Slide4').offset().top - (($('#Slide5').offset().top - $('#Slide4').offset().top) / 2);
var section5Top = $('#Slide5').offset().top - (($(document).height() - $('#Slide5').offset().top) / 2);;
$('.link1').removeClass('active');
$('.link2').removeClass('active');
$('.link3').removeClass('active');
$('.link4').removeClass('active');
$('.link5').removeClass('active');
$('.link1').removeClass('hover');
$('.link2').removeClass('hover');
$('.link3').removeClass('hover');
$('.link4').removeClass('hover');
$('.link5').removeClass('hover');
if($('html').hasClass('no-touch')){
if($(document).scrollTop() >= section1Top && $(document).scrollTop() < section2Top){
$('.link1').addClass('active');
}
else if ($(document).scrollTop() >= section2Top && $(document).scrollTop() < section3Top){
$('.link2').addClass('active');
}
else if ($(document).scrollTop() >= section3Top && $(document).scrollTop() < section4Top){
$('.link3').addClass('active');
}
else if ($(document).scrollTop() >= section4Top && $(document).scrollTop() < section5Top){
$('.link4').addClass('active');
}
else if ($(document).scrollTop() >= section5Top){
$('.link5').addClass('active');
}
}
}

Div scroll with fixed steps like the select element

I'm trying to make a div to mimick the select-element in some ways but that also allow me to style and layout each item/option in any way I like.
One behaviour I'm trying to copy is the scrolling which is in fixed steps with the select-element.
How can I get this behaviour for a div-element (with any number of child-divs)?
(The child-div height is the same for every element)
The scrollbar should never be able to be put in a non multiple position of the child-div height.
UPDATE
This is the solution I came up with:
var scroller;
var itemHeight = 300;
function init(){
scroller = document.getElementById('scrollDiv');
scroller.onscroll = fixedScroll;
scroller.onmousewheel = mousewheel;
scroller.onkeydown = keydown;
}
function fixedScroll(e){
e.target.scrollTop = Math.round(e.target.scrollTop / itemHeight) * itemHeight;
}
function mousewheel(e){
e.preventDefault();
var sign = e.wheelDelta > 0 ? -1 : 1;
e.target.scrollTop += sign * itemHeight;
}
function keydown(e){
var sign = 0;
if (e.keyCode === 40) sign = 1;
else if (e.keyCode === 38) sign = -1;
e.target.scrollTop += sign * itemHeight;
}
init();
Fiddle:
http://jsfiddle.net/4tj6r/61/
Try this:
EDIT Ah, it called upon itself once changing the scroll position so it ended up breaking the whole thing. This should do.
And a DEMO
var delta;
var scroller;
function init(){
scroller = document.getElementById('scrollDiv');
scroller.onscroll = fixedScroll;
delta = scroller.scrollTop;
}
function fixedScroll(e){
if(delta < e.target.scrollTop)
e.target.scrollTop = delta + 100;
if(delta > e.target.scrollTop)
e.target.scrollTop = delta - 100;
delta = e.target.scrollTop;
}
<body onload="init();">
<div id="scrollDiv" style="overflow:auto;height:100px;"></div>

Make HTML5 draggable items scroll the page?

I'm using the HTML5 attribute draggable = "true" on some of my divs on my webpage. I want it so that when you drag one of these items to the bottom of the page, it scrolls the page down and when you drag it to the top, it scrolls the page up.
I will eventually make a playlist on my sidebar, and since it will not always be on view depending on where you're looking on the page, the page needs to scroll when you're dragging.
My page is here and you can try dragging the pictures of the posts around. On Chrome, it automatically lets me scroll down when I drag to the bottom, but not up. On Firefox, it doesn't automatically let me scroll either direction. Any help?
Here's a simple jsfiddle to get you started. On Chrome you should be able to drag the Google icon down and have it scroll the page down, but not going up.
here is a code that will scroll-up or scroll-down your page while you are dragging something. Just placing your dragging object at top or bottom of the page. :)
var stop = true;
$(".draggable").on("drag", function (e) {
stop = true;
if (e.originalEvent.clientY < 150) {
stop = false;
scroll(-1)
}
if (e.originalEvent.clientY > ($(window).height() - 150)) {
stop = false;
scroll(1)
}
});
$(".draggable").on("dragend", function (e) {
stop = true;
});
var scroll = function (step) {
var scrollY = $(window).scrollTop();
$(window).scrollTop(scrollY + step);
if (!stop) {
setTimeout(function () { scroll(step) }, 20);
}
}
I have made a simple JavaScript drag and drop class. It can automatically scroll up or down the page while dragging.
See this jsfiddle. Also avaliable at my github page.
Dragging at a high speed is not recommended now. I need to work out that.
Code below is a part of the library.
var autoscroll = function (offset, poffset, parentNode) {
var xb = 0;
var yb = 0;
if (poffset.isBody == true) {
var scrollLeft = poffset.scrollLeft;
var scrollTop = poffset.scrollTop;
var scrollbarwidth = (document.documentElement.clientWidth - document.body.offsetWidth); //All
var scrollspeed = (offset.right + xb) - (poffset.right + scrollbarwidth);
if (scrollspeed > 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = offset.left - (xb);
if (scrollspeed < 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = (offset.bottom + yb) - (poffset.bottom);
if (scrollspeed > 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
scrollspeed = offset.top - (yb);
if (scrollspeed < 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
} else {
var scrollLeft = offset.scrollLeft;
var scrollTop = offset.scrollTop;
var scrollbarwidth = parentNode.offsetWidth - parentNode.clientWidth; //17
var scrollbarheight = parentNode.offsetHeight - parentNode.clientHeight; //17
var scrollspeed = (offset.right + xb) - (poffset.right - scrollbarwidth);
if (scrollspeed > 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = offset.left - (xb + poffset.left);
if (scrollspeed < 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = (offset.bottom + scrollbarheight + yb) - (poffset.bottom);
if (scrollspeed > 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
scrollspeed = offset.top - (yb + poffset.top);
if (scrollspeed < 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
}
};
Here is the javascript version of AngularPlayers answer, I added horizontal support. I noticed both the JQuery solution and Javascript solution have a bug on mobile safari that allows the page to infinitely grow when the bounce effect from overscrolling happens.
The purpose of VerticalMaxed and HorizontalMaxed is to check that the scroll bars are not maxed before scrolling again. This prevents the page from growing during overscroll bounce.
var stopX = true;
var stopY = true;
document.addEventListener('drag', function(e) {
if (event.target.classList.contains('draggable')) {
stopY = true;
// Handle Y
if (e.clientY < 150) {
stopY = false;
scroll(0,-1)
}
if ((e.clientY > ( document.documentElement.clientHeight - 150)) && !VerticalMaxed()) {
stopY = false;
scroll(0,1)
}
// Handle X
stopX = true;
if (e.clientX < 150) {
stopX = false;
scroll(-1,0)
}
if ((e.clientX > ( document.documentElement.clientWidth - 150)) && !HorizontalMaxed()) {
stopX = false;
scroll(1,0)
}
}
});
document.addEventListener('dragend', function(e) {
if (event.target.classList.contains('draggable')) {
stopY = true;
//stopY = true;
stopX = true;
}
});
// On drag scroll, prevents page from growing with mobile safari rubber-band effect
var VerticalMaxed = function(){ return (window.innerHeight + window.scrollY) >= document.body.offsetHeight}
var HorizontalMaxed = function(){ return (window.pageXOffset) > (document.body.scrollWidth - document.body.clientWidth);}
var scroll = function (stepX, stepY) {
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
window.scrollTo((scrollX + stepX), (scrollY + stepY));
if (!stopY || !stopX) {
setTimeout(function () { scroll(stepX, stepY) }, 20);
}
}

Smooth scroll without the use of jQuery

I'm coding up a page where I only want to use raw JavaScript code for UI without any interference of plugins or frameworks.
And now I'm struggling with finding a way to scroll over the page smoothly without jQuery.
Native browser smooth scrolling in JavaScript is like this:
// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// scroll certain amounts from current position
window.scrollBy({
top: 100, // negative value acceptable
left: 0,
behavior: 'smooth'
});
// scroll to a certain element
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
Try this smooth scrolling demo, or an algorithm like:
Get the current top location using self.pageYOffset
Get the position of element till where you want to scroll to: element.offsetTop
Do a for loop to reach there, which will be quite fast or use a timer to do smooth scroll till that position using window.scrollTo
See also the other popular answer to this question.
Andrew Johnson's original code:
function currentYPosition() {
// Firefox, Chrome, Opera, Safari
if (self.pageYOffset) return self.pageYOffset;
// Internet Explorer 6 - standards mode
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
// Internet Explorer 6, 7 and 8
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elmYPosition(eID) {
var elm = document.getElementById(eID);
var y = elm.offsetTop;
var node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
function smoothScroll(eID) {
var startY = currentYPosition();
var stopY = elmYPosition(eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY); return;
}
var speed = Math.round(distance / 100);
if (speed >= 20) speed = 20;
var step = Math.round(distance / 25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for ( var i=startY; i<stopY; i+=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY += step; if (leapY > stopY) leapY = stopY; timer++;
} return;
}
for ( var i=startY; i>stopY; i-=step ) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
}
}
Related links:
https://www.sitepoint.com/smooth-scrolling-vanilla-javascript/
https://github.com/zengabor/zenscroll/blob/dist/zenscroll.js
https://github.com/cferdinandi/smooth-scroll/blob/master/src/js/smooth-scroll.js
https://github.com/alicelieutier/smoothScroll/blob/master/smoothscroll.js
Algorithm
Scrolling an element requires changing its scrollTop value over time. For a given point in time, calculate a new scrollTop value. To animate smoothly, interpolate using a smooth-step algorithm.
Calculate scrollTop as follows:
var point = smooth_step(start_time, end_time, now);
var scrollTop = Math.round(start_top + (distance * point));
Where:
start_time is the time the animation started;
end_time is when the animation will end (start_time + duration);
start_top is the scrollTop value at the beginning; and
distance is the difference between the desired end value and the start value (target - start_top).
A robust solution should detect when animating is interrupted, and more. Read my post about Smooth Scrolling without jQuery for details.
Demo
See the JSFiddle.
Implementation
The code:
/**
Smoothly scroll element to the given target (element.scrollTop)
for the given duration
Returns a promise that's fulfilled when done, or rejected if
interrupted
*/
var smooth_scroll_to = function(element, target, duration) {
target = Math.round(target);
duration = Math.round(duration);
if (duration < 0) {
return Promise.reject("bad duration");
}
if (duration === 0) {
element.scrollTop = target;
return Promise.resolve();
}
var start_time = Date.now();
var end_time = start_time + duration;
var start_top = element.scrollTop;
var distance = target - start_top;
// based on http://en.wikipedia.org/wiki/Smoothstep
var smooth_step = function(start, end, point) {
if(point <= start) { return 0; }
if(point >= end) { return 1; }
var x = (point - start) / (end - start); // interpolation
return x*x*(3 - 2*x);
}
return new Promise(function(resolve, reject) {
// This is to keep track of where the element's scrollTop is
// supposed to be, based on what we're doing
var previous_top = element.scrollTop;
// This is like a think function from a game loop
var scroll_frame = function() {
if(element.scrollTop != previous_top) {
reject("interrupted");
return;
}
// set the scrollTop for this frame
var now = Date.now();
var point = smooth_step(start_time, end_time, now);
var frameTop = Math.round(start_top + (distance * point));
element.scrollTop = frameTop;
// check if we're done!
if(now >= end_time) {
resolve();
return;
}
// If we were supposed to scroll but didn't, then we
// probably hit the limit, so consider it done; not
// interrupted.
if(element.scrollTop === previous_top
&& element.scrollTop !== frameTop) {
resolve();
return;
}
previous_top = element.scrollTop;
// schedule next frame for execution
setTimeout(scroll_frame, 0);
}
// boostrap the animation process
setTimeout(scroll_frame, 0);
});
}
You can use the new Scroll Behaviour CSS Property.
for example, add the below line to your CSS.
html{
scroll-behavior:smooth;
}
and this will result in a native smooth scrolling feature.
see demo here
All modern browsers support the scroll-behavior property.
Read More about Scroll behavior
I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq
/**
by Nemes Ioan Sorin - not an jQuery big fan
therefore this script is for those who love the old clean coding style
#id = the id of the element who need to bring into view
Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
window.setTimeout = window.setTimeout; //
})();
var smoothScr = {
iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
tm : null, //timeout local variable
stopShow: function()
{
clearTimeout(this.tm); // stopp the timeout
this.iterr = 30; // reset milisec iterator to original value
},
getRealTop : function (el) // helper function instead of jQuery
{
var elm = el;
var realTop = 0;
do
{
realTop += elm.offsetTop;
elm = elm.offsetParent;
}
while(elm);
return realTop;
},
getPageScroll : function() // helper function instead of jQuery
{
var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
return pgYoff;
},
anim : function (id) // the main func
{
this.stopShow(); // for click on another button or link
var eOff, pOff, tOff, scrVal, pos, dir, step;
eOff = document.getElementById(id).offsetTop; // element offsetTop
tOff = this.getRealTop(document.getElementById(id).parentNode); // terminus point
pOff = this.getPageScroll(); // page offsetTop
if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;
scrVal = eOff - pOff; // actual scroll value;
if (scrVal > tOff)
{
pos = (eOff - tOff - pOff);
dir = 1;
}
if (scrVal < tOff)
{
pos = (pOff + tOff) - eOff;
dir = -1;
}
if(scrVal !== tOff)
{
step = ~~((pos / 4) +1) * dir;
if(this.iterr > 1) this.iterr -= 1;
else this.itter = 0; // decrease the timeout timer value but not below 0
window.scrollBy(0, step);
this.tm = window.setTimeout(function()
{
smoothScr.anim(id);
}, this.iterr);
}
if(scrVal === tOff)
{
this.stopShow(); // reset function values
return;
}
}
}
Modern browsers has support for CSS "scroll-behavior: smooth" property. So, we even don't need any Javascript at all for this. Just add this for the "html" element, and use usual anchors and links.
scroll-behavior MDN docs
I recently set out to solve this problem in a situation where jQuery wasn't an option, so I'm logging my solution here just for posterity.
var scroll = (function() {
var elementPosition = function(a) {
return function() {
return a.getBoundingClientRect().top;
};
};
var scrolling = function( elementID ) {
var el = document.getElementById( elementID ),
elPos = elementPosition( el ),
duration = 400,
increment = Math.round( Math.abs( elPos() )/40 ),
time = Math.round( duration/increment ),
prev = 0,
E;
function scroller() {
E = elPos();
if (E === prev) {
return;
} else {
prev = E;
}
increment = (E > -20 && E < 20) ? ((E > - 5 && E < 5) ? 1 : 5) : increment;
if (E > 1 || E < -1) {
if (E < 0) {
window.scrollBy( 0,-increment );
} else {
window.scrollBy( 0,increment );
}
setTimeout(scroller, time);
} else {
el.scrollTo( 0,0 );
}
}
scroller();
};
return {
To: scrolling
}
})();
/* usage */
scroll.To('elementID');
The scroll() function uses the Revealing Module Pattern to pass the target element's id to its scrolling() function, via scroll.To('id'), which sets the values used by the scroller() function.
Breakdown
In scrolling():
el : the target DOM object
elPos : returns a function via elememtPosition() which gives the position of the target element relative to the top of the page each time it's called.
duration : transition time in milliseconds.
increment : divides the starting position of the target element into 40 steps.
time : sets the timing of each step.
prev : the target element's previous position in scroller().
E : holds the target element's position in scroller().
The actual work is done by the scroller() function which continues to call itself (via setTimeout()) until the target element is at the top of the page or the page can scroll no more.
Each time scroller() is called it checks the current position of the target element (held in variable E) and if that is > 1 OR < -1 and if the page is still scrollable shifts the window by increment pixels - up or down depending if E is a positive or negative value. When E is neither > 1 OR < -1, or E === prev the function stops. I added the DOMElement.scrollTo() method on completion just to make sure the target element was bang on the top of the window (not that you'd notice it being out by a fraction of a pixel!).
The if statement on line 2 of scroller() checks to see if the page is scrolling (in cases where the target might be towards the bottom of the page and the page can scroll no further) by checking E against its previous position (prev).
The ternary condition below it reduce the increment value as E approaches zero. This stops the page overshooting one way and then bouncing back to overshoot the other, and then bouncing back to overshoot the other again, ping-pong style, to infinity and beyond.
If your page is more that c.4000px high you might want to increase the values in the ternary expression's first condition (here at +/-20) and/or the divisor which sets the increment value (here at 40).
Playing about with duration, the divisor which sets increment, and the values in the ternary condition of scroller() should allow you to tailor the function to suit your page.
JSFiddle
N.B.Tested in up-to-date versions of Firefox and Chrome on Lubuntu, and Firefox, Chrome and IE on Windows8.
I've made something like this.
I have no idea if its working in IE8.
Tested in IE9, Mozilla, Chrome, Edge.
function scroll(toElement, speed) {
var windowObject = window;
var windowPos = windowObject.pageYOffset;
var pointer = toElement.getAttribute('href').slice(1);
var elem = document.getElementById(pointer);
var elemOffset = elem.offsetTop;
var counter = setInterval(function() {
windowPos;
if (windowPos > elemOffset) { // from bottom to top
windowObject.scrollTo(0, windowPos);
windowPos -= speed;
if (windowPos <= elemOffset) { // scrolling until elemOffset is higher than scrollbar position, cancel interval and set scrollbar to element position
clearInterval(counter);
windowObject.scrollTo(0, elemOffset);
}
} else { // from top to bottom
windowObject.scrollTo(0, windowPos);
windowPos += speed;
if (windowPos >= elemOffset) { // scroll until scrollbar is lower than element, cancel interval and set scrollbar to element position
clearInterval(counter);
windowObject.scrollTo(0, elemOffset);
}
}
}, 1);
}
//call example
var navPointer = document.getElementsByClassName('nav__anchor');
for (i = 0; i < navPointer.length; i++) {
navPointer[i].addEventListener('click', function(e) {
scroll(this, 18);
e.preventDefault();
});
}
Description
pointer—get element and chceck if it has attribute "href" if yes,
get rid of "#"
elem—pointer variable without "#"
elemOffset—offset of "scroll to" element from the top of the page
You can use
document.querySelector('your-element').scrollIntoView({behavior: 'smooth'});
If you want to scroll top the top of the page, you can just place an empty element in the top, and smooth scroll to that one.
With using the following smooth scrolling is working fine:
html {
scroll-behavior: smooth;
}
<script>
var set = 0;
function animatescroll(x, y) {
if (set == 0) {
var val72 = 0;
var val73 = 0;
var setin = 0;
set = 1;
var interval = setInterval(function() {
if (setin == 0) {
val72++;
val73 += x / 1000;
if (val72 == 1000) {
val73 = 0;
interval = clearInterval(interval);
}
document.getElementById(y).scrollTop = val73;
}
}, 1);
}
}
</script>
x = scrollTop
y = id of the div that is used to scroll
Note:
For making the body to scroll give the body an ID.
Here is my solution. Works in most browsers
document.getElementById("scrollHere").scrollIntoView({behavior: "smooth"});
Docs
document.getElementById("end").scrollIntoView({behavior: "smooth"});
body {margin: 0px; display: block; height: 100%; background-image: linear-gradient(red, yellow);}
.start {display: block; margin: 100px 10px 1000px 0px;}
.end {display: block; margin: 0px 0px 100px 0px;}
<div class="start">Start</div>
<div class="end" id="end">End</div>
There are many different methods for smooth scrolling in JavaScript. The most common ones are listed below.
To scroll to a certain position in an exact amount of time, window.requestAnimationFrame can be put to use, calculating the appropriate current position each time. setTimeout can be used to a similar effect when requestAnimationFrame is not supported. (To scroll to a specific element with the function below, just set the position to element.offsetTop.)
/*
#param pos: the y-position to scroll to (in pixels)
#param time: the exact amount of time the scrolling will take (in milliseconds)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
Demo:
/*
#param time: the exact amount of time the scrolling will take (in milliseconds)
#param pos: the y-position to scroll to (in pixels)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 300)">
Scroll To Div (300ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 200)">
Scroll To Div (200ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 100)">
Scroll To Div (100ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 50)">
Scroll To Div (50ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 1000)">
Scroll To Div (1000ms)
</button>
<div style="margin: 500px 0px;">
DIV<p/>
<button onClick="scrollToSmoothly(0, 500)">
Back To Top
</button>
<button onClick="scrollToSmoothly(document.body.scrollHeight)">
Scroll To Bottom
</button>
</div>
<div style="margin: 500px 0px;">
</div>
<button style="margin-top: 100px;" onClick="scrollToSmoothly(500, 3000)">
Scroll To y-position 500px (3000ms)
</button>
For more complex cases, the SmoothScroll.js library can be used, which handles smooth scrolling both vertically and horizontally, scrolling inside other container elements, different easing behaviors, scrolling relatively from the current position, and more.
var easings = document.getElementById("easings");
for(var key in smoothScroll.easing){
if(smoothScroll.easing.hasOwnProperty(key)){
var option = document.createElement('option');
option.text = option.value = key;
easings.add(option);
}
}
document.getElementById('to-bottom').addEventListener('click', function(e){
smoothScroll({yPos: 'end', easing: easings.value, duration: 2000});
});
document.getElementById('to-top').addEventListener('click', function(e){
smoothScroll({yPos: 'start', easing: easings.value, duration: 2000});
});
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll#1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<!-- Taken from one of the library examples -->
Easing: <select id="easings"></select>
<button id="to-bottom">Scroll To Bottom</button>
<br>
<button id="to-top" style="margin-top: 5000px;">Scroll To Top</button>
Alternatively, you can pass an options object to window.scroll which scrolls to a specific x and y position and window.scrollBy which scrolls a certain amount from the current position:
// Scroll to specific values
// scrollTo is the same
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// Scroll certain amounts from current position
window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});
Demo:
<button onClick="scrollToDiv()">Scroll To Element</button>
<div style="margin: 500px 0px;">Div</div>
<script>
function scrollToDiv(){
var elem = document.querySelector("div");
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
}
</script>
If you only need to scroll to an element, not a specific position in the document, you can use Element.scrollIntoView with behavior set to smooth.
document.getElementById("elemID").scrollIntoView({
behavior: 'smooth'
});
Demo:
<button onClick="scrollToDiv()">Scroll To Element</button>
<div id="myDiv" style="margin: 500px 0px;">Div</div>
<script>
function scrollToDiv(){
document.getElementById("myDiv").scrollIntoView({
behavior: 'smooth'
});
}
</script>
Modern browsers support the scroll-behavior CSS property, which can be used to make scrolling in the document smooth (without the need for JavaScript). Anchor tags can be used for this by giving the anchor tag a href of # plus the id of the element to scroll to). You can also set the scroll-behavior property for a specific container like a div to make its contents scroll smoothly.
Demo:
html, body{
scroll-behavior: smooth;
}
Scroll To Element
<div id="elem" style="margin: 500px 0px;">Div</div>
Here's my variation:
let MenuItem = function ( _menuItem ) {
// I had a sticky header, so its height had to be taken into account when scrolling
let _header = document.querySelector('.site-header');
let _scrollToBlock = function( e, menuItem ) {
let id = menuItem.getAttribute('href'), // the href attribute stores the id of the block to which the scroll will be
headerHeight = _header.offsetHeight; // determine the height of the header
id = id.replace(/#/, ''); // remove the # sign from the id block
let elem = document.getElementById( id ), // define the element to which we will scroll
top = elem.getBoundingClientRect().top + window.scrollY - headerHeight; // determine the height of the scroll
window.scroll({
top: top,
left: 0,
behavior: 'smooth'
});
},
_addEvents = function() {
_menuItem.addEventListener('click', function (e){
e.preventDefault(); // Disable redirect on click
_scrollToBlock(e, _menuItem);
});
},
_init = function() {
_addEvents();
};
_init();
};
// Initialize the class MenuItem to all links with class .menu__item
document.querySelectorAll('.menu__item').forEach( function(item) {
new MenuItem(item);
} );
Here's the code that worked for me.
`$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});
`

scroll page so that element is visible

I've just tried prototype's scrollTo function and as the documentation states, it
Scrolls the window so that element
appears at the top of the viewport
I'd like a function that
only scrolls if the element is not entirely visible within the viewport
scrolls so that the element appears at the center of the viewport
does anyone know of such a function in prototype, scriptaculous or stand-alone?
I guess you need something like this (demo):
window.height
function getWindowHeight() {
var body = document.body;
var docEl = document.documentElement;
return window.innerHeight ||
(docEl && docEl.clientHeight) ||
(body && body.clientHeight) ||
0;
}
Scroll
function scrollElemToCenter(id, duration) {
var el = document.getElementById(id);
var winHeight = getWindowHeight();
var offsetTop = el.offsetTop;
if (offsetTop > winHeight) {
var y = offsetTop - (winHeight-el.offsetHeight)/2;
// wo animation: scrollTo(0, y);
scrollToAnim(y, duration);
}
}
Animation (optional, you can use script.aculo.us, etc.)
function interpolate(source,target,pos) { return (source+(target-source)*pos); }
function easing(pos) { return (-Math.cos(pos*Math.PI)/2) + 0.5; }
function scrollToAnim(targetTop, duration) {
duration || (duration = 1000);
var start = +new Date,
finish = start + duration,
startTop = getScrollRoot().scrollTop,
interval = setInterval(function(){
var now = +new Date,
pos = (now>finish) ? 1 : (now-start)/duration;
var y = interpolate(startTop, targetTop, easing(pos)) >> 0;
window.scrollTo(0, y);
if(now > finish) {
clearInterval(interval);
}
}, 10);
}
get scroll root
var getScrollRoot = (function() {
var SCROLL_ROOT;
return function() {
if (!SCROLL_ROOT) {
var bodyScrollTop = document.body.scrollTop;
var docElScrollTop = document.documentElement.scrollTop;
window.scrollBy(0, 1);
if (document.body.scrollTop != bodyScrollTop)
(SCROLL_ROOT = document.body);
else
(SCROLL_ROOT = document.documentElement);
window.scrollBy(0, -1);
}
return SCROLL_ROOT;
};
})();
Here is an alternative approach, that uses some of Prototype's built in functionality for working with the viewport and scroll dimensions...
function scrollToCenterOfElement(id){
// Cache element and property lookups...
var element = $(id);
var height = element.measure('height');
var top = element.cumulativeOffset().top;
var scroll = document.viewport.getScrollOffsets();
var dimensions = document.viewport.getDimensions();
// Checks to see if the top offset plus the height of the element is greater
// than the sum of the viewport height and vertical scroll offset, which means
// that the element has yet to be fully scrolled in to view, or if the
// top offset is smaller than the vertical scroll offset, which means the element
// has already been (at least partly) scrolled out of view..
if ((top + height > dimensions.height + scroll.top) || (top < dimensions.height + scroll.top)) {
// Scroll window to sum of top offset plus half the height of the element
// minus half of the viewport height, thus centering the element vertically.
window.scrollTo(0, top + (height / 2) - (dimensions.height / 2));
}
}
scrollToCenterOfElement('my-element');
My solution does not cover 100% of what is requested, but perhaps someone finds it useful.
/**
* Scroll container so that given element becomes visible. Features:
* <ol>
* <li>If element is already visible, then no action is taken.
* <li>If element is above view port, the viewport is scrolled upwards so that element becomes visible at the top.
* <li>If element is below view port, the viewport is scrolled downwards so that element becomes visible at the bottom.
* </ol>
*
* #param element
* optional string (selector) or jQuery object that controls the scrolling of the element
* #param options
* optional extra settings
* #param options.animationSpeed
* if defined, then scrolling is animated; determines time in milliseconds after which the element should
* be scrolled into viewport
* #param options.heightScale
* double number from 0 to 1; when scrolling the element from bottom sometimes it is desirable to scroll
* element close to the top; e.g. to scroll it to the center specify 0.5; to scroll it to the top specify 0
* #param options.complete
* function to be called after animation is completed; if there is no animation, the function is called straight away
*/
$.fn.scrollTo = function(element, options) {
options = options || {};
var elementTop = element.offset().top;
var containerTop = this.offset().top;
var newScrollTop = null;
if (elementTop < containerTop) {
// Scroll to the top:
newScrollTop = Math.round(this.scrollTop() + elementTop - containerTop);
} else {
// Scroll to the bottom:
var elementBottom = elementTop + element.outerHeight(true);
var containerHeight = this.height();
if (elementBottom > containerTop + containerHeight) {
if (options.heightScale != null) {
if (options.heightScale === 0) {
// This will effectively turn the formulae below into "elementTop - containerTop":
containerHeight = element.outerHeight(true);
} else {
containerHeight *= options.heightScale;
}
}
newScrollTop = Math.round(this.scrollTop() + elementBottom - containerTop - containerHeight);
}
}
if (newScrollTop !== null) {
if (options && options.animationSpeed) {
this.animate({
scrollTop : newScrollTop
}, {
"duration" : options.animationSpeed,
"complete" : options.complete
});
} else {
this.scrollTop(newScrollTop);
if ($.isFunction(options.complete)) {
options.complete();
}
}
} else {
if ($.isFunction(options.complete)) {
options.complete();
}
}
return this;
};
Demo

Categories