Setting the height of a DIV dynamically - javascript

In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.
I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.
My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?
Edit:
The DIV houses a control that does it's own overflow handling (implements its own scroll bar).

Try this simple, specific function:
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
It does not depend on the current distance from the top of the body being specified (in case your 300px changes).
EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.

What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:
div {
position: absolute;
top: 300px;
bottom: 0px;
left: 30px;
right: 30px;
}
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto; to handle cases where the content is larger than the div.
Edit: #Whoever marked this down, an explanation would be nice... Is something wrong with the answer?

document.getElementById('myDiv').style.height = 500;
This is the very basic JS code required to adjust the height of your object dynamically. I just did this very thing where I had some auto height property, but when I add some content via XMLHttpRequest I needed to resize my parent div and this offsetheight property did the trick in IE6/7 and FF3

If I understand what you're asking, this should do the trick:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use
// window.innerWidth and window.innerHeight
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("yourDiv").height = windowHeight - 300 + "px";

With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}

Simplest I could come up...
function resizeResizeableHeight() {
$('.resizableHeight').each( function() {
$(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
});
}
Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).

inspired by #jason-bunting, same thing for either height or width:
function resizeElementDimension(element, doHeight) {
dim = (doHeight ? 'Height' : 'Width')
ref = (doHeight ? 'Top' : 'Left')
var x = 0;
var body = window.document.body;
if(window['inner' + dim])
x = window['inner' + dim]
else if (body.parentElement['client' + dim])
x = body.parentElement['client' + dim]
else if (body && body['client' + dim])
x = body['client' + dim]
element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + "px");
}

Related

JavaScript calculate with viewport width/height

I am trying to set a responsive point in my mobile Webview and did this:
var w = window.innerWidth-40;
var h = window.innerHeight-100;
This works great so far. But the values -40 and -100 are not in the viewport scaling height and width.
When I do this:
var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;
as it should be to stay responsive and relative to the viewport - the JS does not work anymore.
I think vh and vw works only in CSS ?
How can I achieve this in JS ?
Pleas no JQuery solutions - only JS!
Thanks
Based on this site you can use the following util functions to calculate your desired values as a function of a percent of screen width or height:
function vh(percent) {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
return (percent * h) / 100;
}
function vw(percent) {
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return (percent * w) / 100;
}
function vmin(percent) {
return Math.min(vh(percent), vw(percent));
}
function vmax(percent) {
return Math.max(vh(percent), vw(percent));
}
console.info(vh(20), Math.max(document.documentElement.clientHeight, window.innerHeight || 0));
console.info(vw(30), Math.max(document.documentElement.clientWidth, window.innerWidth || 0));
console.info(vmin(20));
console.info(vmax(20));
I used this incredible question in my code!
Try this:
function getViewport() {
var viewPortWidth;
var viewPortHeight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth,
viewPortHeight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewPortWidth = document.documentElement.clientWidth,
viewPortHeight = document.documentElement.clientHeight
}
// older versions of IE
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
}
return [viewPortWidth, viewPortHeight];
}
Reference: http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
Problem is that JS does not have 40vh, calculate how much pixels is 40vh first to use it. It will throw error when doing 1000 - 40vh
40vh means 40 % of viewport height. So window.innerHeight * 0.4 == 40vh
Also there is no such thing as wh, only vh (% of viewport height)
The simplest way to do this, if you can fully edit the page, is to make a css class that has -40vw and -100vh like so:
CSS:
.class{
width: -40vw;
height: -100vh;
}
JS:
element.classList.add("class");
Note: "classList" is not supported in Internet Explorer 9. If you want it to work in all browsers, use this for JS instead:
function myFunction() {
var element, name, arr;
element = document.getElementById("myDIV");
name = "mystyle";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
element.className += " " + name;
}
}
you just need to surround it in quotes I think.
var w = window.innerWidth = "40vw"
var w = window.innerWidth = "40vw"
this is my solve with you can use CSS;
// calc dynamic customer device height/width
let vh = window.innerHeight * 0.01,
vw = window.innerWidth * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
document.documentElement.style.setProperty('--vw', `${vw}px`);
How to use in CSS ?
If you will use 100vh or 100vw with this method, you should set 100vh/100vw for uncompatible browser.
Examples;
.wrapper{
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
.slide-container{
height: calc(var(--vh, 1vh) * 100 - var(--menuHeight) - var(--footerHeight));
}
.little-image{
width: calc(var(--vw, 1vw) * 5);
margin-bottom: calc(var(--vh, 1vh) * 1);
}
/* and more.. */
This isn't a universal solution, but it's a much simpler implementation if you're working with a page that is always 100% displayed within the viewport (ie, if the body doesn't have to be scrolled and always matches the window width and height).
let vh = document.body.getBoundingClientRect().height;
This sets the vh variable to the pixel value of the document body with just one line of code.
Useful for game dev and other scenarios where you have the body affixed to the viewport.
get vmin in px
function vmin(){
return window.innerHeight < window.innerWidth ? window.innerHeight: window.innerWidth;
}

Get css equivalent of "max-width: 600px" using JavaScript

This is a followup question to this quetsion: Get the device width in javascript.
What I'm trying to do, is get the equivalent css of #media (max-width: 600px) in JavaScript.
The accepted answer says to do the following:
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
Is that still correct? Will it work for all devices?
If it's correct, what's the point of checking (window.innerWidth > 0)?
I want to know if it still works. If you look at the last comment on the answer (with 6 upvotes) it says:
How does this have so many upvotes? var width = (window.innerWidth >
0) ? window.innerWidth : screen.width; returns 667 on iphone 6 AND 6
Plus. This solution does not work correctly.
You should be able to do something like this:
if (matchMedia) {
var mq = window.matchMedia("(max-width: 600px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
function WidthChange(mq) {
if (mq.matches) {
//Window width is less than or equal to 600px
} else {
//Window width is greater than 600px
}
}
From your question it seems you are asking for the following (It is a trivial answer but I assume this is what you are asking):
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
is equivalent to:
var width;
if (window.innerWidth > 0)
{
width = window.innerWidth;
}
else
{
width = screen.width;
}
or:
var width = screen.width;
if (window.innerWidth > 0)
{
width = window.innerWidth;
}
they all do the same thing...
from your comment below you may want the following jsFiddle:
(which shows "window.innerWidth" is what you want (size of containing element) - but some browsers don't support it - so "screen.width" becomes the fallback which may not be correct as it is the width of the whole window and not just the containing element)
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
$('#divOutput').html('The width is:' + width + 'px <br>' +
'window.innerWidth = ' + window.innerWidth + 'px & <br>' +
'screen.width = ' + screen.width + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOutput"></div>
if that doesn't help maybe look at:
window.innerWidth can't work on IE7. How to fix via JS and jQuery?

How to check if an element is in the view of the user with jquery

I have a very big draggable div in my window. This div has a smaller window.
<div id="draggable-area" style="width:500px;height:500px;overflow:hidden">
<div id="draggable" style="width:5000px;height:5000px">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
....
</ul>
</div>
</div>
How can I know if the li element is visible in the user viewport (I mean really visible, not in the overflow area)?
To check if an element is in the current veiwport:
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
(top + height) <= (window.pageYOffset + window.innerHeight) &&
(left + width) <= (window.pageXOffset + window.innerWidth)
);
}
(Source)
For a more robust method, I'd recommend Viewport Selectors, which allow you to just do:
$("#elem:in-viewport")
have a look at this plugin
It give's you the option to do the following selectors
$(":in-viewport")
$(":below-the-fold")
$(":above-the-top")
$(":left-of-screen")
$(":right-of-screen")
https://github.com/sakabako/scrollMonitor
var scrollMonitor = require("./scrollMonitor"); // if you're not using require, you can use the scrollMonitor global.
var myElement = document.getElementById("itemToWatch");
var elementWatcher = scrollMonitor.create( myElement );
elementWatcher.enterViewport(function() {
console.log( 'I have entered the viewport' );
});
elementWatcher.exitViewport(function() {
console.log( 'I have left the viewport' );
});
elementWatcher.isInViewport - true if any part of the element is visible, false if not.
elementWatcher.isFullyInViewport - true if the entire element is visible [1].
elementWatcher.isAboveViewport - true if any part of the element is above the viewport.
elementWatcher.isBelowViewport - true if any part of the element is below the viewport.
For a more up-to-date way using getBoundingClientRect():
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
Returns true if the element in completely in the viewport, and false if it’s not.
var myElem = document.querySelector('#draggable');
if (isInViewport(myElem)) {
// Do something...
}
Complete explanation found here.
My solution is using the given code example, and it will show you an overall idea of how to determine whether the li element is visible. Check out the jsFiddle which contains code from your question.
The jQuery .offset() method allows us to retrieve the current position of an element relative to the document. If you click on an li element inside the draggable, your offset from the top will be between 0 and 500 and the offset from the left should be between 0 and 500. If you call the offset function of an item that is not currently visible, the offset will either be less than 0 or greater than 500 from either the top or left offset.
If its not a daunting task I always like to code what I need from 'scrath' it gives me more flexibility when having to modify or debug, hence why I would recommend looking into using jQuery's offset function instead of using a plugin. If what you are trying to accomplish is fairly simple, using your own function will give you one less library to load.
I m using (checks whether an element is at least partially in the view) following code:
var winSize;
function getWindowSize() {
var winW,WinH = 0;
if (document.body && document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
if (document.compatMode == 'CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth) {
winW = document.documentElement.offsetWidth;
winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
winW = window.innerWidth;
winH = window.innerHeight;
}
return {w:winW, h:winH};
}
winSize = getWindowSize();
function inView(element) {
var box = element.getBoundingClientRect();
if ((box.bottom < 0) || (box.top > winSize.h)){
return false;
}
return true;
}

Check if element is visible on screen [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jQuery - Check if element is visible after scroling
I'm trying to determine if an element is visible on screen. In order to to this, I'm trying to find the element's vertical position using offsetTop, but the value returned is not correct. In this case, the element is not visible unless you scroll down. But despite of this, offsetTop returns a value of 618 when my screen height is 703, so according to offsetTop the element should be visible.
The code I'm using looks like this:
function posY(obj)
{
var curtop = 0;
if( obj.offsetParent )
{
while(1)
{
curtop += obj.offsetTop;
if( !obj.offsetParent )
{
break;
}
obj = obj.offsetParent;
}
} else if( obj.y )
{
curtop += obj.y;
}
return curtop;
}
Thank you in advance!
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Intersection Observer
In modern browsers you can use the IntersectionObserver which detects where an element is on the screen or compared to a parent.
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.
Today I would probably lean toward this API if I need to detect and react to when an element has entered or exited the screen.
But for a quick test/lookup when you just want to verify if an emelemt is currently on screen I would go with the version just below using the getBoundingClientRect.
Using getBoundingClientRect
Short version
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
Longer version
And a version with threshold and mode included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
A more traditional way to do it
As BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
Could you use jQuery, since it's cross-browser compatible?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };

How do I constrain the size of a tooltip/popup-style DIV so that it doesn't trigger scrollbars on the page

The mouse hovers over an element and a tip appears. The tip overflows the page, triggering a scrollbar, which changes the layout just enough so that the underlying element that triggered the tip is no longer under the mouse pointer, so the tip goes away.
The tip goes away, so the scrollbar goes away, and now the mouse is again over the element.
Wash, rinse, repeat.
If I could make sure that tip isn't too big so as to trigger scrollbars, that would solve my problem.
EDIT: After reading comments, some things to clarify:
The div contains text which can vary. If I can, I want to show all the text. The div's location needs to be near the element the mouse's tip is over. So the key is, I need to know whether to truncate the text.
I did find this link:
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
which contains this piece of the puzzle, figuring out how big the browser window is:
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
CSS : specify the tooltip's width and height, add overflow: hidden or overflow: scroll to it.
position: absolute works fine too, but of course, then you'll have to specify the top and left position of the tooltip.
edit: in response to the comments, it sounds like you're trying to have the tooltip appear, without affecting the positioning of existing elements (and thus causing the scrollbar on the main window).
if that's the case, you want to define your tooltip's position as absolute, as this will remove it from the flow of elements (so when it appears it won't push the rest of the page down).
for example, you could start it hidden:
#tooltip {
position: absolute;
height: 100px;
width: 200px;
border: 1px solid #444444;
background-color: #EEEEEE;
display: none;
}
then, on your mouseover event (or whatever it's called on), set the top and left css of the #tooltip to where ever you want it, and switch the display to block. as it's positioned absolutely, it won't cause the flicker.
you can use a hidden DIV positioned at 0,0 with width and height set to 100% as a 'yardstick' to measure the client area of the screen
if you know the size of your tooltip window, you can clip it to the client window, or change the display position to shift it so that it stays within the boundaries
some code below (untested, ripped from another project and renamed inline)
var toolTipDiv; //this is your tooltip div element
//call AdjustToolTipPosition(window.event);
function AdjustToolTipPosition(e)
{
var cpos = getPosition(e);
mouseX = cpos.x;
mouseY = cpos.y;
//Depending on IE/Firefox, find out what
//object to use to find mouse position
toolTipDiv.style.visibility = "visible";
//backdrop 'yardstick' for client area measurement
var backdropDiv = document.getElementById("divBackdrop");
//make sure floating box doesn't leave the screen
//we know box is 200x200 plus margins, say 215x215
if ((cpos.y + 215) > backdropDiv.offsetHeight)
{
cpos.y = backdropDiv.offsetHeight - 215;
}
if ((cpos.x + 215) > backdropDiv.offsetWidth)
{
cpos.x = backdropDiv.offsetWidth - 215;
}
toolTipDiv.style.left = cpos.x + "px";
toolTipDiv.style.top = cpos.y + "px";
}
//this function courtesy of
//http://hartshorne.ca/2006/01/23/javascript_cursor_position/
function getPosition(e)
{
e = e || window.event;
var cursor = {x:0, y:0};
if (e.pageX || e.pageY)
{
cursor.x = e.pageX;
cursor.y = e.pageY;
}
else
{
var de = document.documentElement;
var b = document.body;
cursor.x = e.clientX +
(de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
cursor.y = e.clientY +
(de.scrollTop || b.scrollTop) - (de.clientTop || 0);
}
return cursor;
}
Here is the code that I ended up using, and it seems to be working.
function display_popup(s)
{
var popup = document.getElementById("popup");
popup.innerHTML = s
//viewport_height = $(document).height() doesn't work
viewport_height = get_viewport_size()[1] // does this factor in scrollbar?
mytop = $(current_element).offset().top + $(current_element).height() + 4
scroll_offset_y = $(document).scrollTop()
y_in_viewport = mytop - scroll_offset_y
if (y_in_viewport < viewport_height) // are we even visible?
{
// Display the popup, but truncate it if it overflows
// to prevent scrollbar, which shifts element under mouse
// which leads to flicker...
popup.style.height= ""
popup.style.display = "block";
if (y_in_viewport + popup.offsetHeight > viewport_height)
{
overflow = (y_in_viewport + popup.offsetHeight) - viewport_height
newh = popup.offsetHeight - overflow
newh -= 10 // not sure why i need the margin..
if (newh > 0)
{
popup.style.height = newh
}
else
{
popup.style.display = "none";
}
}
popup.style.left = $(current_element).offset().left + 40
popup.style.top = mytop
}
}
function get_viewport_size()
{
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' )
{
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
}
else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
{
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return [myWidth, myHeight];
}
Seems to me that what you need is cursor position within the client browser window. Then you can do your calculations to place the tooltip so it doesn't cross the border.
What I found on the web is a short article discussing this in diffrent browsers: Mouse Cursor Position. Maybe this could help you fix your problem?
And some more info about browser size can be found here.
Hope it helps.
It could be possible to setup a ghost transparent DIV exactly of you whole page/viewport size. Then you can 'stick' a tooltip DIV within it, providing CSS float:right attribute. That would give you correct top/left tooltip's corner measures for a final tooltip rendering.
Edit: this should be done only for the case of 'edge situations'.
You could try determining where the pointer is, and if it is in the right 1/4 (or whatever area you determine) of the viewport, put the tool tip on the left of the pointer, otherwise put it to the right.
You mentioned that the text can vary, but is it possible it will grow very large? Could it take up an entire screen itself? Most likely, there is a maximum size it will be, so take that into account when deciding what threshold to use to decide if the tip should be on the right or the left.
Then, absolutely position your tip div, and to be safe, give it a max-height and max-width attribute. If the text does grow larger than that, give it overflow: scroll in the CSS.
I had this same problem earlier this year. The way I fixed it:
I assumed vertical scrolling is ok, but horizonal scrolling is not. (There was always enough room so that the vertical scrollbar didn't affect my layout)
I fixed the relative vertical position of the tooltip with regards to the target. (The top of the tooltip was always 5px below the bottom of the anchor)
The left side of the tooltip was set with regard to the size of the screen. If the whole tooltip could fit on one line, cool. Otherwise, I constrained the max width and made it wrap.
One thing that helped me implement it this was was Quirksmode's Find Position article.
My solution might not be exactly what you're looking for, but at least have a look at the Quirksmode link, its good.
Hope that helps!
A better idea may be to place the tooltip to the left or to the right of the element depending on which side of the page is closer. I have width of my tooltip fixed, fill it with content and make it visible when needed, and then position it depending on mouse position. Here's the key part of onmousemove event handler when tooltip is enabled:
if (!e) var e = window.event;
if(e) {
var posx = 0;
var posy = 0;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
var overflowX = (document.body.clientWidth + document.body.scrollLeft + document.documentElement.scrollLeft) - (posx + 25+ tooltip.clientWidth);
if(overflowX < 0) posx -= 25+ (tooltip.clientWidth);
var overflowY = (document.body.clientHeight + document.body.scrollTop + document.documentElement.scrollTop) - (posy + 15+ tooltip.clientHeight);
if(overflowY < 0) posy += overflowY;
tooltip.style.left=(10+posx);
tooltip.style.top=(10+posy);
}

Categories