Search code examples
jquerycssviewvisibilityvisible

How do I use jQuery to determine when a div is out of view to the right?


I have a div that displays near a control when it's focused on. Initially, the div was on the left of the control, and life was easy. A simple if left < 0 { left = 0; } would keep the div on the screen. Now the div needs to be on the right, and I can't figure out a similar bit of code. Also, the code needs to determine not only if it's off-screen to the right, but also if it's past the visibility of a (possible) scrollable containing div. How can I accomplish this? Assume the scrollable div, if applicable, can be found with $('.PanelScroll') and we can call the div needing placement elem.


Solution

  • This is more of the simple solution I was looking for:

    var ctrl = $('#<your control id>');         // This is the control that the div is display to the right of.
    var elem = $('#<your element id>');         // This is the div that may be out of view.
    var panel = $('#<your scrollable div id>');
    var left = elem.position().left;
    var right = left + elem.outerWidth();
    
    if ((panel.length && (right > panel.innerWidth())) || (right > ($(window).width() + $(window).scrollLeft()))) {
        left = left - ctrl.outerWidth() - elem.outerWidth();
    }
    
    if (panel.length) {
        left += panel.scrollLeft();
    }
    
    elem.css('left', left);