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
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();
See Measuring Element Dimension and Location for help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With