How to stop JS click event mirror to each other inside shortcodes placed on the same page?


I am building a simple shortcode which will display recent blog posts in a tabbed format. The tab is created using vanilla JS.

But the problem is – when two or more instances of the shortcode are used on the same page the JS display/hide action mirrors to each other meaning if I click on a tab in Shortcoe-1, the content of the Div inside the Shortcode-2 displays/hides and vice-versa. Any suggestion will be appreciated.

The WP shortcode code

function tab_posts(){
    <div class="tab-area">
    <ul id="alltabs" class="tab-heads" role="tablist">
    $categories = get_categories($args);
    foreach ($categories as $category) { ?>
     <li class="tab">
     <span onclick="clickOnTab(event, '<?php echo $category->slug;?>')"  class="catname" role="tab" data-toggle="tab"><?php echo $category->name;?></span>
    <?php } ?>
   <section class="content-body">
    foreach ($categories as $category) {
       <div class="pane" id="<?php echo $category->slug;?>">
       $cust_query = new WP_Query(array(
            'post_type' => 'post',
            'posts_per_page' => 5,
            'category_name' => $category->slug,
            'post_status' => 'publish'
        if ($cust_query->have_posts()):
          while ($cust_query->have_posts()):
        <div class="articles">
        <a class="image" href="<?php the_permalink(); ?>">
        <?php if (has_post_thumbnail()){
               the_post_thumbnail(array(550,350 ));
         } ?>
         </a><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    <?php endif;?>
    </div><!---tab pane-->
    </section><!---tab content-->
    </div><!--post tab pane-->
    $output = ob_get_clean();
    return $output;
add_shortcode('tab_posts', 'tab_posts');

The JS Code

function add_js(){
    ob_start(); ?>
    <script language="javascript" type="text/javascript">
    document.addEventListener("DOMContentLoaded", function () {
    var elems = document.getElementsByClassName('tab-heads');
    for (var i=0;i<elems.length;i+=1){
    elems[i].style.display = 'block';
    function clickOnTab(event, tabHead) {
        var i, tbody, tlinks;
        tbody = document.getElementsByClassName("pane");    
    for (i = 0; i < tbody.length; i++) {
        tbody[i].style.display = "none";
    tlinks = document.getElementsByClassName("catname");
        for (i = 0; i < tlinks.length; i++) {
    tlinks[i].className = tlinks[i].className.replace(" active", "");
  document.getElementById(tabHead).style.display = "block";
  event.currentTarget.className += " active";
echo ob_get_clean();
add_action('wp_footer', 'add_js');

KBD 1 month 2023-04-27T07:25:11-05:00 0 Answers 0 views 0

Leave an answer