Search code examples
jquerypopupwindowpositioning

jQuery: How to check if an element exceeds the browser window's size, and how to reposition it


I have this code:

var pos = $(this).offset();
var width = $(this).width();

userPreviewCon.css({
     left: (pos.left + 30) + 'px',
     top: (pos.top + 15) + 'px'
}).fadeIn();

...which is for positioning a popup window relative to the element that the mouse is pointing.

But when an element is close to the window's border, some of the tooltip is not visible because part of it exceeds the window size. The question is:  how can I reposition the tooltip to no longer exceed the window's border?


Solution

  • To get the width of the window you would do this

    $(window).width();
    

    And then to check and see if this is too far to the side you would (from the looks of what you posted, do this evaluation

    (pos.left + 30) > $(window).width();
    

    And finally, if this evaluation is true, you could do the following

    pos.left -= pos.left + 30 - $(window).width();
    

    And this should make it so that your tooltip box pops up so that its right edge is on the window's right edge.