Shina
Shina

Reputation: 2066

jQuery event not working after load

$(document).ready(function(){

$(function() {
    $('a.ajaxload').click(function(e) {           
      var url = $(this).attr('href');
      $('#desktopcontainer').load(url); // load the html response into a DOM element
      e.preventDefault(); // stop the browser from following the link
    });
});

$(function() {
    $(".accordion .accordion-tabs .tab").each(function(){
        $(this).click(function(){
            if ($(this).hasClass('tab')){
            $(this).removeClass('tab');
            $(this).addClass('active');
          }else{
            $(this).removeClass('active');
                    $(this).addClass('tab');
          }

          $(this).next().slideToggle('slow');
                return false;
        });
    });
});
});

My tab works fine but after I click the "a.ajaxload" to add a content to the page, then my tab doesn't respond anymore.

Can anyone please tell me where the problem is?

SOLVED!!!

What I did was to add the function after my load ... look at the new code below and see the difference. I hope it helps someone.

$(document).ready(function(){

initDashboard();

$(function() {
    $('a.ajaxload').click(function(e) {           
      var url = $(this).attr('href');
      $('#desktopcontainer').load(url); // load the html response into a DOM element
      e.preventDefault(); // stop the browser from following the link
      initDashboard();
    });
});

function initDashboard() {
    $(".accordion .accordion-tabs .tab").each(function(){
        $(this).click(function(){
            if ($(this).hasClass('tab')){
            $(this).removeClass('tab');
            $(this).addClass('active');
          }else{
            $(this).removeClass('active');
                    $(this).addClass('tab');
          }

          $(this).next().slideToggle('slow');
                return false;
        });
    });
}

});

Upvotes: 3

Views: 4507

Answers (1)

Blaster
Blaster

Reputation: 9110

You need on() since it is dynamically added (eg inserted via load method):

$('.accordion .accordion-tabs').on('click', '.tab', function(){
   if ($(this).hasClass('tab')) {
        $(this).removeClass('tab');
        $(this).addClass('active');
   }else{
        $(this).removeClass('active');
        $(this).addClass('tab');
   }

   $(this).next().slideToggle('slow');
        return false;    
   });
});

Also no need to use jQuery ready handler three times, just put all your jQuery-related code inside this:

$(document).ready(function(){

});

Docs:

Upvotes: 2

Related Questions