How to check if the tool image is off the screen


how to check if the tooltip image is out of the screen. i want if the image is out of the screen then the tooltip image should be of left side or right side, it should not go out of the screenand make scroll bar. here is the jquery code.

 this.imagePreview = function(){
/* CONFIG */

    xOffset = 10;
    yOffset = 30;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result

    this.t = this.title;
    this.title = "";
    var c = (this.t != "") ? "<br/>" + this.t : "";
    $("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px")
    this.title = this.t;
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px");

  // starting the script on page load

here is the demo code. . note its show scroll when tooltip goes out of screen. i want tooltip should change position to right if it detect end of page in x position.

If you use jQuery UI's position function, you can define what should happen on collisions:

From the documentation:

collision (default: "flip")

Type: String When the positioned element overflows the window in some direction, move it to an alternative position. Similar to my and at, this accepts a single value or a pair for horizontal/vertical, e.g., "flip", "fit", "fit flip", "fit none".

"flip": Flips the element to the opposite side of the target and the collision detection is run again to see if it will fit. Whichever side allows more of the element to be visible will be used.

"fit": Shift the element away from the edge of the window.

"flipfit": First applies the flip logic, placing the element on whichever side allows more of the element to be visible. Then the fit logic is applied to ensure as much of the element is visible as possible.

"none": Does not apply any collision detection.