Toggle Multiple Divs on Click

Simple jQuery function to toggle between multiple containers on click.Filter links HTML:

<?php foreach($example as $post) : ?>

     <a href="#" data-toggle="#<?php echo $post->post_name; ?>"><?php the_title(); ?></a>

<?php endforeach; ?>

Target containers HTML:

<?php foreach($example as $post) : ?>

     <div id="<?php echo $post->post_name; ?>">
          <?php the_post_thumbnail(); ?>
     </div>

<?php endforeach; ?>

jQuery:

$("a[data-toggle]").on("click", function(e) {
  e.preventDefault();  // prevent navigating
  var selector = $(this).data("toggle");  // get corresponding selector from data-toggle
  $("div").hide();
  $(selector).show();
});

Source.

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.