开发者

Make content div clickable with nested divs

开发者 https://www.devze.com 2023-02-10 18:21 出处:网络
I have the following layout: <div id=\"content\"> <div id=\"img\"><img src=\"\"></div>

I have the following layout:

<div id="content">
  <div id="img"><img src=""></div>
  <div id="main">Some content</div>
  <div id="btn" class="hidden"><button>Submit</div>
  <div class="hidden">Some other stuff</div>
</div>

I have jQuery click event tied to the content div that expands it an开发者_如何学God makes the hidden divs (the button and more content) visible. I also have an event tied to the button that activates a modal on click.

The expand/collapse of the div works without a problem using hide/show methods. The problem is after clicking on the button, the div collapses even though the modal is activated.

So after clicking on the Submit button, the modal pops up but in the background the main div is collapsed. I am trying to keep the main div open if the Submit button is pushed.

I tried setting the z-index fields on the button and the containing div to a value higher than what's on content div; this did not help.

How could I keep the functionality of clicking anywhere in the collapsed div (where the button and extra content are not visible) expands that div and clicking on the button in the expanded div activate the modal dialog without collapsing the main div?

Thank you


You have to prevent the event from bubbling up. When you click the button, the click event bubbles up the DOM tree and triggers other event handlers.

Have a look at event.stopPropagation():

$('button').click(function(event) {
    event.stopPropagation()
    // modal stuff
});

You can also ignore all clicks that don't originate at the #content div:

$('#content').click(function(event) {
    if(event.target == this) {
       // hide/colapse
    }
});

This might be better if you want to click "anywhere" inside the div without hiding it.


It sounds like the click event from the button is being used to open the modal (like you want), but then continues to propagate up the DOM tree until it triggers the onclick event handler for the "content" div as well, closing it.

You should be able to stop this by either returning false from your button's onclick function or by calling event.stopPropagation() anywhere in that same function.

Hope this helps!


$("#btn").click(function(event){
  event.stopPropagation();
  // do something
});  

Stopping event bubbling.


Try putting e.stopPropagation() on your button click event. Like this:

$("#btn").click(function(e) {
    e.stopPropagation();
    // some other code
});
0

精彩评论

暂无评论...
验证码 换一张
取 消