Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position div depending on distance browser edge (javascript)

I am trying to create a small tooltip script that mostly relies on css. The bit of JavaScript I can't figure out is how to position the div based on its distance to the browsers edge.

When the div appears I would like it to check how close it is to the top, bottom, left and right. For example if there is not enough space to display the div above the tooltip link it should position it below the link.

Essentially I would like the div to be "aware" of its position and know where to go to make sure it is visible.

Thanks

like image 983
Cawlin Avatar asked Feb 02 '09 17:02

Cawlin


2 Answers

I just had to write very similar code myself, for use with tipsy (so my solution uses jQuery). Here's the basic math, assuming <div id="mydiv">...</div> is the div you're working with. I account for the div's height and width when measuring the distances to the right and bottom edges as well.

dTop, dBottom, dLeft, and dRight are the distance from the div's top, bottom, left, and right edges, respectively, to the same edge of the viewport. If you want to measure based on the upper-left corner of the div, don't subtract dTop or dLeft when computing dBottom and dRight.

var $doc = $(document),
    $win = $(window),
    $this = $('#mydiv'),
    offset = $this.offset(),
    dTop = offset.top - $doc.scrollTop(),
    dBottom = $win.height() - dTop - $this.height(),
    dLeft = offset.left - $doc.scrollLeft(),
    dRight = $win.width() - dLeft - $this.width();
like image 154
Matt Ball Avatar answered Sep 21 '22 00:09

Matt Ball


See Measuring Element Dimension and Location for help

like image 42
Galwegian Avatar answered Sep 18 '22 00:09

Galwegian