CuriousDev
CuriousDev

Reputation: 1275

ScrollTop does not work

When the page loads, I am trying to scroll header 3 upwards. Basically Header 3 should be displayed at the top most position on the page.

I am using this:

$(function(){
 $('body').animate({
     scrollTop: $(":header3").offset().top
}, 500);
});

Similarly if I use Header 4, the scroller should come down and Header 4 should be displayed at the top most position on the page.

However the scroll does not happen. Not sure why?

here's a fiddle http://jsfiddle.net/xdaf7o3b/

Upvotes: 1

Views: 120

Answers (5)

sifriday
sifriday

Reputation: 4462

If you want to scroll to the third header of any sort (h1, h2, h3, h4, etc) on the page, try the :eq selector:

$(function(){
 $('body').animate({
    scrollTop: $(":header:eq(2)").offset().top
}, 500);
});

Here's a fiddle: http://jsfiddle.net/sifriday/xdaf7o3b/5/

And to ensure there is enough space in the document to correctly scroll the viewport right to the header you want, you can do some measurement and add padding to the containing div, if required:

var wh = $(window).height();
var dh = $(document).height();
var top = $(":header:eq(2)").offset().top
if ((dh - top) < wh) {
    $("#someDiv").css("padding-bottom", (wh - (dh - top)) + "px")
}

demo here: http://jsfiddle.net/sifriday/xdaf7o3b/6/

A good test for this is to try it on the 4th header of the page, demoed here: http://jsfiddle.net/sifriday/xdaf7o3b/7/

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

AFAIK there is no such selector as :header3. You can use :header:eq(2) instead. Or simply h3.

$(function(){
 $('body,html').animate({
     scrollTop: $(":header:eq(2)").offset().top
}, 800);
});

Demo.

Upvotes: 0

Saqueib
Saqueib

Reputation: 3520

Use html body selector

$(function(){
 $('html, body').animate({
     scrollTop: $("h3").offset().top
   }, 800);
});

here is working fiddle

Upvotes: 0

prog1011
prog1011

Reputation: 3495

Use below Code

$(function(){
 $('body').animate({
     scrollTop: $("h3").offset().top
}, 800);
});

Upvotes: 0

rishiAgar
rishiAgar

Reputation: 168

Replace of :header3 use h3

$(function(){
    $('body').animate({
        scrollTop: $("h3").offset().top
    }, 500);
});

Updated JsFiddle

Upvotes: 0

Related Questions