Reputation: 1505
Let's say I have Div A, with a child Div B. Both have a mouse click assigned to them. How might I be able to click Div A, and have both Div A's and Div B's events triggered? I've looked into event bubbling but all my attempts to make this happen have failed so far.
I am assigning mouse events as such:
elem.addEventListener( 'click', myResponseFunction, true );
I tried setting the bubbling to true and false on both or one or the other and have had no success. Is this possible? No jQuery solutions please.
Further clarification:
Consider an expandable ad with tiles in the collapsed portion that can either be video or synopsis, determined at runtime from a data provider. I want the ad to expand when clicked anywhere in the collapsed portion, but if a "view video" button or "view synopsis" button is below the click-to-expand button, I'd like the ad to advance to the appropriate view after expanding. I desired a cleaner approach, if possible, than putting the expand action on each tile's call-to-action button. Each tile is a div with a background image and call-to-action button, all covered by and click-to-expand button.
Upvotes: 1
Views: 2893
Reputation: 3515
Click events are only triggered on those elements that are under mouse/touch pointer.
Bubbling (up) means that once a child element has processed a click event it then triggers another event of the same type on it's parent element. This process repeats all the way up to the document
element. What you want is bubbling down. Unfortunately that concept doesn't exist in JavaScript.
A pragmatic solution is to iterate over all child nodes and trigger click events manually when a parent node is clicked. There will be one side effect: mouse events bubble up by default and so when a child node is clicked, it's parent will also receive a click event. This can be easily solved by stopping event propagation further up inside of a child click event handler.
Here is a complete sample:
document.querySelector('.parent').addEventListener('click', function(e) {
console.log('hello from parent');
var children = this.children;
[].forEach.call(children, function(elem) {
elem.click();
});
});
document.querySelector('.child').addEventListener('click', function(e) {
e.stopPropagation();
console.log('hello from child');
});
.parent {
height: 300px;
width: 400px;
background-color: lightblue;
}
.child {
position: relative;
top: 100px;
left: 100px;
height: 100px;
width: 200px;
background-color: lightyellow;
}
<div class='parent'>
<div class='child'></div>
</div>
Upvotes: 2