Search code examples
javascriptjqueryjquery-pluginsscrolltopscrollto

jQuery scrollTop Not Triggering


I have some markup like so:

<div id="landing">
    <p>Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin.</p>
</div>

<header id="header">
    <p>Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin.</p>
    <p>Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin.</p>
    <p>Ut in nulla enim. Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum feugiat nisl ut dapibus. Mauris iaculis porttitor posuere. Praesent id metus massa, ut blandit odio. Proin.</p>
</header>

And I'm trying to get it so that, when the <p> element in #landing is clicked, jQuery scrolls the page down to the #header element.

Going by the jQuery docs, I would have assumed it would be as simple as:

$('#landing p').click(function() {
    $('#header').scrollTop(250);
});

But that doesn't appear to work at all. Plus, every other thread I look at (including some answers to my previous / similar threads) that uses the scrollTop method seems to use more complex code. So then I thought maybe I need to have something like this:

$('#landing p').bind('click', function(e) {
    try {
        e.preventDefault();
        target = this.hash;
        $('#header').animate({
            scrollTop: 0
        }, 150);
    } catch (error) {
        alert('error - ' + error);
    }
});

Yet that doesn't work either. I get no error messages in the console but the event just won't seem to trigger. I've tested it with a simple alert statement which works fine, just I can't get it to scroll


Solution

  • I think you might be looking for something like this?

    $('#landing p').click(function(){
        var headerOffset=$('#header').offset();
        $('html,body').animate({
            scrollTop:headerOffset.top
        });
    });