Performing a function on two different elements without one affecting the other

Asked

Viewed 255 times

0

By clicking on the "See More" button, I need to make the div containing the text of the post expand, if it affects the div next to it. I tried to use toggleClass() but both open at the same time, or using an id only the first opens.

inserir a descrição da imagem aqui

js

jQuery(document).ready(function($) {
        $('#btn-open-post').click(function(event) {
          $('#post-collapse').toggleClass('post-collapse');
        });
      });

html

     <div class="blog">
        <h2 class="blog-latest">últimas do blog</h2>
           <div class="row">
              <?php echo do_shortcode( '[dois_ultimos]' ); ?>
           </div>
           <a href="/blog/" class="all-posts">ver todas</a>
        </div>
     </div>

php

function dois_ultimos_posts()
{
    global $post;

    $html = "";

    $dois_ultimos = new WP_Query( array(
         'post_type' => 'post',
         'posts_per_page' => 2
    ));

    if( $dois_ultimos->have_posts() ) : while( $dois_ultimos->have_posts() ) : $dois_ultimos->the_post();
             $html .= "<div class='col-md-6 post-home'  >";
         $html .= "<a href=\"" . get_permalink() . "\" class=\"post-permalink\"> <h3 class='post-title'>" . get_the_title() . " </h3>" . "</a>";
         $html .= "<p class='post-resume' id='post-collapse'>" . get_the_content() . "</p>";
         $html .= "<button id='btn-open-post' class='btn-open-post' id=\"" .get_the_ID() . "\" >Ver mais</button> ";
         $html .= "<div class='overlay-blog-post'>&nbsp;</div> ";
         $html .= "</div>";
    endwhile; endif;

    return $html;
}

1 answer

0


You can use the $(this) inside the click event call to pick up exactly the button that was clicked. From there you can find the "brother" element of the button, which would be the element #post-collapse, and then apply the toggleClass. Remember that if you put two equal ids on the same page, it will only be applied to one of the elements, because the value of the id attribute should be unique, try it with a class.

It would be something like this:

jQuery(document).ready(function($) {
  $('#btn-open-post').click(function(event) {
    $(this).prev('#post-collapse').toggleClass('post-collapse');
  });
});
  • Thank you very much, Simon!

  • It worked, Luan?

  • I made some adjustments but I used $(this) and now it’s working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.