views:

652

answers:

6

Hey,

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!

A: 

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

geowa4
A: 

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
Agreed. I don't have control over content in this document.
Nick
A: 

So I can't change the elements attributes. So I am attempting to solve this another way. The text that the user clicks can be used as and index. Now I am stuck with getting a unique element out of the wrapped set.

The following will return 8:

$('.HwCitationsContent li').length;

However when I try to select a unique object out of the wrapped set.. I get nothing. In fact, the alert box I'm using for debugging won't even appear?? Wha? Can someone help me with that?

alert($('.HwCitationsContent li')[1].offset().top)

It seems that specifying an index value breaks something.

Nick
a) you should have just edited your question instead of posting an answer here. b) why can't you use `scrollTop`? and c) you cant alert what's not defined. `[1]` gets the actualy element, for which `offset()` is not defined.
geowa4
A: 

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
A: 

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

A: 

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