1

I am using jquery code to make drop down on sidebar filters. this code is working properly but after selecting a filter this code is not working , i think due to ajax call. what is solution. please guide me

jQuery(function(){
    jQuery("#sidebar h4, #sidebar h3, body.woocommerce #sidebar>div>.inner .widget h4, body.woocommerce #sidebar>div>.inner .widget h3").on('click', function(){
        jQuery(this).parent().toggleClass("dropdown-hide");
    });
});
Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • What do you do after the ajax call? Do you do any DOM modifications? – vrdrv Jun 29 '22 at 10:02
  • The *most* likely case is that your ajax call replaces one or more of the elements that you have in your click selector. Change to event delegation: `$(document).on("click", "#sidebar h4, #sidebar h3....", function()...` (you can/should pick a closer common parent element that `document` but document is a catch-all) – freedomn-m Jun 29 '22 at 10:21

1 Answers1

0
jQuery(document).on('click', "SELECTOR", function(event){ 
});

This bind a click event to the document and all child elements within it. This method will works with dynamically created elements also

Working with jQuery(document).on( events

jQuery(function(){
        setTimeout(function () {
            jQuery('.btn-group').html('<button class="btn-default">Click</button>')
        },  1000);
        jQuery(document).on('click', ".btn-default", function(event){
            console.log('clicked');
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-group"></div>

Not working with jQuery(selector).on( events

jQuery(function(){
        setTimeout(function () {
            jQuery('.btn-group').html('<button class="btn-default">Click</button>')
        },  1000);
        jQuery(".btn-default").on('click', function(){
            console.log('clicked');
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-group"></div>

So, you have to change like below

jQuery(document).on('click', "#sidebar h4, #sidebar h3, body.woocommerce #sidebar>div>.inner .widget h4, body.woocommerce #sidebar>div>.inner .widget h3", function(event){

});
Mahesh Thorat
  • 1
  • 4
  • 11
  • 22