Misha Moroshko
Misha Moroshko

Reputation: 171439

How to change cursor based on mouse position?

I would like to change the cursor from default to pointer when the mouse enter the rectangle (50, 50, 100, 100) of the body element (the numbers are in pixels).

I know that I could define a div, place it at this position, and set cursor: pointer; on it, but I'm looking for some way without defining a div.

I would like to something like:

if (mousePosition inside rectangle) {
    change cursor to pointer
} else {
    change cursor to default
}

Is that possible to do that ?

Upvotes: 3

Views: 3780

Answers (1)

MiffTheFox
MiffTheFox

Reputation: 21575

Try something like this (untested though):

$("body").mousemove(function(e){
    if (e.pageX > 50 && e.pageY > 50 && e.pageX < 100 && e.pageY < 100)
        $("body").css("cursor", "pointer");
    else
        $("body").css("cursor", "default");
});

You might want to use a global variable though instead of just appling the properties each time for performance reasons. You also might want to look into using CSS classes instead of directly setting the style in JS.

Update: Why did I think style instead of css... :(

Upvotes: 2

Related Questions