Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how do I get the element underneath my cursor?

Tags:

jquery

I'm making a drag and drop action, and I want an element to shift down when I bring an element over the one that is in my way.

like image 633
NullVoxPopuli Avatar asked Aug 13 '10 18:08

NullVoxPopuli


3 Answers

a simple hack would be to say something like:

var hoverElem = null;
$('*').hover(function() {hoverElem = this});

then when you need to call what ever function to get the value, just use hoverElem

EDIT: this is a less resource intensive call:

$('*').live('mouseenter', function() { hoverEleme = this; });

EDIT 2: due to .live() being deprecated, you should use .on()

$("*").on("mouseenter", function() { hoverElem = this; });
like image 84
Jeremy Boyd Avatar answered Sep 22 '22 05:09

Jeremy Boyd


$('*').on('mouseenter', function() { hoverEleme = this; });

This is a lot cheaper then attaching a mouse handler to every element (which also fires on mouseleave), especially the more elements you get.

like image 42
antony.trupe Avatar answered Sep 23 '22 05:09

antony.trupe


I don't know if there is a standard way, but I would probably bind a "mouseover" event to all the elements you might want to move down if you are over them and then test to see if you are currently dragging an object.

Again, i don't really know your exact setup, but you could have a global variable var currentlyDragging = false then when you start dragging set it to true. Then when you mouse over an element you want to move out of your way you can test to see if your currentyDragging variable is true and if it is then you can move it.

Bit complicated, but I can't really think of any other way of doing it off the top of my head. :)

like image 28
Thomas Clayson Avatar answered Sep 24 '22 05:09

Thomas Clayson