javascript - On click event not working when it has child elements -


sorry if title kinda confusing i'll try , explain through code. have created button show or hides cart of e-commerce site(i'm using woocommerce). here sample of 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 when click on child elements img or span doesn't seem trigger onclick function though it's inside parent element(.toggle-cart)

here link website http://crate.ph/home/

enter image description here

both of event handlers firing single click you're toggling twice. you'll able see problem if put breakpoint in each handler.

try adding event.stoppropagation() toggle-cart handler instead of if-statement in other handler. 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

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -