I have a page which displays team members (each being a custom post type) and, when a team member is clicked, the content opens inside a modal window called #single-post-container. I do this by attaching an onclick event to each link which has a class of ".post-link". This works fine, but inside the modal window I also have links allowing the navigation between members without closing the window. I display these using <?php previous_post_link(); ?>
(same for next post) and I made sure the links being output also have the class ".post-link" by using a filter inside functions.php. The problem is that these links don't always work, sometimes the page content doesn't load inside the modal windows and I suspect there is something not right in my apropach even though it works most of the time.
Here is the relevant code:
The modal window div, which is initially hidden:
<div id="single-post-container" class="hidden"></div>
The links where jQuery will attach the "onclick" event:
<h1><a class="post-link" rel="<?php the_ID(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
The ajax.js script which I enqueue after jQuery:
jQuery(document).ready(function ($) {
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
$("#single-post-container").show();
var post_link = $(this).attr("href");
$("#single-post-container").html("content loading");
$("#single-post-container").load(post_link);
return false;
});
$("#close").click(function(){
$("#single-post-container").hide();
});
});
And then in the template for each single post called single-team.php, I also call the same script at the end, since I know the links generated within are not part of the DOM at the beginning, so the event listener cannot be attached until the page is loaded inside the modal window (though I suspect this is where my approach might be wrong):
<script src="<?php echo get_template_directory_uri(); ?>/js/ajax.js"></script>