Evi
Evi

Reputation: 39

How to disable jQuery(document).ready(function()

I want to disable jQuery(document).ready(function() after jQuery(document).ajaxComplete.. This is my code.

function doStuff(){
  jQuery('.type-title').click(function(e){
       e.preventDefault();
      if(!jQuery(this).parent('.type-top').hasClass('collapsed')){
        jQuery(this).parent('.type-top').addClass('collapsed');  
       }      
    };

jQuery(document).ready(doStuff);
jQuery(document).ajaxComplete(doStuff);

Everything works fine, but after new div is open by ajax, Click function works only on new div, on old divs click does not work, it means I should disable jQuery(document).ready function. I have treid many things but no one was working.

how can I disable jQuery(document).ready function? I try this, but it does not work too.

var flag = ' ';
jQuery(document).ready(function() {
 flag = true;
   if(flag){ 
    doStuff();
   } 
}); 
jQuery.ajax({ 
  success: function(){
   flag = false;   
   doStuff(); 
   } 
 });

Thanks

Upvotes: 0

Views: 1380

Answers (1)

Andrew
Andrew

Reputation: 13853

Instead of attaching your event handler to the divs each time what you really need to do is use a delegated event handler

You didn't show your HTML so I will use an example, given,

<div class="my-container">
  <div class="type-top">
     <div class="type-title">...</div>
  </div>
  <div class="type-top">
     <div class="type-title">...</div>
     <div class="type-title">...</div>
  </div>
</div>

You can listen to events on all the children by specifying a delegated listener,

function doStuff(){
 jQuery(".my-container").on("click", ".type-title", function() {
   e.preventDefault();
   if(!jQuery(this).parent('.type-top').hasClass('collapsed')){
     jQuery(this).parent('.type-top').addClass('collapsed');  
   }  
 });
}

jQuery(document).ready(doStuff);

This listener will automatically pick up events from new .type-title divs as they are added, so you only need to call this once when the document loads.

Upvotes: 0

Related Questions