38

Situation:

<div class="header">
    <div style="float: left;" class="headerTitle">+ OPEN</div>
    <div class="closeBtn" style="float: right;">- CLOSE</div>
 </div> 
<div class="touristenContent">.....</div>

Visually:

|+Open..............................|-Close|..| (header)

|............Content..........................|

Header DIV is a 'big button' with jQuery click() event for opening the content. The close DIV is inside the big header DIV and represents the close button also with click() event to close the content. This close button is only visible by clicking on the big header.

Clickng on the header and oppening the content works as expecting but clicking on the close button let the click event through to the header DIV. The content closes and opens again beacause of two click events.

So how can i design the whole thing properly to make the close button solid and to prevent click through it to the header?

1
  • 10
    Not every JavaScript question on Stack Overflow needs to be demonstrated on jsfiddle.net. While it does help for many questions, I'm beginning to get the feeling that some users are considering it mandatory. Not sure who down voted, but this is a perfectly valid question without a jsfiddle to back it up.
    – Andy E
    Oct 20, 2011 at 12:20

3 Answers 3

61

You need to stop the event from propagating up the DOM tree:

$('.closeBtn').click(function (evt) {
    evt.stopPropagation();

    // Your code here
});
0
13
$('.closeBtn').click(function (event){
   event.stopPropagation();
   //   ... your code here
   return false;
});

that should do the trick, so everytime you click on close it will not affect your header div,

4
  • Thank You very much! Is it important to have 'return false;' at the end? Oct 20, 2011 at 12:26
  • 4
    @PaulGeisler: return false; would also cancel the browser's default action. In this case, there is no default action for clicking a <div> element so it isn't necessary.
    – Andy E
    Oct 20, 2011 at 12:28
  • 1
    If you want to cancel the default action, event.preventDefault() is the right way, at least in 2016.
    – Mark
    Feb 22, 2016 at 19:44
  • The solution didn't work for me without the return false;
    – Savage
    Jul 12, 2019 at 16:02
0

Why not hook open event with <div style="float: left;" class="headerTitle">+ OPEN</div> instead of parent div. Otherwise return false or stopPropagation from inner div click handler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.