views:

315

answers:

3

Say I've got a big list of elements which are displayed vertically.

How can you change the window position so that a specified element in the list is shown at the top of the page with javascript?

Does this method work for major browsers (ie 6+, firefox, safari, chrome)?

Thanks

A: 

I'm using jQuery here, but you could easily adapt the logic to any other JS library or even POJ:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4 -- Should move to the top in 5 seconds</li>
    <li>Item 5</li>
</ul>

function changeList(){
    $('li:nth-child(4)').prependTo('ul');
}
$(document).ready(function(){
    var t = setTimeout('changeList()',5000);
});

Demo (make sure to view source)

Note: Updated the code & demo to not use an ID selector and to use setTimeout(), per his request in a comment.

cpharmston
is it possible to do this without the use of '#'? i have a special purpose for # so it can't be replaced. also i'd like to be able to move to the specified list element at some arbitrary time after window load
inktri
cpharmston
+1  A: 
John Kugelman
A: 

You could also use the scrollIntoView function. When you have a reference (say in var el) to the element you want to view simply call el.scrollIntoView (true) to put that element at the top of the window or el.scrollIntoView (false) to put it at the bottom of the window. Unfortunately there is no (easy) mean so centering the element :-(

Hans B PUFAL