Fabrizio Mazzoni
Fabrizio Mazzoni

Reputation: 1909

Repositioning a div in window if it overlaps

I'm creating div on my page dynamically with jQuery. If the the mouse click position is on the lower part of the screen, the div will display partly off the screen. Basically taking screen 680px, mouse clicked at 600px, div height 300, the lower 220px of the div would be out of the screen as the overflow property is set to hidden.

What I'm trying to achieve is a function that will calculate how much to move it back upwards in order to make sure the div is fully visible.

Unfortunately for me it is not working. Any help appreciated, even an alternate solution via CSS or other.

This function should return the value top in px. Basically it should calculate how much the div exceeds the screen height and remove that from the current mouse position in order to make the div fit.

Javascript:

var mousex;
var mousey;
var currshowingid;
var mousepos;

$( document ).on( "mousemove", function( event ) {
    mousex = event.pageX;
    mousey = event.pageY;
    //console.log( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});

function xfromtop(el) {
    if ((mousey + $(el).height()) > $(window).height()) {
        fromtop = mousey - ((mousey + $(el).height()) - $(window).height())*1.1;
        fromtop = fromtop.toString() + "px";
    } else {
        fromtop = mousey.toString() + "px";
    }
    return fromtop;
}

This will create the div runtime and use xfromtop() to the thetop CSS property

function showdriverdetails(id) {
    $('div[id^="driver_"]').remove();
    // Add div and place in at mouse position 
    $("#main").append("<div class='driverdetails dets' id='driver_" + id + "'>");
    $("#driver_" + id).load("ajax/driver_info.php?id=" + id).fadeIn().draggable();
    $("#driver_" + id).css("top", xfromtop($("#driver_" + id)));
}

CSS:

div.driverdetails {
    width: 70%;
    height: auto;
    min-height: 300px;
    max-height: 400px;
    left: 18%;
}

.dets {
    z-index: 1000;
    position: fixed;
    padding: 2px;
    border: solid #5c6cb0 2.5px;
    background-color: white;
    border-radius: 12px;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    display: none;
}

HTML:

<button onclick="showdriverdetails(100)">SHOW</button>

Upvotes: 0

Views: 52

Answers (1)

Grax32
Grax32

Reputation: 4059

The height property does not account for margin, padding, and border. You should use jQuery's outerHeight to get the full height of your div.

function xfromtop(el) {
    var elHeight = $(el).outerHeight();
    var windowHeight = $(window).height();

    if ((mousey + elHeight) > windowHeight) {
        fromtop = windowHeight - elHeight;
        fromtop = fromtop.toString() + "px";
    } else {
        fromtop = mousey.toString() + "px";
    }
    return fromtop;
}

Upvotes: 1

Related Questions