views:

101

answers:

3

Yo!

If I have a div with a fixed height and width, which I am moving using keypress (or keydown/keyup). Can I get the window to "follow" that div?

I know you can auto scroll a page, but can you get the co-ordinates of a div and scroll the page as the div moves?

Cheers :)

A: 

are you using a javascript framework? If you use jQuery you can get the position of the div using:

jQuery('#yourdiv').position().top()
jQuery('#yourdiv').position().left()

Also, if you use jQuery, the window will automatically scroll to keep the Div in view anyway with no further work from you.

In response to your comment:

You can use jQuery('body').animate({scrollTop:xPosOfDiv});

Mark
Ah, excellent - would there be a way to scroll the page to that position? I suspect itll be .scroll() actually...
Neurofluxation
No offense, but the title and the tags are stating that he uses JQuery. ;)
Bobby
Nevermind - GOT IT! Cheers! - Ill accept in 6 minutes
Neurofluxation
My mistake, didn't see the jQuery tag. =)
Mark
@Neurofluxation - `$(window).scrollTop()`. I would also recommend using `.offset()` instead of `.position()`, as `.offset()` will give you the position relative to the document.
Michal
A: 
var pos = $("#theDiv").position();
window.scrollTo(pos.left, pos.top);
Josh Stodola
Note that `scrollTo` requires the scrollTo plugin: http://plugins.jquery.com/project/ScrollTo
kingjeffrey
@kingjeffey No, I am not using any plugins. I am using the native Javascript method: https://developer.mozilla.org/en/DOM/window.scrollTo
Josh Stodola
+1  A: 

One way:

$(document.body).bind('keydown', function(){
    $('#somediv')[0].scrollIntoView(true);
});

Another way:

$(document.body).bind('keydown', function(){
    $('#somediv').css('top', $(window).scrollTop() + 'px');
});

Smooth way:

$(document.body).bind('keydown', function(){
    $('#somediv').animate({'top': $(window).scrollTop() + 'px'}, 1000);
});
jAndy
Was going to suggest this too - only thing to look out for is that sometimes the IE6/7 renderer gets confused by `scrollIntoView` and breaks the layout. However it definitely works *most* of the time.
Pointy