skip to Main Content

I want to add a custom click event to the remove button in the mini cart

function ajax_call(){
$.ajax({
      url: ajax_url,
      type: 'post',
      data: {action : 'remove_from_cart','cart_item_key' : 10},
      beforeSend: function(res){
        console.log('loading');
      },
      success: function(res){
        $('.widget_shopping_cart_content ').replaceWith(res); // once this worked, the click function below became not working
}
});
}

$('.remove_from_cart_button').click(function(e){
    e.preventDefault();
    ajax_call();
});

Some of the code I’ve tried doesn’t work

$('.widget_shopping_cart_content .remove_from_cart_button').click(function(e){
    e.preventDefault();
});
$(document.body).on('click', '.widget_shopping_cart_content .remove_from_cart_button', function(e){
    e.preventDefault();
});

3

Answers


  1. Chosen as BEST ANSWER

    Thanks all for the answers, I just found a function that is wc_fragments_refreshed which is the answer to my question this time. my mistake, I should have made the question more specific, namely adding a function when an item on the mini cart is removed.

    $(document.body).on('wc_fragments_refreshed', function(){
      $('.remove_from_cart_button').click(function(e){
        e.preventDefault();
      });
    });
    

  2. I’m pretty sure your $(document.body) one should work at least. Since you mentioned it’s loaded dynamically from ajax. As long as you register an event relative to an element that wasn’t reloaded, it should work (in your case the document.body should be fine). I’m assuming you had some functions running after the e.preventDefault()? Do those functions have any errors? I don’t know your html structure, but you could also confirm you’re not accidentally overwriting a parent element when you finish the ajax call (this would break the ".widget_shopping_cart_content .remove_from_cart_button" node tree). I’d need a bit more info like the html structure, what the button functions are doing and maybe the structure of the js file itself to help more, but hopefully this helps.

    EDIT:
    The only other thing I can think of, sometimes you can need to wrap your handlers in this function to make sure the document is ready.

    $(document).ready(function() { 
        ...
    });
    
    Login or Signup to reply.
  3. You’re replacing (using .replaceWith()) .widget_shopping_cart_content with some other HTML, so you cannot use any more that .widget_shopping_cart_content selector since it’s removed from the DOM. Instead use only the newly generated .remove_from_cart_button

    $(document).on('click', '.remove_from_cart_button', function(evt) {
      evt.preventDefault();
      console.log($(this)); // Your $Button
    });
    

    which should work since it uses Event delegation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search