- This topic is empty.
-
AuthorPosts
-
August 2, 2016 at 11:09 am #9765jonathanParticipant
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 anhref
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();
November 23, 2016 at 12:33 pm #9749svnmParticipantI 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:
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 } }
January 4, 2017 at 3:11 am #9759shahdatParticipant$('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.
$(‘#content’).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>
February 27, 2017 at 10:09 am #9760user7601056ParticipantAnimations:
// 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 }); });
September 23, 2017 at 12:11 pm #9762fajirParticipantIf 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 }
October 10, 2017 at 1:03 am #9763irshad-khanParticipantEasy way to achieve the scroll of page to target div id
var targetOffset = $('#divID').offset().top; $('html, body').animate({scrollTop: targetOffset}, 1000);
September 22, 2018 at 4:25 am #9754cynyaParticipantThis 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();
November 7, 2018 at 8:51 am #9744polarisParticipantThis worked for me:
var targetOffset = $('#elementToScrollTo').offset().top; $('#DivParent').animate({scrollTop: targetOffset}, 2500);
December 20, 2018 at 5:22 am #9771object-objectParticipantThis is achievable without jQuery:
document.getElementById("element-id").scrollIntoView();
January 17, 2019 at 7:58 am #9750stardust4891ParticipantUpdated answer as of 2019:
$('body').animate({ scrollTop: $('#subject').offset().top - $('body').offset().top + $('body').scrollTop() }, 'fast');
March 19, 2019 at 3:25 am #9745minguocodeParticipantjQuery(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"><a href="#pane1" role="tab">Section 1</a></li> <li id="p2"><a href="#pane2" role="tab">Section 2</a></li> <li id="p3"><a href="#pane3" role="tab">Section 3</a></li> </ul> <div id="pane1"></div> <div id="pane2"></div> <div id="pane3"></div>
June 20, 2019 at 1:59 am #9768edvard-kerbergParticipantThis 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>
January 8, 2020 at 11:16 am #9755kamil-kielczewskiParticipantONELINER
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>
August 13, 2020 at 10:19 am #9746jaber-alshamiParticipantYou just need:
$("selector").get(0).scrollTo(0, 0)
August 26, 2020 at 6:42 am #9761vu-viet-hungParticipantAfter 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 exactpageY
value (seepageY
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");
-
AuthorPosts
- You must be logged in to reply to this topic.