5

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.

enter image description here

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
AlexB
  • 7,302
  • 12
  • 56
  • 74

1 Answers1

10

You can do that inline with stopPropagation.

<div onclick="alert('Red Square Clicked'); event.stopPropagation();">I am the red square</div>
VDWWD
  • 35,079
  • 22
  • 62
  • 79
  • Ok it was so easy I forget to use the `event.stopPropagation()`... It works well, thanks ! – AlexB May 12 '17 at 21:07