1

I am attempting to scroll the window to a location on my page based on a user's selection. I am getting some strange results. Can anyone suggest a good/better way to go about this?

Here is what I'm working with:

 var rel = $(this).attr('rel');
 var citation = rel.split("-")[0];
 window.scrollTo(0, $('[name = ' + citation + ' ]').offset().top);
 alert($('[name = ' + citation + ' ]').offset().top);

The last alert gives me a number that seems wrong and the scrolling is not working. The following code is executed when the user clicks on a link from within the document. I am capturing that element's rel attribute value and (after a little string manipulation) using it to find the position of the corresponding anchor. The destination element's name attribute should match the rel attribute of the clicked link. See what I mean?

Thanks!

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
Nick
  • 19,198
  • 51
  • 185
  • 312

5 Answers5

3

This is another easy oldschool way to scroll to a html element:

// scrolls to the element with id='citation' 

var node = document.getElementById('citation');    
node.scrollIntoView();
port-zero
  • 657
  • 3
  • 7
1

You should be using scrollTop instead of offset since your goal is attempting to scroll the window.

geowa4
  • 40,390
  • 17
  • 88
  • 107
0

This code ought to work:

var rel = $(this).attr('rel');
var citation = rel.split("-")[0];
window.scrollTo(0, $('[name = ' + citation + ' ]').scrollTop());
alert($('[name = ' + citation + ' ]').scrollTop());

I would add, though, that your name selector there isn't guaranteed to be unique, in which case you'd get strange effects. IDs are meant to be unique on a page, name doesn't have to be. Just a tip.

Gabriel Hurley
  • 39,690
  • 13
  • 62
  • 88
0

Had similar issues but the jQuery's scrollTo plugin saved my life.

0

I was able to get around this by not using offset() but by rather using jQuery's position() function.

I am just getting the returned object's "top" property. I have to use the element's text as an index value because these elements did not have unique IDs.

var citationIndex = parseInt($(this).text() - 1);
var elementOffset = $('.HwCitationsContent li:eq(' + citationIndex + ')').position().top;
Nick
  • 19,198
  • 51
  • 185
  • 312