How to scroll to a part of the page using jQuery? - javascript

My code scrolls the user to the bottom of the page:
var $elem = $('body');
$('html, body').animate({scrollTop: $elem.height()}, 800);
How can it be modified to take the user to the part of the page where there is a h3 tag with the id "myTitle":
<h3 id="myTitle">Hello</h3>

How about:
var $elem = $("#myTitle");
$('html, body').animate({scrollTop: $elem.offset().top}, 800);
using .offset().
Here's a working example: http://jsfiddle.net/naTjL/

You can get the offset of the element from the top:
var position = $("#myTitle").offset().top;
You can then use that as the value to scroll to.

This is a brilliant example
That even works with JS turned off. Additionally this adds the #myTitle to the URL allowing bookmarking.

$('html, body').scrollTop($("#myTitle").offset().top)

Related

smooth scroll does not work with overflow-y

I am trying to use a smooth scroll and adopted an example I found online. Here is a fiddle with my code
https://jsfiddle.net/4DcNH/144/
I have special conditions set to html and body (basically to offset the page context by 50px from the top to avoid the navbar). Therefore the smooth scroll does not work. Does anybody know a solution to this?
thanks
carl
$(document).ready(function() {
$('a[rel="relativeanchor"]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 2000);
return false;
});
});
Is this what you're after?
$(document).ready(function () {
if(!/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
$('html').css({'overflow-x':'auto','overflow-y':'hidden'});
}
$('a[rel="relativeanchor"]').click(function () {
var $el = $($(this).attr('href'));
$('html, body').stop().animate({
scrollTop: $el.prop('offsetTop')
}, 2000);
return false;
});
});
JSFiddle
Updates were needed in the CSS. The html overflows were removed for chrome, because otherwise, this would not work in Chrome. However, the overflows are needed for Firefox, so they are done by setting it dynamically in the JavaScript (set if not chrome).
If you want to maintain an offset, subtract it from the calculated offset. Given the above, $el.prop('offsetTop') - 50 adds 50px above.
The issue appears to be related to differences in how Chrome scrolls the <body> with height:100%. A discussion of the issue is here: Body set to overflow-y:hidden but page is still scrollable in Chrome
A workable solution is to wrap the scrolling content in <div class="content"> and disable scrolling on <body>.
Here's a JSFiddle to demonstrate the updated behavior: https://jsfiddle.net/f1zv1c5k/5/
To get the scroll to stop at the appropriate point, you need to subtract the vertical offset applied to the <html> tag (using $el.prop('offsetTop') recommended by #vol7ron) when scrolling. Your smooth scroll function would look like this:
$('a[rel="relativeanchor"]').click(function(){
var $el = $($(this).attr('href'));
$('.content').animate({
scrollTop: $el.prop('offsetTop')
}, 2000);
return false;
});

Simple easing on bootstrap scrollspy

This is pretty simple question I think for those who knows javascript/jquery good. I am pretty new to all this and couldn't make it. I found code that is calculating the offset of navbar that looks like this:
var offset = 50;
$('.navbar li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);
});
And here is the fiddle example of what I have so far. As you can see if you click link in navbar it just skips to section. Where in this script to add easing so it scroll down a bit smoother?
With original code I found first I had that smooth scroll but with new script is lost. This is the old code:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
Plavookac Hi there.
I have set up a working sample here in this Fiddle for you.
When you place this code in your page, place it below all of you other js script links. or if you put this in a script link, place the link at the end.
I take it that you would already have the jquery link .
Have a look at this code here, you will see the smooth scrolling and the offset.
$(document).ready(function(){
// Add scrollspy to <body>
$('body').scrollspy({target: "#navbar"});
// Add smooth scrolling on all links inside the navbar
$("#navbar a").on('click', function(event) {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top - 60
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
});
});
Notice this line of code... event.preventDefault(); this is used to prevent that flicker when first clicked to start the scrolling.
This part of the code will handle the smooth scroll.
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top - 60
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
Does this help?

Jquery: scrollTop() is not set to a value

i am trying to scroll the page to the ajax loader gif in the page on the click of a link.
As shown below i am trying to scroll to the div with id "divWaitImage"
However scrollTop used below is not working when given the variable offs as parm.
var offS = $("#divWaitImage").offset().top;
$('html, body').animate({ scrollTop: offS}, 'slow');
However it works if i pass in a hardcoded value:
$('html, body').animate({ scrollTop: 500}, 'slow');
Can anyone please point out the error or a workaround , i am sure its something that i have missed.
thanks for any pointers in advance!
According to your current question this might be a good approach.
http://jsfiddle.net/rRsM4/1/
This is not true -> You need to make sure that you have a height set in the parent container. You can remove the height.
Updated version: http://jsfiddle.net/floradu88/rRsM4/2/
Html:
<div style="height:1500px;">
<img src="http://linux.m2osw.com/sites/linux.m2osw.com/files/images/waiting-wheel-300x300.gif" alt="image" style="margin-top:1000px;" id="divWaitImage"/>
</div>
JS:
var offS = $("#divWaitImage").offset().top;
$('html, body').animate({ scrollTop: offS}, 'slow');
P.S. I will update the answer if you provide updates to your question.

jQuery animated vertical scroll to one element and horizontal to different element at the same time from a single hash tag/variable

I am a jQuery novice but have got really close to achieving my result. Basically what I am trying to do is the following process:
From page load #anchor:
Convert the hash to an ID and a class
Scroll vertical to an element with the anchor ID
Scroll horizontal to a different element with a class
Additionally, the same functionality works when on the page. I am trying to direct link to the url.homl#hash so it is important that the animation effect works on the load as well.
My example is here: http://willminnig.com/stacko/vertical-test-5.html#1908
So far, I can get it to scroll to the vertical ID on page load but not the horizontal class, and also after the pages has loaded perfectly. It will also scroll to the class the very first time after the page loads perfectly, but is erratic behavior after the 1st time.
This is my (messy) jQuery:
$(window).bind("load", function() {
var mainhash = window.location.href.split("#")[1];
$('html, body').animate({
scrollTop: $('#'+mainhash).offset().top
}, 900, 'swing');
$('a[href^="#"]').bind('click',function() {
var target = this.hash; //target is whole #hash
var whatever = '.pics .'+this.hash.split("#")[1];
$whatever = $(whatever);
$target = $(target); //$target is $(#hash)
$('.pics').animate({
scrollLeft: $whatever.offset().left
}, 900, 'swing');
$('html, body').stop().animate({
scrollTop: $target.offset().top
}, 900, 'swing');
window.location.hash = target; //target is whole #hash
});
});
Any expertise explaining what I am doing wrong would be greatly appreciated! Additionally, I could change the way I am scrolling to the elements if it is recommended. The class/ID/hash was just the best I could come up with. Many thanks all!
To trigger the horizontal scroll on load all you need to do is trigger a click on the element with the id equal to 'mainhash'. You could achieve this by adding this line at the end of your 'load' handler:
$('#'+mainhash).trigger('click');
As for the erratic scrolling, well, it's a little complicated. $whatever's offset().left is $whatever's distance from the left side of the window, not its distance from the left side of .pics. When .pics .scrollLeft() is 0 (ie., when '1900' is flush to the left) then your animation will work correctly, otherwise it won't. I think the solution is to add the .pics .scrollLeft() amount to $whatever's offset().left so that you will have the value of $whatever's offset from the left side of .pics:
scrollLeft: ($('.pics').scrollLeft() + $whatever.offset().left)
Also, I think the 200% widths you have on #picswrap and .pics are wreaking havoc, though I am unable to explain precisely why. I think they should be changed to 100%.

jQuery - Slide to id .stop(); equivalent

I have this code for sliding down to each section on the page. The nav link has an id which links to the corresponding class. This works perfectly except if you click a nav button and then quicky click another it will continue to play out the animation. This isn't too bad.. but if you're mashing the buttons it really freaks out.
I tried using .stop(); but as expected, this stops the animation all together and jumps to the section. Ideally I wish it to go to stop animating wherever it is and continue to the selected section.
I have NO idea how to do this, so jQuery wizards please help!
JSFiddle
$('.nav-item').on('click',function(e){
var scrollSpeed = 1000;
var scrollTop = $(window).scrollTop();
var id = $(this).attr('id');
var goTo = $('div.'+ id).offset().top;
e.preventDefault();
$("html, body").animate({ scrollTop: goTo }, scrollSpeed);
});
just use stop as you have said before
$("html, body").stop().animate({ scrollTop: goTo },
http://jsfiddle.net/XRGkd/

Categories

Resources