jQuery: Get the vertical mid point of the browser's window

Posted in Javascript -

jQuery's $(window).height() and $(window).scrollTop() can be used to calculate the vertical mid point of a browser's window. This quick post shows how to do this and then tomorrow's post will look at vertically centering a Facebox dialog in the middle of the window using this method.

Vertical center of browser with jQuery

It's easy to find the vertical mid point of a window: take the height, divide it by two and add the vertical scroll offset. The first example below does this in one line, assigning it to the "mid" variable:

var mid = $(window).scrollTop() + Math.floor($(window).height() / 2);

If you want to usethe scroll and height values again, are writing a more complex calculation, or simply want to make the code more readable (by removing all the $ symbols and function calls etc) then assign the values to variables first:

var windowHeight = $(window).height();
var scrollTop = $(window).scrollTop();
var mid = scrollTop + Math.floor(windowHeight / 2);

That's all for this post. Stayed tuned for tomorrow when I use a variation of this code to vertically center a Facebox dialog window in the browser window.



Related posts:


Comments