user1856596
user1856596

Reputation: 7233

JavaScript: How to figure out, if a div is on the middle of the screen?

Is there an easy way to figure out if a certain div is on the middle of the screen? I tried http://www.appelsiini.net/projects/viewport but it needs extra code as well. By middle I mean centered vertically and horizontally.

Isnt there an easier way to figure this out?

Thanks!

Upvotes: 0

Views: 98

Answers (1)

Michael Kunst
Michael Kunst

Reputation: 2988

jQuery solution:

var offsetLeft = $('#whatever').offset().left;
var offsetRight = ($(window).width() - (offsetLeft + $('#whatever').outerWidth()));
var isInMiddle = offsetLeft == offsetRight;

Edit: If you want not only want to check if it's centered vertically, do the same also for the offsetTop and bottom

Upvotes: 1

Related Questions