Skip to content Skip to sidebar Skip to footer

Inner Div Affected By Outer Div's Onclick

Problem: Clicking of the inner div triggers the onClick-event of the outer div. In this case it toggles the visibility of the outer
, inner
and the

Solution 1:

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:

functiontoggleMessageForm(evt){
  if (evt.stopPropagation) {
      evt.stopPropagation();
  }
  else {
      evt.cancelBubble = true;
  }
  $('#messageForm').toggle();
}

...but as you're already using jQuery, that would be unusual.

Solution 2:

Use stopPropagation();

function toggleMessageForm(e){
 e.stopPropagation();
  $('#messageForm').toggle();
}

e.stopPropagation();

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Solution 3:

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();
});

Post a Comment for "Inner Div Affected By Outer Div's Onclick"