Search code examples
javascriptjquerypositiontooltipmouse

Jquery set div at mouse position


I want to have an div under my mouse at all times, this div I want to use to display tool-tips.

This is the code i'm trying to use. But this code gives an error: " Cannot read property 'pageX' of undefined"

My question is why is pageX undefined, and how do I fix this problem?

$( document ).ready(function() {

    AppentMouse(); //Setup div that is used for mouse icon

    window.setInterval(function(){
        SetMouse(); //Set div that is used for mouse icon at mouse location
    }, 5);
});

function AppentMouse(){
    $( 'Body' ).append( "<div id='Mouse'>Mouse</div>");
}
function SetMouse(){
var e = window.event || e; 

    var left  = e.pageX + "px";
    var top  = e.clientY  + "px";

    var div = document.getElementById('Mouse');

    div.style.left = left;
    div.style.top = top;
}

Solution

  • Considering this is your html code:

    <body>
        <div>Your content</div>
    </body>
    

    And you have these styles for the div:

    div {
        position: absolute;
        border: solid 1px #fc0;
    }
    

    Using jQuery, attach mousemove event listener to the document and make the div to have top and left styles changed on every move:

    $(document).on('mousemove', function(e){
        $('div').css('top', e.pageY);
        $('div').css('left', e.pageX);
    });
    

    See this JSFiddle

    EDIT:

    Considering your code, variable e is undefined. And the error says that an undefined value does not have a pageX property.

    That is because you need an mouse event (for your case) to have object event defined. And that object is received by the event listener that we add in the code that I provided.