I have a bunch of divs postioned absolutely on top of each other. When I bind a click event to all of them, only the top div responds. How can I send the event to all divs under the cursor?
Two mechanisms allow the click event to be passed through or not : attaching the handler to only selected elements (standard jQuery). namespacing the click event, click. passThrough analogous to event.
To set an onClick listener on a div element in React:Set the onClick prop on the div. The function you pass to the prop will get called every time the div is clicked. You can access the div as event.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
Taking FelixKling's suggestion to use document.elementFromPoint()
and Amberlamps's fiddle, and employing jQuery for the DOM interactions, I ended up with the following :
$divs = $("div").on('click.passThrough', function (e, ee) {
var $el = $(this).hide();
try {
console.log($el.text());//or console.log(...) or whatever
ee = ee || {
pageX: e.pageX,
pageY: e.pageY
};
var next = document.elementFromPoint(ee.pageX, ee.pageY);
next = (next.nodeType == 3) ? next.parentNode : next //Opera
$(next).trigger('click.passThrough', ee);
} catch (err) {
console.log("click.passThrough failed: " + err.message);
} finally {
$el.show();
}
});
DEMO
try/catch/finally
is used to ensure elements are shown again, even if an error occurs.
Two mechanisms allow the click event to be passed through or not :
click.passThrough
analogous to event.stopPropagation()
.Separately or in combination, these mechanisms offer some flexibility in controlling the attachment and propagation of "passThrough" behaviour. For example, in the DEMO, try removing class p
from the "b" element and see how the propagation behaviour has changed.
As it stands, the code needs to be edited to get different application-level behaviour. A more generalized solution would :
event.stopPropagation()
.Both of these ambitions might be achieved by establishing a clickPassthrough
event in jQuery, with underlying "passThrough" behaviour, but more work would be involved to achieve that. Maybe someone would like to have a go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With