Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery selector issue

I have the following html markup on my page,

<div id="sig_container">
    <div id="layer1" class="layer ui-draggable ui-resizable ui-resizable-autohide">
    <div id="layer2" class="layer ui-draggable ui-resizable ui-resizable-autohide">
    <div id="layer3" class="layer ui-draggable ui-resizable selected ui-resizable-autohide">
</div>

On this page I am trying to select the #sig_container div without selecting any of the children. However I am having an issue doing so. The selector either selects everything or nothing.

Thanks in advance Daniel

Edit: Sorry i should add I am trying to add a click event on the container. So i want the event to fire only when i click the container and not the children.

like image 427
Daniel Cannon Avatar asked Apr 27 '26 17:04

Daniel Cannon


1 Answers

You can accomplish what you want by testing the event.target of the click event.

$('#sig_container').click(function( event ) {
    if( event.target === this ) {
        // the children were not clicked, so run your code
    }
});

The reason for this is that click events naturally bubble, so if you click one of the children, the event bubbles up to the sig_container and fires its handler.

With this solution, you make sure that the target of the event was actually the sig_container before it fires the code.

So basically:

  • this is the sig_container

  • event.target is the actual element clicked

  • if this is the same as the event.target run the code

like image 155
user113716 Avatar answered Apr 29 '26 07:04

user113716