user123
user123

Reputation: 43

Combine two scripts into one

I have those two scripts; first works on page load and second after ajax call, how to combine them into one?

<script>
$('.togglestuff').click(function() {
    $('.views-table').toggle('slow');
});
</script>
<script>
$(document).ajaxComplete(function(){
    $('.togglestuff').click(function() {
        $('.views-table').toggle('slow');
    });
})
</script>

Upvotes: 2

Views: 326

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

Use event delegation with on()

$(document).on('click', '.togglestuff', function() {
    $('.views-table').toggle('slow');
});

This is delegating an event handler from document for all current and future .togglestuff elements

Update

If you are using an older jQuery version which does not support on(), a workaround would be

$(document).click(function(e){
   if(e.target.className == 'togglestuff'){
       $('.views-table').toggle('slow');
   }
});

Upvotes: 4

Related Questions