D.R.
D.R.

Reputation: 21194

JavaScript or JQuery: get innermost element on position

I want to get the innermost element on a certain cursor position, i.e.:

<div>
  <div>
    <span>Text</span>
  </div>
</div>

If I point my mouse cursor over the text, I want to retrieve the span tag, not the outermost div which is the default of JavaScript's elementFromPoint(x,y).

(if it is of any help: I want to retrieve the element inside a JQuery keydown event handler)

Upvotes: 1

Views: 432

Answers (3)

sbonkosky
sbonkosky

Reputation: 2557

Demo: http://jsfiddle.net/mspocq9h/1/

var hoverEleme = null;

$('*').hover(function(){ 
    hoverEleme = $(this); 
});

$(window).on('keydown', function( e ) {
    // Get hoverEleme here
    $('span').css('color', 'black');
    $(hoverEleme).closest('span').css('color','red');
});

Using jQuery's .closest() call with traverse up the element's ancestors to find the first element matching the selector, in this case the closest span.

Here there are no filters for what key was pressed, and it just sets the color to red so you can see it finds the one you're looking for.

Upvotes: 0

Ray_Poly
Ray_Poly

Reputation: 173

you can do something like this:

$('div').hover(function(element){
   element.find('span').dosomestuff();
});

I hope it helps.

Upvotes: 1

jAndy
jAndy

Reputation: 236022

A keydown event does not provide properties like .pageX and .pageY, so you cannot apply those values on document.elementFromPoint(). You need to have an event listener on your window or document.body and provide the event data information to a more public context, so you can access that data in your keydown handler.

Demo: http://jsfiddle.net/1ztf2p9b/

Upvotes: 1

Related Questions