Question

So i have this tooltip that changes position on the mousemove event. It's working fine but I want that when it reaches the right corner, the tooltip either gets hidden or snaps to the right side. Sample: http://jsfiddle.net/bortao/qN3RP/

Of course i can take the parent element's width, check if it's greater and limit to it, but this overloads the code a bit.

I also could set body's overflow: hidden, but I can't because there are other elements that i want to scroll.

Is there other way out? Something like a max-right.

Was it helpful?

Solution 2

DEMO

jQuery

var _offset;
$(document).on("mousemove", function (e) {
    if (!_offset) _offset = $("body").offset();



    var calc = e.pageX;
    var getWidth = $('body').width() - $("#help").width();
    $("#help").show();


    if (calc > getWidth) {           
        $("#help").css({
            right: (e.pageX - _offset.right) + "px",
            top: (e.pageY - _offset.top + 25) + "px"

        });
    } else {
        $("#help").css({
            left: (e.pageX - _offset.left + 10) + "px",
            top: (e.pageY - _offset.top + 25) + "px",
            right: "auto"
        });
    }


})
  • can be adjusted as per dynamic width of document

  • on body body{overflow:hidden;} overflow hidden is added so scroll bar wont affect position of tooltip

Hope it helps!

OTHER TIPS

hi U can use following code it works fine

<html>
<head>
<script src="jquery-1.10.2.js"></script>
<style>
#help {
    white-space: nowrap;
    position: absolute;
    background: yellow;
    color: #111;
    padding: 4px 4px 2px 4px;
}

</style>
<script>
var _offset;
$(document).ready(function(){
$(document).on("mousemove", function (e) {
    if (!_offset) _offset = $("body").offset();
    $("#help").show();
    $("#help").css({
        left: (e.pageX - _offset.left + 10) + "px",
        top: (e.pageY - _offset.top + 25) + "px"
    });


    if((e.pageX - _offset.left + 10)>(window.screen.availWidth-50))
    {
        //you can change the position or hide
            $("#help").css({
            left: (e.pageX - _offset.left - 120) + "px",
            top: (e.pageY - _offset.top + 25) + "px"
        });
            //$("#help").hide();
    }
    else
    {

        $("#help").show();
    }

});
});
</script>
</head>
<body>
<div id="help">This is some help</div>
</body>
</html>

You can use something like this:

var _offset;
$(document).on("mousemove", function (e) {
    if (!_offset) _offset = $("body").offset();
    $("#help").show();
    $("#help").css({

        left: (e.pageX - _offset.left) > 400 ? '400px' : (e.pageX - _offset.left + 10) + "px" ,
        top: (e.pageY - _offset.top + 25) > 400 ?  '400px' : (e.pageY - _offset.top + 25) + "px"
    });
})

increase/decrease the value of 400 to your desired value.

fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top