Leave a unique javascript action for each "button"

Asked

Viewed 44 times

0

I am developing a javascript action to minimize and return a div to normal size,and it is working correctly, my only difficulty is to leave this action unique by pressing the "button". What is happening is when on a "button" the action is done on all Ivs. I will try to explain better with images.

inserir a descrição da imagem aqui

When I click on any of the buttons, the action is executed on everyone, I would like it to be just what I clicked.

inserir a descrição da imagem aqui

Code of the div:

<div class="row" style="margin-top: 20px;">
  <div class="col-md-12">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <button class="btn-minimize"></button>
        <img src="<?php echo $this->crud_model->get_image_url($post['created_by'], $post['created_by_' . $post['created_by']]);?>">
        <span class="name"><?= $creator->name ?> <small style="font-weight: 500;">/ publicado para: <b><?= $postClassName ?></b> na categoria <b><i class="<?= $category->icon ?>"></i> <?= $category->name ?></b></small></span>
        <span class="date"><?= $post['created_at'] ?></span>
      </div>
      <div class="panel-body">

Code for javascript/jquery:

$(".btn-minimize").click(function(){
$(this).toggleClass('btn-plus');
$(".panel-body").slideToggle();

});

1 answer

1


Hello,

Your code is working just as programmed, let’s note. Note that you give the slideToggle on all Divs with class panel-body, this includes the one you clicked and the one you did not click. To solve this, we will use the functions parent() and children() from jQuery to catch the class div panel-body, but only of the clicked element.

The Parent function is responsible for taking the parent element of the one in question in the DOM tree. Already the function Children, for catching the child of that element in the DOM tree. Let’s go to the code:

$(".btn-minimize").click(function(){
    $(this).toggleClass('btn-plus');

    // Volta até o elemento "panel-primary" e pega seu filho cuja classe seja "panel-body"
    $(this).parent().parent().children(".panel-body").slideToggle(); 
});



I hope I helped, hug!

  • Show!!! Thank you very much. It worked perfectly.

  • Smart the solution, thanks too.

Browser other questions tagged

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