Veldin
Veldin

Reputation: 23

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;
}

Upvotes: 2

Views: 10589

Answers (2)

6pandas
6pandas

Reputation: 21

As for your code, you will have to bind the event to the div.

An easy way to do this would be to not dynamically generate the div, just show and hide it. (As in my example). This is faster as well.

Alternatively, each time you generate the div, define and trigger the set mouse event from within the function that generates it.

Providing an alternate way of doing this:

Firstly, the HTML. Add the following anywhere inside the body.

<div id="tooltip"></div>

Now the CSS (add more to make it look pretty):

#tooltip {
position: absolute;
display: inline-block;
opacity: 0;
}

Make a class called tips and have all elements that you wish to provide tool tips for, belong to that class.

And then the jQuery:

//For every element in ".tips" have an attribute "tooltiptext" 
$('.tips').mouseenter(function(e) {
    $("#tooltip").css("left", e.pageX + 10);
    $("#tooltip").css("top", e.pageY+ 10);
    $("#tooltip").html($(this).attr("tooltiptext"));
    $("#tooltop").show();
});
$('.tips').mouseout(function() {
    $("#tooltip").hide();    
});

Do tell me if this works.

Upvotes: 2

leo.fcx
leo.fcx

Reputation: 6467

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.

Upvotes: 4

Related Questions