jQuery: center the viewport on an element

If you have a page that's very long vertically (something that requires a scrollbar) and you want to center the viewport on a specific element do this:

var elem_top = $("#my_item").offset()['top'];
var viewport_height = $(window).height();

// Scroll to the middle of the viewport
var my_scroll = elem_top - (viewport_height / 2);
$(window).scrollTop(my_scroll);


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 44.192.15.251
To prevent spam please submit by clicking the kitten: