J Doe.
J Doe.

Reputation: 349

Stop propagation on specific element

I have a drop down menu within a header using Bootstrap data-toggle="dropdown". When you click the drop down button, a list should appear. When you click the header, the content should slide up and down.

The problem is, when I click the drop down button it also triggers the header. The usual answer here is e.stopPropagation but when I use that, it also stops the drop down menu from appearing.

How can I prevent the dropdown button from triggering the header?

HTML

<div id="top">
  <div class="dropdown">
    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
      Show List
    </button>
    <ul class="dropdown-menu">
      <li>Some Item</li>
      <li>Some Item</li>
      <li>Some Item</li>
    </ul>
  </div>
</div>
<div id="content" class="collapse">
  This is the actual content
</div>

JS

// CANNOT USE BOOTSTRAP DATA-TARGET !
$('#top').click(function() {
  $('#content').collapse('toggle')
})
$('button').click(function(e) {
  //e.stopPropagation();
})

I have prepared a fiddle that illustrates this issue.

Upvotes: 2

Views: 2348

Answers (3)

SilverSurfer
SilverSurfer

Reputation: 4366

Another way to do it, use e.target to determine if the clicked element is #top:

$('#top').click(function(e) {
   if(e.target.id=="top"){
        $('#content').collapse('toggle')
   } 
})
$('button').click(function(e) {
  //e.stopPropagation();
})

Upvotes: 0

Comteng
Comteng

Reputation: 11

You can do this as well.

// CANNOT USE BOOTSTRAP DATA-TARGET !
$('#top').click(function(e) {
    if(e.target.type != "button"){
      $('#content').collapse('toggle')
  } 
})
$('button').click(function(e) {
  //e.stopPropagation();
})

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You should instead filtering regarding event.target of click on #top element:

$('#top').click(function(e) {
  if($(e.target).closest('button[data-toggle], .dropdown-menu').length) return;
  $('#content').collapse('toggle')
})

-jsFiddle-

Upvotes: 2

Related Questions