andy
andy

Reputation: 2754

document.ready not working with ajax loaded content

I'm using ajax to load in posts on a WordPress site.

Inside each post I have a hidden div with sharing buttons, which is unhidden with a jquery toggleClass function.

It's really simple.

$(document).ready(function(){ 
    $(".sharing-mp").click(function() {       
      $(".sharing-mp").toggleClass('sharing-mp-hidden').toggleClass('sharing-mp-visible');
    });    
});

The problem is, it doesn't work on posts that are loaded in with ajax, I guess because they're being appended to the DOM and the .ready function isn't finding them? Is there some other way to do it?

Upvotes: 2

Views: 2839

Answers (3)

Jai
Jai

Reputation: 74738

Yes you have to use event delegation with .on() handler to its parent which was available at the time of page load. This could be the $(document) itself because its the parent of all other elements or you could try to delegate the event to its closest available parent which was available at doc ready like post holder div or content container etc.

Nonetheless this will work:

$(document).ready(function(){ 
    $(document).on('click', '.sharing-mp', function() {       
      $(this).toggleClass('sharing-mp-hidden sharing-mp-visible');
    });    
});

Upvotes: 0

Adil
Adil

Reputation: 148120

You need to use on() to bind click event for dynamically loaded elements. You can delegate the event to parent element to which elements added dynamically or to document otherwise.

$(document).ready(function(){ 
     $(document).on("click", ".sharing-mp", function() {     
         $(".sharing-mp").toggleClass('sharing-mp-hidden').toggleClass('sharing-mp-visible');    
     });    
});

Upvotes: 7

schmicko
schmicko

Reputation: 53

You probably only need one of those classes too.

sharing-mp-hidden and sharing-mp-visible sound like they're simply opposites of each other. So one would have display: none; and the other display:block;. Instead of 2 classes you could set the default for sharing-mp to be display:block;

Also, there is are jquery functions for show and hide which do the same thing.

Upvotes: 1

Related Questions