clestcruz clestcruz - 6 months ago 13
Javascript Question

On click event not working when it has child elements

Sorry if the title is kinda confusing I'll just try and explain through code. Basically I have created a button that show or hides the cart of an e-commerce site(I'm using woocommerce). Here is a sample of the code I'm working.

enter image description here

HTML Markup

<div class="crate-status toggle-cart">
<img src="http://localhost/crate/wp-content/uploads/2016/05/mini-cart-icon.png" /><span class="crate-name">Crate:</span>
<span class="cart-contents"><?php echo sprintf (_n( '%d', '%d', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></span>

<?php woocommerce_header_add_to_cart_fragment( $fragments ) ?>
</div>


Javascript

$(document).ready(function() {
$('.toggle-cart' ).on('click', function(event) {
$('.crate-box').toggleClass('toggle');
$('.overlay-site').toggleClass('show-overlay');
})

$('body').on('click', function(event) {
if (!$(event.target).is('.toggle-cart')) {
$('.crate-box').removeClass('toggle');
$('.overlay-site').removeClass('show-overlay');
}
})

})


The button works fine but when I click on the child elements like img or span it doesn't seem to trigger the onclick function even though it's inside a parent element(.toggle-cart)

Here is the link to the website http://crate.ph/home/

enter image description here

Answer

Both of your event handlers are firing from a single click so you're toggling it twice. You'll be able to see the problem if you put a breakpoint in each handler.

Try adding event.stopPropagation() to the toggle-cart handler instead of the if-statement in the other handler. Like so:

$(document).ready(function() {
    $('.toggle-cart' ).on('click', function(event) {
        event.stopPropagation();
        $('.crate-box').toggleClass('toggle');
        $('.overlay-site').toggleClass('show-overlay');
    })

    $('body').on('click', function(event) {
        $('.crate-box').removeClass('toggle');
        $('.overlay-site').removeClass('show-overlay');
    })
})
Comments