1

I'm creating a split page with a menu on the left, and the main content on the right. When I click on a menu item, I want to scroll the main content to that item.

I found JavaScript scrollTo(), which takes offset arguments.

Is there any way to determine the offset of a particular <p> or other element within a <div>? Or perhaps there is another way to scroll to an element without knowing its offset?

EDIT

Thanks for the replies. Looks like everyone gave similar answers. However, I ran into a problems with this. It seems that offset().top (or position().top) return different values depending on the current scroll position.

My jsFiddle is here: http://jsfiddle.net/gBTW9/4/embedded/result/

If I scroll to the top and selection Section 4, it works as expected. But once I've scrolled, it stops working correctly. Can anyone see what is happening.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

5 Answers5

1

You can get the vertical offset of an element using $('p').offset().top. You can combine this with scrollTop() using this:

$('div').scrollTop($('p').offset().top);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

You need to use position() rather than offset(). If you know the id of that

you can easily find the position of that paragraph tag

jQuery: Difference between position() and offset()

Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

There are jquery methods offset and position stat can help there.

Also there is good scrollTo plugin which accepts elements and much more.

antejan
  • 2,594
  • 12
  • 15
1

If i didn't misunderstood you just need an animated scrolling to a particular element, something similar on what I did on my portfolio.

Assuming that the menu on the left is fixed, then just scroll the page to the element you want to scroll to:

$("html, body").animate({
   scrollTop: $('#element').offset().top 
});

If you need to move a particular element over another element then:

$("#element1").animate({
   top: $('#element2').offset().top 
});
MacK
  • 2,132
  • 21
  • 29
1

Why try it the hard way, when you can use a HTML native attribute??

call me old school, but i like to keep it simple.

within your menu:

use:

<ul>
    <li>
        <a href="#Paragraph1">Paragraph 1</a>
    </li>
</ul>

instead of

<ul>
    <li>Paragraph 1</li>
</ul>

this will make your section jump to the # (id) that equals Paragraph1

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
Ilinea
  • 62
  • 6