views:

330

answers:

3

I have 2 divs, one positioned absolutely right: 0 and the other relatively positioned center screen. When the window's width is too small, they overlap. How can I invoke a javascript function when this happens?

Thanks. Mike

Edited to make clearer.

+1  A: 

Part 1:

Do it like this:

<script type="text/javascript">
document.getElementById('example').style.display = "inline";
</script>

...

<div id="example"> ... </div>
Eric
Excellent. It's actually an image that I'm showing, but I didn't make that clear. Only thing left to do is figure out how to detect the div overlapping.
Mike
I would personally go for ...display='inline-block' instead of inline as it will still avoid the overlap, but will also keep more of the other CSS attributes it already has.
wheresrhys
A: 
document.getElementById('div_id').style.display = 'inline-block'

document.getElementById('div_id').offsetWidth gives us width of div

offsetHeight, offsetLeft, offsetTop are useful also.

Sergey Kovalenko
+1  A: 

To check for overlapping div's you might wanna do a check once the page is loaded, and whenever the window is resized:

window.onload = checkOverlap;
window.onresize = checkOverlap;

And then use some offset-checking:

function checkOverlap() {
   var centerBox = document.getElementById('centerDiv');
   var rightBox = document.getElementById('rightDiv');
   console.log("centerbox offset left: " + centerBox.offsetLeft);
   console.log("centerbox width: " + centerBox.offsetWidth);
   console.log("rightbox offset left: " + rightBox.offsetLeft);
   if ((centerBox.offsetLeft + centerBox.offsetWidth) >= rightBox.offsetLeft) {
      centerBox.style.display = "inline-block";
   } else {
      centerBox.style.display = "block";
   }
}

You might wanna do some more checks in the function, e.g. to see if the box is already displayed inline, and such. But that should give you a good place to start.

edit: added some diagnostics and fixed error

peirix
It's a great place to start! However, it isn't working yet. I'd like to diagnose it. How can I use alert to show me the value of, for example, centerBox.offsetLeft?
Mike
My bad, the comparison was wrong. Tested and works (:
peirix
My console gives me: "TypeError: Result of expression 'centerBox' [null] is not an object." Any ideas? Thanks again.
Mike
Which line produces this error?
peirix
console.log("centerBox offset left: " + centerBox.offsetLeft);Also, a bit more info for you: I am using width: auto for both divs.
Mike
try adding `console.log("centerBox: " + centerBox);` before the other log-statements. It should give you `[object HTMLDivElement]`, if it doesn't, there's something wrong with the `getElementById()`-statement.
peirix
It just says centerBox: null
Mike
That means you're using the wrong selector. Can you paste your HTML into the question area? Just the HTML for the two divs, with class names and ids
peirix