Related
I want to try the same effect of this site but am getting lost in action on how to implement this animation.
When the user starts scrolling, the images in the header zoom in, the scrolling tab(vertical) does not move, up to a point which another image shows up, and only afterward the scroll bar starts working.
How can I achieve this animation when scrolling?
At the moment, what I thought was: to get the pixel value of the DOM when am scrolling, as well as the height of the div I want to target.
While the value of the DOM is less than the height of the box, the scale value should change based on the scrolling value.
The JS looks like this:
<script>
$(window).scroll(function() {
var initial_scroll = $('html').scrollTop();
var firstbox_height = $('#firstbox').height();
// console.log(firstbox_height);
while(initial_scroll < firstbox_height){
var sum = firstbox_height + ((firstbox_height * 0.01) / 100);
$('img').css({
// "transform": "scale(" + sum + ")"
});
}
});
</script>
I seem to be going into an infinite loop.
My pen is here
Here's a working sample. It's not flawless, it bugs when you scroll just a little back and forth at the top, the text size might change in the wrong direction. Also it doesn't work when scrolling with arrow keys. But what it does is that it should give you the idea on how to proceed.
There's probably a cleaner, nicer and more concise way to do this, but this is one way.
To get a perfectly working one, I think you might have to place a transparent <div> over the one that changes, just to keep track of the position and hence the direction.
Fiddle here: https://jsfiddle.net/codesam/nedj3ubx/53/
HTML:
<body>
<div id="box">
Text
</div>
<p id="direction">
</p>
</body>
CSS:
body {
height: 200vh;
}
#box {
width: 100%;
height: 50vh;
background-color: black;
color: white;
font-size: 72px;
}
jQuery:
$(document).ready(function(){
var initialScroll = -1;
var size;
$(window).on('scroll touchmove mousewheel', function(e){
var currentScroll = $(window).scrollTop();
if (currentScroll > initialScroll) {
$("#direction").text("down");
size = parseInt($("#box").css("font-size"));
if (size > 10) {
$("#box").css("font-size", "-=2");
e.preventDefault();
e.stopPropagation();
return false;
}
}
else if (currentScroll < initialScroll) {
$("#direction").text("up");
}
else if (currentScroll == 0 && initialScroll == 0) {
size = parseInt($("#box").css("font-size"));
if (size < 72) {
$("#box").css("font-size", "+=2");
e.preventDefault();
e.stopPropagation();
return false;
}
}
initialScroll = currentScroll;
});
});
I have this input element:
<input type="text" class="textfield" value="" id="subject" name="subject">
Then I have some other elements, like other tag's & <textarea> tag's, etc...
When the user clicks on the <input id="#subject">, the page should scroll to the page's last element, and it should do so with a nice animation (It should be a scroll to bottom and not to top).
The last item of the page is a submit button with #submit:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
The animation should not be too fast and should be fluid.
I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.
Assuming you have a button with the id button, try this example:
$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>
jQuery .scrollTo(): View - Demo, API, Source
I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?
Examples Usage:
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
Options:
scrollTarget: A element, string, or number which indicates desired scroll position.
offsetTop: A number that defines additional spacing above scroll target.
duration: A string or number determining how long the animation will run.
easing: A string indicating which easing function to use for the transition.
complete: A function to call once the animation is complete.
If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
So all you need to do is: $("selector").get(0).scrollIntoView();
.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.
UPDATE
now is possible to scroll with animation, passing scroll options (see MDN). You can even control the block position. It seems to have large support, except for Safari
$("selector").get(0).scrollIntoView({behavior: 'smooth'});
This is achievable without jQuery:
document.getElementById("element-id").scrollIntoView();
Using this simple script
if($(window.location.hash).length > 0){
$('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}
Would make in sort that if a hash tag is found in the url, the scrollTo animate to the ID. If not hash tag found, then ignore the script.
jQuery(document).ready(function($) {
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate( {
'scrollTop': $target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = target;
} );
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul role="tablist">
<li class="active" id="p1">Section 1</li>
<li id="p2">Section 2</li>
<li id="p3">Section 3</li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
This is the way I do it.
document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
Works in any browser.
It can easily be wrapped into a function
function scrollTo(selector) {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
Here is a working example
$(".btn").click(function() {
document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })
})
.btn {margin-bottom: 500px;}
.middle {display: block; margin-bottom: 500px; color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Scroll down</button>
<h1 class="middle">You see?</h1>
<div id="scrollHere">Arrived at your destination</div>
Docs
The solution by Steve and Peter works very well.
But in some cases, you may have to convert the value to an integer. Strangely, the returned value from $("...").offset().top is sometimes in float.
Use: parseInt($("....").offset().top)
For example:
$("#button").click(function() {
$('html, body').animate({
scrollTop: parseInt($("#elementtoScrollToID").offset().top)
}, 2000);
});
A compact version of "animate" solution.
$.fn.scrollTo = function (speed) {
if (typeof(speed) === 'undefined')
speed = 1000;
$('html, body').animate({
scrollTop: parseInt($(this).offset().top)
}, speed);
};
Basic usage: $('#your_element').scrollTo();
With this solution you do not need any plugin and there's no setup required besides placing the script before your closing </body> tag.
$("a[href^='#']").on("click", function(e) {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
return false;
});
if ($(window.location.hash).length > 1) {
$("html, body").animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}
On load, if there is a hash in the address, we scroll to it.
And - whenever you click an a link with an href hash e.g. #top, we scroll to it.
##Edit 2020
If you want a pure JavaScript solution: you could perhaps instead use something like:
var _scrollToElement = function (selector) {
try {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
} catch (e) {
console.warn(e);
}
}
var _scrollToHashesInHrefs = function () {
document.querySelectorAll("a[href^='#']").forEach(function (el) {
el.addEventListener('click', function (e) {
_scrollToElement(el.getAttribute('href'));
return false;
})
})
if (window.location.hash) {
_scrollToElement(window.location.hash);
}
}
_scrollToHashesInHrefs();
If you are only handling scrolling to an input element, you can use focus(). For example, if you wanted to scroll to the first visible input:
$(':input:visible').first().focus();
Or the first visible input in an container with class .error:
$('.error :input:visible').first().focus();
Thanks to Tricia Ball for pointing this out!
Easy way to achieve the scroll of page to target div id
var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
If you want to scroll within an overflow container (instead of $('html, body') answered above), working also with absolute positioning, this is the way to do :
var elem = $('#myElement'),
container = $('#myScrollableContainer'),
pos = elem.position().top + container.scrollTop() - container.position().top;
container.animate({
scrollTop: pos
}
After finding the way to get my code work, I think I should make thing a bit clear:
For using:
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
you need to be on top of the page since $("#div1").offset().top will return different numbers for different positions you scroll to. If you already scrolled out of the top, you need to specify the exact pageY value (see pageY definition here: https://javascript.info/coordinates).
So now, the problem is to calculate the pageY value of one element. Below is an example in case the scroll container is the body:
function getPageY(id) {
let elem = document.getElementById(id);
let box = elem.getBoundingClientRect();
var body = document.getElementsByTagName("BODY")[0];
return box.top + body.scrollTop; // for window scroll: box.top + window.scrollY;
}
The above function returns the same number even if you scrolled somewhere. Now, to scroll back to that element:
$("html, body").animate({ scrollTop: getPageY('div1') }, "slow");
Animations:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});
In most cases, it would be best to use a plugin. Seriously. I'm going to tout mine here. Of course there are others, too. But please check if they really avoid the pitfalls for which you'd want a plugin in the first place - not all of them do.
I have written about the reasons for using a plugin elsewhere. In a nutshell, the one liner underpinning most answers here
$('html, body').animate( { scrollTop: $target.offset().top }, duration );
is bad UX.
The animation doesn't respond to user actions. It carries on even if the user clicks, taps, or tries to scroll.
If the starting point of the animation is close to the target element, the animation is painfully slow.
If the target element is placed near the bottom of the page, it can't be scrolled to the top of the window. The scroll animation stops abruptly then, in mid motion.
To handle these issues (and a bunch of others), you can use a plugin of mine, jQuery.scrollable. The call then becomes
$( window ).scrollTo( targetPosition );
and that's it. Of course, there are more options.
With regard to the target position, $target.offset().top does the job in most cases. But please be aware that the returned value doesn't take a border on the html element into account (see this demo). If you need the target position to be accurate under any circumstances, it is better to use
targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;
That works even if a border on the html element is set.
This is my approach abstracting the ID's and href's, using a generic class selector
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 500);
});
});
<!-- example of a fixed nav menu -->
<ul class="nav">
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>
Very simple and easy to use custom jQuery plugin. Just add the attribute scroll= to your clickable element and set its value to the selector you want to scroll to.
Like so: <a scroll="#product">Click me</a>. It can be used on any element.
(function($){
$.fn.animateScroll = function(){
console.log($('[scroll]'));
$('[scroll]').click(function(){
selector = $($(this).attr('scroll'));
console.log(selector);
console.log(selector.offset().top);
$('html body').animate(
{scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
1000
);
});
}
})(jQuery);
// RUN
jQuery(document).ready(function($) {
$().animateScroll();
});
// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
$('html, body').animate(...) does not work for me in the iPhone, Android, Chrome, or Safari browsers.
I had to target the root content element of the page.
$('#cotnent').animate(...)
Here is what I have ended up with:
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
$('#content').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
else{
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
All body content wired up with a #content div
<html>
....
<body>
<div id="content">
...
</div>
</body>
</html>
$('html, body').animate({scrollTop:
Math.min(
$(to).offset().top-margintop, //margintop is the margin above the target
$('body')[0].scrollHeight-$('body').height()) //if the target is at the bottom
}, 2000);
To show the full element (if it's possible with the current window size):
var element = $("#some_element");
var elementHeight = element.height();
var windowHeight = $(window).height();
var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);
var scrollTo = function($parent, $element) {
var topDiff = $element.position().top - $parent.position().top;
$parent.animate({
scrollTop : topDiff
}, 100);
};
This is Atharva's answer from: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView.
Just wanted to add if your document is in an iframe, you can choose an element in the parent frame to scroll into view:
$('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
I wrote a general purpose function that scrolls to either a jQuery object, a CSS selector, or a numeric value.
Example usage:
// scroll to "#target-element":
$.scrollTo("#target-element");
// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);
// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
The function's code:
/**
* Scrolls the container to the target position minus the offset
*
* #param target - the destination to scroll to, can be a jQuery object
* jQuery selector, or numeric position
* #param offset - the offset in pixels from the target position, e.g.
* pass -80 to scroll to 80 pixels above the target
* #param speed - the scroll speed in milliseconds, or one of the
* strings "fast" or "slow". default: 500
* #param container - a jQuery object or selector for the container to
* be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {
if (isNaN(target)) {
if (!(target instanceof jQuery))
target = $(target);
target = parseInt(target.offset().top);
}
container = container || "html, body";
if (!(container instanceof jQuery))
container = $(container);
speed = speed || 500;
offset = offset || 0;
container.animate({
scrollTop: target + offset
}, speed);
};
When the user clicks on that input with #subject, the page should
scroll to the last element of the page with a nice animation. It
should be a scroll to bottom and not to top.
The last item of the page is a submit button with #submit
$('#subject').click(function()
{
$('#submit').focus();
$('#subject').focus();
});
This will first scroll down to #submit then restore the cursor back to the input that was clicked, which mimics a scroll down, and works on most browsers. It also doesn't require jQuery as it can be written in pure JavaScript.
Can this fashion of using focus function mimic animation in a better way, through chaining focus calls. I haven't tested this theory, but it would look something like this:
<style>
#F > *
{
width: 100%;
}
</style>
<form id="F" >
<div id="child_1"> .. </div>
<div id="child_2"> .. </div>
..
<div id="child_K"> .. </div>
</form>
<script>
$('#child_N').click(function()
{
$('#child_N').focus();
$('#child_N+1').focus();
..
$('#child_K').focus();
$('#child_N').focus();
});
</script>
I set up a module scroll-element npm install scroll-element. It works like this:
import { scrollToElement, scrollWindowToElement } from 'scroll-element'
/* scroll the window to your target element, duration and offset optional */
let targetElement = document.getElementById('my-item')
scrollWindowToElement(targetElement)
/* scroll the overflow container element to your target element, duration and offset optional */
let containerElement = document.getElementById('my-container')
let targetElement = document.getElementById('my-item')
scrollToElement(containerElement, targetElement)
Written with help from the following SO posts:
offset-top-of-an-element-without-jquery
scrolltop-animation-without-jquery
Here is the code:
export const scrollToElement = function(containerElement, targetElement, duration, offset) {
if (duration == null) { duration = 1000 }
if (offset == null) { offset = 0 }
let targetOffsetTop = getElementOffset(targetElement).top
let containerOffsetTop = getElementOffset(containerElement).top
let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
scrollTarget += offset
scroll(containerElement, scrollTarget, duration)
}
export const scrollWindowToElement = function(targetElement, duration, offset) {
if (duration == null) { duration = 1000 }
if (offset == null) { offset = 0 }
let scrollTarget = getElementOffset(targetElement).top
scrollTarget += offset
scrollWindow(scrollTarget, duration)
}
function scroll(containerElement, scrollTarget, duration) {
let scrollStep = scrollTarget / (duration / 15)
let interval = setInterval(() => {
if ( containerElement.scrollTop < scrollTarget ) {
containerElement.scrollTop += scrollStep
} else {
clearInterval(interval)
}
},15)
}
function scrollWindow(scrollTarget, duration) {
let scrollStep = scrollTarget / (duration / 15)
let interval = setInterval(() => {
if ( window.scrollY < scrollTarget ) {
window.scrollBy( 0, scrollStep )
} else {
clearInterval(interval)
}
},15)
}
function getElementOffset(element) {
let de = document.documentElement
let box = element.getBoundingClientRect()
let top = box.top + window.pageYOffset - de.clientTop
let left = box.left + window.pageXOffset - de.clientLeft
return { top: top, left: left }
}
Updated answer as of 2019:
$('body').animate({
scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
}, 'fast');
ONELINER
subject.onclick = e=> window.scroll({ top: submit.offsetTop, behavior: 'smooth'});
subject.onclick = e=> window.scroll({top: submit.offsetTop, behavior: 'smooth'});
.box,.foot{display: flex;background:#fdf;padding:500px 0} .foot{padding:250px}
<input type="text" class="textfield" value="click here" id="subject" name="subject">
<div class="box">
Some content
<textarea></textarea>
</div>
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
<div class="foot">Some footer</div>
For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling. In our case we don't scroll the full body, but just particular elements with overflow: auto; within a larger layout.
It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.
var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');
$scrollTo.prepend(inputElem);
inputElem.css({
position: 'absolute',
width: '1px',
height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();
This worked for me:
var targetOffset = $('#elementToScrollTo').offset().top;
$('#DivParent').animate({scrollTop: targetOffset}, 2500);
Let's say i have a box and it's offset from the correct spot by tranform:translateX(-200px)
Example below pic has two <section>'s, one is the large grey box and other white containing the .box in red. The illustration shows where/how the animation should move only as the viewer scrolls and contentiously move .box back and forth from -200px to 0px.
$( document ).ready(function(){
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
var greySection = $('.grey').height(); // Which is 800px high
// (what other variables, and functions could I add? )
if( wScroll > greySection /1.3 ) // 1.3 of section.grey is where i want the animation to start
$('.box').css('transform','translateX(' + /* (what do i put here?) */ + 'px)');
});
});
.grey{ /* for visual purposes */
background-color: grey;
}
section {
width:100%;
height:800px;
}
p{
width:100%;
text-align:center;
}
.box{
width:200px;
height:200px;
background-color:red;
margin:0 auto; /* Here is where the box position should end up */
transform:translateX(-200px); /* Control this property to move box */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<section class="grey">
<p>Some contents here. Ignore this section</p>
</section>
<section id="box-holder">
<div class="box"></div>
</section>
How could i let the user control the transform property of the box position to the finished spot -200px to 0px only back and forth with the scrollbar.
I will look into now but first a few hints.
Use document ready so your variable gets stored ones and not after each scroll.
$( document ).ready(function() {
var greySection = $('.grey').height();
});
Should the box slide to the complete right, directly in the middle or just 200px to the right? I got a little confused by the -200px.
Here you go
https://jsfiddle.net/DenizTemizer/j6m73qnf/1/
var greySection;
$( document ).ready(function() {
greySection = $('.grey').height();
console.log(greySection);
});
$(window).scroll(function() {
var wScroll = $(this).scrollTop();
if( !$('.grey').hasClass('animated') && wScroll > (greySection / 1.3) ) {
console.log("animate");
$('.grey').addClass('animated');
$('.box').css({
"-webkit-transform":"translateX(0)",
"-ms-transform":"translateX(0)",
"transform":"translateX(0)"
});
}
});
Added as new answer so it is easier to find if this thread gets bigger.
Ripped this from stuff I'm working on, then chunked it together, Dig in.
The formula you want is something like:
(scrollTop-topOffset)/(pageHeight-windowHeight-topOffset)*translateDistance
This is where it is in the JavaScript:
mem[7] = -(~~(((mem[0]-BoxOffset)/mem[6])*BoxDistance));
This needs some work, I used a right shift by zero to round the result but it was acting weird when I ran the snippet so I used the double '~~' and then had to set it to negative '-' to make it positive, don't copy/paste, fix/tidy up my chicken scratch!! XD
INP=0xFFFF; // INPut flags
BoxDistance=200; // box travel distance
mem=[]; // mem array
JC = function(intv, event){
L_BOOT:{
L_TRIPEVENT:{
if (!event) break L_TRIPEVENT; // if there is an event
event = event || window.event; // for IE
if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } // stop bubble up
FP= event.target ? event.target : event.srcElement; // get it
if ((INP&=intv)&0x002) break L_TRIPEVENT; // if boot is complete
INP_Resize:{
// Save the old browser width/height dimentions? if needed ...
if(INP&0x020) break INP_Resize; INP |= 0x020; // INP_Resize = OFF
//
// Get the window dimentions
//
mem[2] = (document.body.innerWidth)? document.body.innerWidth : document.body.clientWidth; // window width
mem[3] = (document.body.innerHeight)? document.body.innerHeight : document.body.clientHeight; // window height
//
// Get the page dimentions
//
mem[4]=document.getElementById('box-holder').offsetWidth; // section width:
mem[5]=document.getElementById('box-holder').offsetHeight*2; // section width: (box-holder x 2) both sections are of the same height
BoxOffset=document.getElementById('ThisTrigger').offsetHeight; // section width:
mem[6]=mem[5]-mem[3]-BoxOffset; // page height - window height = (scroll bottom)
}// INP_Resize:
INP_Scroll:{
mem[1] = mem[0]; // Save last scroll location, not really needed ...
if(INP&0x010) break INP_Scroll; INP |= 0x010; // INP_Scroll = OFF
mem[0] = ((document.body.scrollTop)? (document.body.scrollTop) : ((document.documentElement.scrollTop)? (document.documentElement.scrollTop):(window.pageYOffset) ));// get current scroll location
if ( BoxOffset<mem[0] ) { // get current scroll location
if (BoxOffset<mem[0]) {
mem[7] = -(~~(((mem[0]-BoxOffset)/mem[6])*BoxDistance)); // right shift 0 times, un-round to a whole number
/*
mem[0] = scroll top -> DistanceThusFar
BoxOffset = with the top offfset
mem[6] = (scroll bottom) -> DistanceCanGo
BoxDistance = distance
(DistanceThusFar / DistanceCanGo) = (0.???)%
the ratio between how far, and whats left to go
(0.???) * (BoxDistance) = (???px)
the ratio multiplied by BoxDistance is the distance
*/
mem[7] = BoxDistance<mem[7] ? BoxDistance : mem[7]; // if the number rounded, exceeds BoxDistance, set it to BoxDistance
}//if (mem[0]>=BoxOffse...
} else {
mem[7]^=mem[7]; // if the number rounded, is greater than 0, when scrollTop is less then trigger height, set it to zero
}
AX=mem[7];
document.getElementById("meee").setAttribute('style', 'margin-left: '+AX+'px;'); // update box distance
}// INP_Scroll:
}//L_TRIPEVENT:
if (INP&0x001) break L_BOOT; INP|=0x001; INP&=0xFFD; // L_BOOT = OFF
INP &= 0xFEF; // 1110:1111 <- set this bit off, to trip SCROLL interupt
INP &= 0xFDF; // 1110:1111 <- set this bit off, to trip SCROLL interupt
}//L_BOOT:
//
// Print out memory
//
PrintText='';
i=0;
do{
PrintText += "<br> " + i + " " + mem[i];
i++;
}while (i^0x08)
document.getElementById("JC_TEST_TEXT").innerHTML = PrintText;
PrintText^=PrintText;
TIC=setTimeout(JC,100);
}; JC();
function JCinterupts(i0,i1,i2,i3){
if ('addEventListener' in window){
window.addEventListener(i0, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFBF ), false);
window.addEventListener(i1, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFEF ), false);
window.addEventListener(i2, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFDF ), false);
window.addEventListener(i3, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFFE ), false);
} else if ('attachEvent' in window){//IE
window.attachEvent('on'+i0, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFBF ) );
window.attachEvent('on'+i1, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFEF ) );
window.attachEvent('on'+i2, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFDF ) );
window.attachEvent('on'+i2, ( function (intv) {return function (event) {JC(intv, event);};} )( 0xFFE ) );
}
} JCinterupts('click','scroll','resize','load');
<!--
░░█████░░░░░░░░░░░░███░░░░░░░░░░░░
░░░░█░░░░░░░░░░░░░░█░░░░░░░░░█░░░░
░░░░█░░███░███░███░█░░░███░░░█░███
░░░░█░░█░█░█░█░█░░░█░░░█░█░███░█░█ JonathanClingan
░░░░█░░█░█░█░█░░░█░█░░░█░█░█░█░█░░ ©JonsCode
░░███░░███░█░█░███░███░███░███░███ 5.24.16
■ JonWasHere :P
-->
<HTML /><!-- HTML markup -->
<HEAD /><!-- self closing tags -->
<style>
HTML,BODY {
margin:0;
padding:0;
border:0;
}
.grey{ /* for visual purposes */
background-color: grey;
}
.darkgrey{ /* for visual purposes */
background-color: darkgrey;
height:34px;
}
section {
width:100%;
height:134px;
}
p{
width:100%;
text-align:center;
}
.box{
left:200px;
width:200px;
height:200px;
background-color:red;
margin:0 auto;
}
#JC_TEST_HOLD{
position:absolute;
position:fixed;
overflow:visible;
padding:0 10px 0 0;
color:white;
z-index:900;
text-align:left;
}
#JC_TEST_BOX{
height:100%;
overflow:auto;
position:relative;
margin:0;
padding:0 15px 0 0;
color:white;
background:rgba(0,0,0,0.8);
text-align:left;
}
#JC_TEST_TEXT{
text-align:left;
}
</style>
<BODY /><!-- Mhmmm, I like yo' body. ;) -->
<DIV ID="JC_TEST_HOLD" >
<DIV ID="JC_TEST_BOX" >
<p id="JC_TEST_TEXT"></p>
</DIV>
</DIV>
<section id="ThisBox" class="grey">
<div id="ThisTrigger" class="darkgrey">
<p>Some contents here. Ignore this section, or pay attention.</p>
</div>
</section>
<section id="box-holder">
<div id="meee" class="box"></div>
</section>
I have a back to top image that popups when the user scrolls beyond 280. The issue is when you reach the bottom the image is over links in the footer. So I want to change the position of the image once the user is about 90px from the very bottom of the page - I want "bottom": '35px' to be 95. The page height is always changing fyi. Code I have:
function update() {
if ($(window).scrollTop() > 280) {
$('#btt').animate({
"bottom": '35px'
}, 300);
}
else {
$('#btt').animate({
"bottom": '-80px'
}, 300);
}
}
setInterval(update, 500);
It might be better to check for the scroll position only when the page has been scrolled rather than just checking every 1/2 second.
I've put together a working demo of what I think you want here: http://jsfiddle.net/swpqpv4r/5/
Basically we need to look at the scroll position of the bottom of the window as we scroll instead of the top by using document.body.scrollTop + $(win).height(). Normaly we might want to worry about what could happen if the window were to be resized, but we calculate this each time inside of the scroll event, so it shouldn't be an issue if the window changes sizes.
Next we need to know when the top of the footer has scrolled above the bottom of the window. We can use $("#footer").position().top; to see where it's top position is.
Hopefully the code is commented enough to help explain it. Let me know if you have any questions.
HTML
<header>Top</header>
<br><br><br> <!-- Lots of these for testing -->
<footer id="footer">Bottom</footer>
<a id="btt" href="javascript:{};">Back to top</a>
JavaScript
$(function(){
//select once and re-use later
var $win = $(window);
var $btt = $("#btt");
var $foot = $("#footer");
var bttDisplay = 500;
var footerHeight = $foot.outerHeight();
var footerTop = $foot.position().top;
function updateScroll() {
var scrollBottom = document.body.scrollTop + $win.height();
if (scrollBottom >= bttDisplay && scrollBottom <= footerTop) {
//show it by setting the bottom position to 0
animateBtt(0);
}else if (scrollBottom >= footerTop) {
//move it up above the footer's top position
animateBtt(footerHeight);
}else {
//hide it by setting the bottom position to the negative value of it's height
animateBtt($btt.height() * -1);
}
}
function animateBtt(pos){
$btt.animate({
"bottom": pos
}, 300);
}
//run initially
updateScroll();
//Create a var to hold the timer
var scrollTimer = null;
$win.on("scroll",function(ev){
//when scrolling, clear the timer
clearTimeout(scrollTimer);
//Now set the timer to run a function after a small delay.
//This prevents the update from happening too many times when you scroll
scrollTimer = setTimeout(updateScroll, 50);
});
//click to scroll back up
$btt.on("click",function(){
$('html, body').animate({scrollTop:0},300);
})
});
CSS
html,body{
margin:0;
padding:0;
}
header, footer{
background: #CCC;
padding: 10px;
}
#btt{
position:fixed;
height: 30px;
width: 100px;
text-align:center;
bottom: -30px;
right:0;
background: #F00;
color: #FFF;
z-index: 1000;
}
I have this input element:
<input type="text" class="textfield" value="" id="subject" name="subject">
Then I have some other elements, like other tag's & <textarea> tag's, etc...
When the user clicks on the <input id="#subject">, the page should scroll to the page's last element, and it should do so with a nice animation (It should be a scroll to bottom and not to top).
The last item of the page is a submit button with #submit:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
The animation should not be too fast and should be fluid.
I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.
Assuming you have a button with the id button, try this example:
$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>
jQuery .scrollTo(): View - Demo, API, Source
I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?
Examples Usage:
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
Options:
scrollTarget: A element, string, or number which indicates desired scroll position.
offsetTop: A number that defines additional spacing above scroll target.
duration: A string or number determining how long the animation will run.
easing: A string indicating which easing function to use for the transition.
complete: A function to call once the animation is complete.
If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
So all you need to do is: $("selector").get(0).scrollIntoView();
.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.
UPDATE
now is possible to scroll with animation, passing scroll options (see MDN). You can even control the block position. It seems to have large support, except for Safari
$("selector").get(0).scrollIntoView({behavior: 'smooth'});
This is achievable without jQuery:
document.getElementById("element-id").scrollIntoView();
Using this simple script
if($(window.location.hash).length > 0){
$('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}
Would make in sort that if a hash tag is found in the url, the scrollTo animate to the ID. If not hash tag found, then ignore the script.
jQuery(document).ready(function($) {
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate( {
'scrollTop': $target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = target;
} );
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul role="tablist">
<li class="active" id="p1">Section 1</li>
<li id="p2">Section 2</li>
<li id="p3">Section 3</li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
This is the way I do it.
document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
Works in any browser.
It can easily be wrapped into a function
function scrollTo(selector) {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
Here is a working example
$(".btn").click(function() {
document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })
})
.btn {margin-bottom: 500px;}
.middle {display: block; margin-bottom: 500px; color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Scroll down</button>
<h1 class="middle">You see?</h1>
<div id="scrollHere">Arrived at your destination</div>
Docs
The solution by Steve and Peter works very well.
But in some cases, you may have to convert the value to an integer. Strangely, the returned value from $("...").offset().top is sometimes in float.
Use: parseInt($("....").offset().top)
For example:
$("#button").click(function() {
$('html, body').animate({
scrollTop: parseInt($("#elementtoScrollToID").offset().top)
}, 2000);
});
A compact version of "animate" solution.
$.fn.scrollTo = function (speed) {
if (typeof(speed) === 'undefined')
speed = 1000;
$('html, body').animate({
scrollTop: parseInt($(this).offset().top)
}, speed);
};
Basic usage: $('#your_element').scrollTo();
With this solution you do not need any plugin and there's no setup required besides placing the script before your closing </body> tag.
$("a[href^='#']").on("click", function(e) {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
return false;
});
if ($(window.location.hash).length > 1) {
$("html, body").animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}
On load, if there is a hash in the address, we scroll to it.
And - whenever you click an a link with an href hash e.g. #top, we scroll to it.
##Edit 2020
If you want a pure JavaScript solution: you could perhaps instead use something like:
var _scrollToElement = function (selector) {
try {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
} catch (e) {
console.warn(e);
}
}
var _scrollToHashesInHrefs = function () {
document.querySelectorAll("a[href^='#']").forEach(function (el) {
el.addEventListener('click', function (e) {
_scrollToElement(el.getAttribute('href'));
return false;
})
})
if (window.location.hash) {
_scrollToElement(window.location.hash);
}
}
_scrollToHashesInHrefs();
If you are only handling scrolling to an input element, you can use focus(). For example, if you wanted to scroll to the first visible input:
$(':input:visible').first().focus();
Or the first visible input in an container with class .error:
$('.error :input:visible').first().focus();
Thanks to Tricia Ball for pointing this out!
Easy way to achieve the scroll of page to target div id
var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
If you want to scroll within an overflow container (instead of $('html, body') answered above), working also with absolute positioning, this is the way to do :
var elem = $('#myElement'),
container = $('#myScrollableContainer'),
pos = elem.position().top + container.scrollTop() - container.position().top;
container.animate({
scrollTop: pos
}
After finding the way to get my code work, I think I should make thing a bit clear:
For using:
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
you need to be on top of the page since $("#div1").offset().top will return different numbers for different positions you scroll to. If you already scrolled out of the top, you need to specify the exact pageY value (see pageY definition here: https://javascript.info/coordinates).
So now, the problem is to calculate the pageY value of one element. Below is an example in case the scroll container is the body:
function getPageY(id) {
let elem = document.getElementById(id);
let box = elem.getBoundingClientRect();
var body = document.getElementsByTagName("BODY")[0];
return box.top + body.scrollTop; // for window scroll: box.top + window.scrollY;
}
The above function returns the same number even if you scrolled somewhere. Now, to scroll back to that element:
$("html, body").animate({ scrollTop: getPageY('div1') }, "slow");
Animations:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});
In most cases, it would be best to use a plugin. Seriously. I'm going to tout mine here. Of course there are others, too. But please check if they really avoid the pitfalls for which you'd want a plugin in the first place - not all of them do.
I have written about the reasons for using a plugin elsewhere. In a nutshell, the one liner underpinning most answers here
$('html, body').animate( { scrollTop: $target.offset().top }, duration );
is bad UX.
The animation doesn't respond to user actions. It carries on even if the user clicks, taps, or tries to scroll.
If the starting point of the animation is close to the target element, the animation is painfully slow.
If the target element is placed near the bottom of the page, it can't be scrolled to the top of the window. The scroll animation stops abruptly then, in mid motion.
To handle these issues (and a bunch of others), you can use a plugin of mine, jQuery.scrollable. The call then becomes
$( window ).scrollTo( targetPosition );
and that's it. Of course, there are more options.
With regard to the target position, $target.offset().top does the job in most cases. But please be aware that the returned value doesn't take a border on the html element into account (see this demo). If you need the target position to be accurate under any circumstances, it is better to use
targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;
That works even if a border on the html element is set.
This is my approach abstracting the ID's and href's, using a generic class selector
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 500);
});
});
<!-- example of a fixed nav menu -->
<ul class="nav">
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>
Very simple and easy to use custom jQuery plugin. Just add the attribute scroll= to your clickable element and set its value to the selector you want to scroll to.
Like so: <a scroll="#product">Click me</a>. It can be used on any element.
(function($){
$.fn.animateScroll = function(){
console.log($('[scroll]'));
$('[scroll]').click(function(){
selector = $($(this).attr('scroll'));
console.log(selector);
console.log(selector.offset().top);
$('html body').animate(
{scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
1000
);
});
}
})(jQuery);
// RUN
jQuery(document).ready(function($) {
$().animateScroll();
});
// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
$('html, body').animate(...) does not work for me in the iPhone, Android, Chrome, or Safari browsers.
I had to target the root content element of the page.
$('#cotnent').animate(...)
Here is what I have ended up with:
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
$('#content').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
else{
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
All body content wired up with a #content div
<html>
....
<body>
<div id="content">
...
</div>
</body>
</html>
$('html, body').animate({scrollTop:
Math.min(
$(to).offset().top-margintop, //margintop is the margin above the target
$('body')[0].scrollHeight-$('body').height()) //if the target is at the bottom
}, 2000);
To show the full element (if it's possible with the current window size):
var element = $("#some_element");
var elementHeight = element.height();
var windowHeight = $(window).height();
var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);
var scrollTo = function($parent, $element) {
var topDiff = $element.position().top - $parent.position().top;
$parent.animate({
scrollTop : topDiff
}, 100);
};
This is Atharva's answer from: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView.
Just wanted to add if your document is in an iframe, you can choose an element in the parent frame to scroll into view:
$('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
I wrote a general purpose function that scrolls to either a jQuery object, a CSS selector, or a numeric value.
Example usage:
// scroll to "#target-element":
$.scrollTo("#target-element");
// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);
// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
The function's code:
/**
* Scrolls the container to the target position minus the offset
*
* #param target - the destination to scroll to, can be a jQuery object
* jQuery selector, or numeric position
* #param offset - the offset in pixels from the target position, e.g.
* pass -80 to scroll to 80 pixels above the target
* #param speed - the scroll speed in milliseconds, or one of the
* strings "fast" or "slow". default: 500
* #param container - a jQuery object or selector for the container to
* be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {
if (isNaN(target)) {
if (!(target instanceof jQuery))
target = $(target);
target = parseInt(target.offset().top);
}
container = container || "html, body";
if (!(container instanceof jQuery))
container = $(container);
speed = speed || 500;
offset = offset || 0;
container.animate({
scrollTop: target + offset
}, speed);
};
When the user clicks on that input with #subject, the page should
scroll to the last element of the page with a nice animation. It
should be a scroll to bottom and not to top.
The last item of the page is a submit button with #submit
$('#subject').click(function()
{
$('#submit').focus();
$('#subject').focus();
});
This will first scroll down to #submit then restore the cursor back to the input that was clicked, which mimics a scroll down, and works on most browsers. It also doesn't require jQuery as it can be written in pure JavaScript.
Can this fashion of using focus function mimic animation in a better way, through chaining focus calls. I haven't tested this theory, but it would look something like this:
<style>
#F > *
{
width: 100%;
}
</style>
<form id="F" >
<div id="child_1"> .. </div>
<div id="child_2"> .. </div>
..
<div id="child_K"> .. </div>
</form>
<script>
$('#child_N').click(function()
{
$('#child_N').focus();
$('#child_N+1').focus();
..
$('#child_K').focus();
$('#child_N').focus();
});
</script>
I set up a module scroll-element npm install scroll-element. It works like this:
import { scrollToElement, scrollWindowToElement } from 'scroll-element'
/* scroll the window to your target element, duration and offset optional */
let targetElement = document.getElementById('my-item')
scrollWindowToElement(targetElement)
/* scroll the overflow container element to your target element, duration and offset optional */
let containerElement = document.getElementById('my-container')
let targetElement = document.getElementById('my-item')
scrollToElement(containerElement, targetElement)
Written with help from the following SO posts:
offset-top-of-an-element-without-jquery
scrolltop-animation-without-jquery
Here is the code:
export const scrollToElement = function(containerElement, targetElement, duration, offset) {
if (duration == null) { duration = 1000 }
if (offset == null) { offset = 0 }
let targetOffsetTop = getElementOffset(targetElement).top
let containerOffsetTop = getElementOffset(containerElement).top
let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
scrollTarget += offset
scroll(containerElement, scrollTarget, duration)
}
export const scrollWindowToElement = function(targetElement, duration, offset) {
if (duration == null) { duration = 1000 }
if (offset == null) { offset = 0 }
let scrollTarget = getElementOffset(targetElement).top
scrollTarget += offset
scrollWindow(scrollTarget, duration)
}
function scroll(containerElement, scrollTarget, duration) {
let scrollStep = scrollTarget / (duration / 15)
let interval = setInterval(() => {
if ( containerElement.scrollTop < scrollTarget ) {
containerElement.scrollTop += scrollStep
} else {
clearInterval(interval)
}
},15)
}
function scrollWindow(scrollTarget, duration) {
let scrollStep = scrollTarget / (duration / 15)
let interval = setInterval(() => {
if ( window.scrollY < scrollTarget ) {
window.scrollBy( 0, scrollStep )
} else {
clearInterval(interval)
}
},15)
}
function getElementOffset(element) {
let de = document.documentElement
let box = element.getBoundingClientRect()
let top = box.top + window.pageYOffset - de.clientTop
let left = box.left + window.pageXOffset - de.clientLeft
return { top: top, left: left }
}
Updated answer as of 2019:
$('body').animate({
scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop()
}, 'fast');
ONELINER
subject.onclick = e=> window.scroll({ top: submit.offsetTop, behavior: 'smooth'});
subject.onclick = e=> window.scroll({top: submit.offsetTop, behavior: 'smooth'});
.box,.foot{display: flex;background:#fdf;padding:500px 0} .foot{padding:250px}
<input type="text" class="textfield" value="click here" id="subject" name="subject">
<div class="box">
Some content
<textarea></textarea>
</div>
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
<div class="foot">Some footer</div>
For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling. In our case we don't scroll the full body, but just particular elements with overflow: auto; within a larger layout.
It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.
var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');
$scrollTo.prepend(inputElem);
inputElem.css({
position: 'absolute',
width: '1px',
height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();
This worked for me:
var targetOffset = $('#elementToScrollTo').offset().top;
$('#DivParent').animate({scrollTop: targetOffset}, 2500);