1
<html>
    <head>
        <style>
            body
            {
                margin:0;   
            }
            .container
            {
                display:table;
                width:100vw;
                height:100vh;
                position:absolute;
                background:#000;
            }
            .helper
            {
                display:table-cell;
                vertical-align:middle;
            }
            .content
            {
                margin-left:auto;
                margin-right:auto;
                width:500px;
                height:200px;
                background:#FFF;
            }
        </style>
    </head>
    <body>
        <div class="container" onClick="alert('A')">
            <div class="helper">
                <div class="content" onClick="alert('C')">
                </div>
            </div>
        </div>
    </body>
</html>

I need to run some script when user click the content div and another script when user click the container div.

But when I click content div it run content script and container div.

How to make it only run content script when the content div is clicked.

Thanks

KononK
  • 13
  • 4
  • 2
    [`Event.stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) – Andreas Oct 28 '15 at 07:58

2 Answers2

3

Just add a event.stopPropagation. Below is the code.

<div class="container" onclick="alert('A')">
            <div class="helper" id="content">
                <div class="content" onclick="alert('C') event.stopPropagation;">
                </div>
            </div>
        </div>
  </div>

This is jsfiddle link with solved problem

shumana chowdhury
  • 1,742
  • 2
  • 14
  • 34
  • it only run alert('A'), I want to make it only run alert('C') when i click the content div – KononK Oct 28 '15 at 10:35
  • 1
    it's work. it only missing ";" after "alert('c')" and '()' after "event.stopPropagation" thanks – KononK Oct 28 '15 at 10:54
0

When you click on an element the event moves upwards or downwards. It depends on the 3rd parameter (true or false). Based on that you need to stop the propagation/bubbling to stop at the element you want it to stop. Here is it . . .

http://javascript.info/tutorial/bubbling-and-capturing

Gacci
  • 1,388
  • 1
  • 11
  • 23