0

Today I was trying to build a tooltip which will show below the mouse pointer and it move along with it. To do this I have written code below. demo

HTML:

<body bgcolor="#4679BD">
   <div class="pointer_tooltip"> 
      Hi am a crazy tooltip
   </div>
</body>

CSS:

.pointer_tooltip{
   width : auto;
   height : auto;
   padding : 10px;
   border-radius : 5px;
   background-color : #fff;
   position: absolute;
}

Jquery:

$(document).mousemove(function( event ) {
    var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";     

    var position_top = event.pageY+18;
    var position_left = event.pageX-30;

    $('.pointer_tooltip').css('top',position_top+'px');
    $('.pointer_tooltip').css('left',position_left+'px');
});

This is working fine but whenever I move the pointer to left my tooltip his getting hide like below image

enter image description here

And whenever I move it right its looks like this

enter image description here

What I want is whenever i move left or right the tooltip should move right and left respectively pixel by pixel

1 Answer 1

1

try this code:-

$(document).mousemove(function( event ) {
    var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";   

    //set the actuall width
    $('.pointer_tooltip').width($('.pointer_tooltip').width());
    var position_top = event.pageY+18;
    var position_left = event.pageX-60;          
    var width=$('body').width()-$('.pointer_tooltip').width();

    //check if left not minus
    if(position_left<0){
      position_left=10;
    }else if(position_left > width){
     position_left=width-10;
    }       


    $('.pointer_tooltip').css('top',position_top+'px');
    $('.pointer_tooltip').css('left',position_left+'px');
});

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.