Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force positioned elements to stay withing viewable browser area?

I have a script which inserts "popup" elements into the DOM. It sets their top and left css properties relative to mouse coordinates on a click event. It works great except that the height of these "popup" elements are variable and some of them extend beyond the viewable area of the browser window. I would like to avoid this.

alt text

Here's what I have so far

<script type="text/javascript">
    $(function () {
        $("area").click(function (e) {
            e.preventDefault();

            var offset = $(this).offset();
            var relativeX = e.pageX - offset.left;
            var relativeY = e.pageY - offset.top;

            // 'responseText' is the "popup" HTML fragment
            $.get($(this).attr("href"), function (responseText) {
                $(responseText).css({
                    top: relativeY,
                    left: relativeX
                }).appendTo("#territories");

                // Need to be able to determine
                // viewable area width and height
                // so that I can check if the "popup" 
                // extends beyond.

                $(".popup .close").click(function () {
                    $(this).closest(".popup").remove();
                });
            });
        });
    });
</script>
like image 523
jessegavin Avatar asked Jun 10 '10 18:06

jessegavin


2 Answers

You would compare the window width/height to the window's scrollTop, scrollLeft, etc.

Here are some methods for you to take a look at:

$(window).width()
$(window).height()
$(window).scrollTop()
$(window).scrollLeft()
$(window).scrollWidth()
$(window).scrollHeight()

Take a look at the jQuery documentation on these methods. Depending on exactly the behavior you want, you'll need to compare the width and position of your popup with the currently visible area of the window, determined with the scroll dimensions.

http://api.jquery.com/scrollTop/ .. etc

like image 97
liquidleaf Avatar answered Oct 10 '22 22:10

liquidleaf


I figured out a solution. I added the following code in the place of my 4 line comment in the original question.

var diffY = (popup.offset().top + popup.outerHeight(true)) - $(window).height();
if (diffY > 0) {
  popup.css({ top: relativeY - diffY });
}

var diffX = (popup.offset().left + popup.outerWidth(true)) - $(window).width();
if (diffX > 0) {
  popup.css({ left: relativeX - diffX });
}

@liquidleaf pointed me in the right direction, so +1 and thanks for that.

like image 41
jessegavin Avatar answered Oct 10 '22 22:10

jessegavin