Search code examples
javascriptprototypejs

How to know when an element will be off screen?


I am writing a simple script that displays a dialog box when a user hovers over a profile picture. It dynamically determines the profile pics location on the page and then places itself to the left of it and about 100px above it. This part is working fine.

My issue arises when a profile pic is at the top of the screen and a user mouses over it. The dialog will appear but the top portion of it will be above the fold (i.e. not in the current browser window). Naturally this is not good usability and I would like it to appear on the screen.

My question is how do I know when a dialog will be off screen so I can recalculate its position on the page?

I saw this question which seems like the same as mine but unfortunately no actual solution was provided other then to link to a jQuery plugin. I am using Prototype.


Solution

  • Prototype already provides positions with Element.viewportOffset().

    Edit, as Mathew points out document.viewport gives the rest of the information. For example,

    var dialogtop = dialog.viewportOffset().top;
    if (dialogtop < 0) {
        // above top of screen
    }
    elseif (dialogtop + dialog.getHeight > document.viewport.getHeight()) {
        // below bottom of screen
    }