questions

How to target a single div in a loop with jQuery?

Rate this post

I have this loop here that shows post data from a WordPress blog –

<?php foreach ( $product_posts as $post ) : setup_postdata( $post ); ?><div class="card-container">
    <div class="card-image">
        <figure>
            <a href="<?php the_permalink();?>"><?php the_post_thumbnail(); ?></a>
        </figure>
    </div>
    <div class="gallery-card-text">
        <h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2>
        <p><?php the_excerpt() ?></p>
    </div>
</div><?php endforeach; wp_reset_postdata(); ?>

Using this jQuery function –

$(".card-container").mouseenter(function () {
  $(".gallery-card-text").show();
  $(".card-image").hide();
});

It targets everything in the loop, so if you hover over 1 post it hides the image on all of them. I want to show/hide each div in the loop individually on mouse enter.

How can I do this?

 

✔️Solution:

Select the elements in the element you hovered.

$(".card-container").mouseenter(function () {
  var card = $(this);
  card.find(".gallery-card-text").show();
  car.find(".card-image").hide();
});

but why even use JavaScript when simple CSS can do it?

.card-container .gallery-card-text { display: none;} 
.card-container:hover .gallery-card-text { display: block;} 
.card-container .card-image { display: block;}
.card-container:hover .card-image { display: none;}

Leave a Reply

Your email address will not be published.

Back to top button