Reputation: 19664
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!
Upvotes: 1
Views: 8503
Reputation: 19664
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;
Upvotes: 0
Reputation: 439
Had similar issues but the jQuery's scrollTo plugin saved my life.
Upvotes: 0
Reputation: 667
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();
Upvotes: 3
Reputation: 40052
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.
Upvotes: 0
Reputation: 41823
You should be using scrollTop
instead of offset
since your goal is attempting to scroll the window.
Upvotes: 1