0

We are doing logging, we have a header of the website where we are logging anytime it is clicked. We have elements within the element that need logging as well. Is there a way to only log the child elements when clicked within the header by using jquery .not() function or anything?

Here is the working jsfiddle

HTML

<div id="header">
    <div><a class="box blue" href="#">Blue</a></div>
    <div><a class="box red" href="#">Red</a></div>
    <div><a class="box green" href="#">Green</a></div>
</div>

CSS

$('#header').on('click', function() 
    alert('header')
});
$('.box').on('click', function() {
    alert($(this).attr('class'));
});
Jon Harding
  • 4,928
  • 13
  • 51
  • 96

3 Answers3

4

You can use jQuery's .stopPropagation() function to stop the bubbling from the children to the parent:

$('#header').on('click', function() {
    alert('header');
});
$('.box').on('click', function(e) {
    e.stopPropagation();
    alert($(this).attr('class'));
});
#header { padding:20px; background:yellow; overflow:auto; }
    .box { width:50px; height:50px; float:left; margin:0 20px 0 0; }
    .blue { background:blue; }
    .red { background:red; }
    .green { background:green; }
 a { color:white; display:block; text-align:center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header">
 <div><a class="box blue" href="#">Blue</a></div>
    <div><a class="box red" href="#">Red</a></div>
    <div><a class="box green" href="#">Green</a></div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
2

e.stoppropagation is one way to stop the bubbling up from the child element . other than that you can simply check if the current target element is the one that is clicked.

$('#header').on('click', function(e) {
 if(e.target == this){
    alert('header');
 }
});

fiddle

bipen
  • 36,319
  • 9
  • 49
  • 62
  • Checking target is better because it stop this particular event not all other event like Stoppropagation. – Kinga Sep 26 '14 at 15:13
1

e.stoppropagation

$('#header').on('click', function() 
    alert('header')
});
$('.box').on('click', function(e) {
    e.stoppropagation();
    alert($(this).attr('class'));
});

http://api.jquery.com/event.stoppropagation/

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81