JamesBrownIsDead
JamesBrownIsDead

Reputation: 915

jQuery: Having one element act as event proxy for another

I have two elements laid over one another. I'd like whatever mouse events are triggered on the top-most element to not apply the event to the top-most element and instead apply it to the element underneath it. How can I do this?

In other words, the element with the highest z-index should appear on top but be invisible to mouse events so the element beneath it receives them instead.

Upvotes: 1

Views: 1462

Answers (3)

Macil
Macil

Reputation: 3703

You can accomplish this with the CSS property pointer-events:

#top {
  pointer-events: none;
}

It's supported by most browsers, though IE only supports it from 11 and up.

Upvotes: 1

machineghost
machineghost

Reputation: 35807

Depending on your needs, you can also just hook your event handler up to the bottom element:

 $('#bottom').click(function(e){
   doWhatever();              
 });

As long as you don't hook any handlers up to "top", the events will just bubble up to the "bottom" element.

(Well, technically even if you do hook handlers up to "top" this will still work, as long as those handlers don't return false or trigger stopPropagation ... but then you'd have "top" handlers triggering which I think is what you're trying to avoid.)

Upvotes: 0

kioopi
kioopi

Reputation: 2250

You can trigger the event of the lower element in the event-handler of the higher element:

 $('#top').click(function(e){
   $('#bottom').trigger(e);                   
 });

You can bind all the events you want to proxy together:

$('#top').bind('mouseenter mouseleave mousemove click etc', function(e) {
  $('#bottom').trigger(e);
});

I'm not sure what happens to mouseX, mouseY, target, etc.

Upvotes: 1

Related Questions