Reputation: 3733
Problem:
Clicking of the inner div triggers the onClick-event of the outer div. In this case it toggles the visibility of the outer <div>
, inner <div>
and the <p>
element.
What I've tried:
Setting the z-index higher on the inner div than the outer div. No effect.
HTML:
<div id='messageForm' onClick=toggleMessageForm() >
<div class="innerBox">
<p>Hi!</p>
</div>
</div>
JS:
function toggleMessageForm(){
$('#messageForm').toggle();
}
Note: The reason I'm using toggle() instead of show() is because I am using the same function when initially showing the form from a button in the original webpage.
Upvotes: 2
Views: 2624
Reputation: 2865
if you have one or more jQuery click functions on outer and inner div and you want to be performed only one of them (for example outer div) use stopImmediatePropagation function of jQuery:
$("#messageForm").click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
$('#messageForm').toggle();
});
Upvotes: 0
Reputation: 1075437
Remove the onClick
attribute entirely, and instead hook up the handler with jQuery:
$("#messageForm").click(function(evt) {
evt.stopPropagation();
toggleMessageForm();
});
Put that in a script
element lower down in the HTML than the div
(or wrap it in a ready
handler).
evt.stopPropagation
cancels the bubbling (stops the propagation) of the click event, so it doesn't reach the parent div.
If you really, really want to keep the onClick
attribute, you can do this instead:
<div id='messageForm' onClick="toggleMessageForm(event);">
...and then in toggleMessageForm
:
function toggleMessageForm(evt){
if (evt.stopPropagation) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
$('#messageForm').toggle();
}
...but as you're already using jQuery, that would be unusual.
Upvotes: 2
Reputation: 9637
Use stopPropagation();
function toggleMessageForm(e){
e.stopPropagation();
$('#messageForm').toggle();
}
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Upvotes: 0