Myafk
Myafk

Reputation: 25

How detect first div clicked when all of them absolute

sorry for my bad English. I have (for example 3 level of divs), all they have position absolute. I want to add class 'Exit' for div which the user clicked. But when the user clicks on one div the function is triggered not only this but on all of his parents, how can I change its function so that it works only 1 time for 1 item? This my code:

Html

<div class="center">
   <div class="right">
      <div class="top">
      </div>
   </div>
</div>

Js

$(document).on('click', 'div', function() {
   console.log($(this));
   $('div').removeClass('exit');
   $(this).addClass('exit');
});

Console, when user click on div 'top'

[div.top, context: div.top, jquery: "1.11.1", constructor: function, selector: "", toArray:  function…]
[div.right, context: div.right, jquery: "1.11.1", constructor: function, selector: "", toArray: function…] way.php:28
[div.center, context: div.center, jquery: "1.11.1", constructor: function, selector: "", toArray: function…]

Css

div {
    position: absolute;
    background-color: #000;
    box-shadow: inset 0px 0px 0px 2px yellow;
}

And these divs are located in different areas of the screen (via css).

Upvotes: 0

Views: 102

Answers (1)

Marian Gibala
Marian Gibala

Reputation: 884

You are looking for jQuery stopPropagation method which prevents to event bubbling.

$(document).on('click', 'div', function(event) {
    event.stopPropagation();   
    console.log($(this));
   $('div').removeClass('exit');
   $(this).addClass('exit');
});

Upvotes: 2

Related Questions