Search code examples
jquerycsstooltip

Limit element position by CSS


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.


Solution

  • 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!