Łukasz Baran
Łukasz Baran

Reputation: 1239

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?

Upvotes: 2

Views: 4946

Answers (2)

Niklas
Niklas

Reputation: 30002

Use Math.max() and Math.min() which selects the higher/lower value of the variables provided, like this:

var pos = $(this).offset();
        var width = $(this).width();
        userPreviewCon.css({
            left: Math.min((Math.max(0,pos.left + 30)+$(this).width(),$(window).width()) + 'px',
            top: Math.min(Math.max(0,pos.top + 15)+$(this).height(),$(window).height()) + 'px'
        }).fadeIn();

So if the calculated value is > 0 then 0 is the higher value and will be selected if it is trying to go out of bounds on the left. Likewise, if the x+width>window.width(), the lower value, i.e. window.width() will be used on the right side.

Upvotes: 1

MoarCodePlz
MoarCodePlz

Reputation: 5176

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.

Upvotes: 5

Related Questions