Here is the deal:
The dark square has a onclick
event attached
The red square, which overlaps the dark square, also have its own onclick
event.
When I click the red square, I'd like only the red square's onclick
event to be fired.
When I click the dark square, I'd like only the dark square's onclick
event to be fired.
Currently, both are fired, and this is a problem for me.
How can I achieve my goal?
Some piece of code:
$('#dark-square').loadData({
//load some HTML template with red square element inside
//Red square looks like :
//<div id="red-square" onclick="myFunction()">Some plain text</div>
}).click(function() {
//what to do when dark-square only is clicked
})
#red-square {
position: absolute !important;
top: 9px !important;
right: 16px !important;
z-index: 1000 !important; //I tried that to force the element to be on the top, but no result on onclick
}
//#dark-square is just a div with width / height
TIP : For simplicity, I'd like to keep the Javascript syntax to add my onclick
event on dark square, and inline syntax on red square.
Here is the deal:
The dark square has a onclick
event attached
The red square, which overlaps the dark square, also have its own onclick
event.
When I click the red square, I'd like only the red square's onclick
event to be fired.
When I click the dark square, I'd like only the dark square's onclick
event to be fired.
Currently, both are fired, and this is a problem for me.
How can I achieve my goal?
Some piece of code:
$('#dark-square').loadData({
//load some HTML template with red square element inside
//Red square looks like :
//<div id="red-square" onclick="myFunction()">Some plain text</div>
}).click(function() {
//what to do when dark-square only is clicked
})
#red-square {
position: absolute !important;
top: 9px !important;
right: 16px !important;
z-index: 1000 !important; //I tried that to force the element to be on the top, but no result on onclick
}
//#dark-square is just a div with width / height
TIP : For simplicity, I'd like to keep the Javascript syntax to add my onclick
event on dark square, and inline syntax on red square.
- 1 You need to prevent the event from bubbling up: api.jquery./event.stoppropagation – Jonathan Dion Commented May 12, 2017 at 21:02
1 Answer
Reset to default 10You can do that inline with stopPropagation
.
<div onclick="alert('Red Square Clicked'); event.stopPropagation();">I am the red square</div>