kenny kenny - 11 days ago 7
PHP Question

Adding and Removing class on clicks (in wordpress loop)

So I have a wordpress loop to show certain posts. Each posts has a modal that I'll show the in and each modal is triggered by the .modal-trigger class. However, because there are more than one posts I want to prevent the user from opening more than one modal at a time and this is why I want to remove the .modal-trigger class once it is clicked. I will then addClass the .modal-trigger once the .fa-close is clicked

my main objective is to remove the

.modal-trigger
class once it is clicked and add this class once the
.fa-close
class is clicked

<section class="meet-the-team">
<div class="inner">
<?php
$team = new wp_query (array(
'post_type' => 'team',
'orderby' => 'date',
'order' => 'ASC'
));
if($team->have_posts()):
while($team->have_posts()):
$team->the_post();
?>
<div class="team-section">
<p class="team-header"><?php the_title(); ?></p>
<p class="team-details"><?php the_field('person_job_title'); ?></p>

<button class="button modal-trigger ">Read More</button>

<!-- MODAL SECTION FOR READ MORE POSTS -->
<div class="my-Modal">
<i class="fa fa-close"></i>
<?php the_title(); ?>
<p><?php the_field('person_job_title'); ?></p>
<?php the_content(); ?>
</div>
<!-- ENDING OF MODAL SECTION -->
</div>
<?php
endwhile;
else: "no posts available" ;
endif;
wp_reset_postdata();
?>


my jquery

$(document).ready(function(){
$('.modal-trigger').click(function(){
var post_content = $(this).parent('.team-section').find('.my-Modal').fadeIn().css('transform' , 'translate(0px , 15%)' );
$('.button .modal-trigger').removeClass('modal-trigger');
});
$('.fa-close').click(function(){
$('.my-Modal').fadeOut().css('transform' , 'translate(0px , 5%)');
$('.button .modal-trigger').addClass('modal-trigger');
});
});


thank you for any help!

Answer

This won't work because your opening click removes the class you use to 'close' as well. Essentially, the following element you try to select doesn't exist anymore:

$('.button .modal-trigger').addClass('modal-trigger');

I'd go with a global variable that blocks all clicks when active, something like this:

$(document).ready(function(){

    var hasActiveModal = false;

    $('.modal-trigger').click(function(){
        if(!hasActiveModal) {
            hasActiveModal = true;
            var post_content = $(this).parent('.team-section').find('.my-Modal').fadeIn().css('transform' , 'translate(0px , 15%)' );
            return;
        }
    });
    $('.fa-close').click(function(){
        if(hasActiveModal) {
            hasActiveModal = false;
            $('.my-Modal').fadeOut().css('transform', 'translate(0px , 5%)');
            return;
        }
    });
});

This way you keep track of an active modal, and only allow modals to be opened when there's no open modal, and close them when there's a modal open.