Search code examples
jquerystoppropagation

event stop propagation issue with children event


I have an issue with jquery stop propagation. To close a cart modal when i click on the page except on the cart modal, i had to do :

        $('html').click(function() {
            $('.cart-block').css('display','none');
        });

        $('.mycart, .cart-block').click(function(event){
            event.stopPropagation();

        });

But i have an issue, i have an AJAX call to delete an item inside my cart div (cart-block) but the stop propagation is stopping the event.

$(document).on('click', '.deleteItem', function() {
    //ajax call
});

Is anyone can help me ? thanks a lot (sorry for my english)

EDIT : HTML STRUCTURE //button cart

  <div class="center cart mycart" >
           //icon and cart item counter
            </div>

        <div id="cartcaption" class="cart-block">
    //modal : content of the cart
<div class="productsPanier">
 <span id="{{$cart->rowId}}" class="deleteItem">delete</span>
    </div>
</div>

Solution

  • Instead of what you're doing (binding 2 handlers with one stopping propagation), just bind one handler and check whether the target of event has class .cart-block

    So something like this:

    $('html').click(function(event) {
       if (!$(event.target).hasClass('cart-block'))
          $('.cart-block').css('display','none');
    });
    

    And remove the following part

     $('.mycart, .cart-block').click(function(event){
        event.stopPropagation();
     });
    

    Your events will now properly propagate and the 'display: none;' won't get added to cart block if you're clicking within cart-block element

    EDIT: if the outermost class is named 'mycart', you could alternatively try it like this:

    $('html').click(function(event) {
       if (!($(event.target).closest('.mycart').length))
          $('.cart-block').css('display','none');
    });
    

    What this will do is check if the target element of your click has a parent with class 'mycart'. This solution assumes that whatever you click inside the cart has a container with class 'mycart'. Obviously, without seeing your DOM, I cannot be sure this will solve your specific case. If it's different to what I assumed, it should point you in the right direction at least.