Alex Rivera | Logout

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

Asked 2010-06-10T18:11:36.653
10

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>
Edit
Report

1 Answer

1

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.

answered 2010-06-10T21:12:46.490

Your Answer