Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - If I'm moving a div with the keyboard

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?

like image 838
Barrie Reader Avatar asked Jul 15 '10 20:07

Barrie Reader


2 Answers

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});

like image 53
Mark Avatar answered Nov 01 '22 10:11

Mark


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);
});
like image 20
jAndy Avatar answered Nov 01 '22 10:11

jAndy