user1658080 user1658080 -4 years ago 56
Javascript Question

On click except one child with class + use of this

I was wondering how I could define a click event in jQuery / JavaScript which excludes children with a specific class. In the same time I need to use "this" to access the clicked element.



$(".slidebox-header *:not(.stop)").click(function(event) {
alert("woohoo!");
$(this).siblings(".slidebox-content").slideToggle();
});

.slidebox-header {
background-color: yellow;
}

.stop {
background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slidebox">
<div class="slidebox-header">
<div class="stop">BLOCKED AREA</div>
<span>Header - Click allowed</span>
</div>
<div class="slidebox-content">
<p>Content</p>
</div>
</div>





But because "this" refers to the children of ".slidebox-header", it is not working.

My question: Is there an elegant way to solve this issue?

Thanks a lot!

Answer Source

slidebox-content is a sibling of slidebox-header, so use .closest() to traverse to to header then use .sibling()

$(".slidebox-header *:not(.stop)").click(function(event) {
  $(this).closest('.slidebox-header').siblings(".slidebox-content").slideToggle();
});

Also you can use descendant selector to target the specific child.

$(".slidebox-header > span").click(function(event) {
  $(this).closest('.slidebox-header').siblings(".slidebox-content").slideToggle();
});

$(".slidebox-header *:not(.stop)").click(function(event) {
  //alert("woohoo!");
  $(this).closest('.slidebox-header').siblings(".slidebox-content").slideToggle();
});
.slidebox-header {
  background-color: yellow;
}

.stop {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slidebox">
  <div class="slidebox-header">
    <div class="stop">BLOCKED AREA</div>
    <span>Header - Click allowed</span>
  </div>
  <div class="slidebox-content">
    <p>Content</p>
  </div>
</div>


Or you could bind event with header and use event.stopPropagation() with block element to stop event bubbling.

$(".slidebox-header").click(function(event) {
  $(this).siblings(".slidebox-content").slideToggle();
});
$(".slidebox-header .stop").click(function(event) {
  event.stopPropagation();
});

$(".slidebox-header").click(function(event) {
  $(this).siblings(".slidebox-content").slideToggle();
});
$(".slidebox-header .stop").click(function(event) {
  event.stopPropagation();
});
.slidebox-header {
  background-color: yellow;
}

.stop {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slidebox">
  <div class="slidebox-header">
    <div class="stop">BLOCKED AREA</div>
    <span>Header - Click allowed</span>
  </div>
  <div class="slidebox-content">
    <p>Content</p>
  </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download