Home > Enterprise >  How to minimize and maximize cards uniquely using jQuery
How to minimize and maximize cards uniquely using jQuery

Time:09-16

I want to create the functionality of minimizing and maximizing the cards individually.

For example I have 10 card divs, each having one button to hide/show the div. I have tried from the w3School's tutorial but I am only able to do it for one card not for all other cards individually.

This code is working fine for one div at a time how can I make it dynamic for all the divs? For unique id of div's I am having createdTime. Please help

$(document).ready(function(event) {
  $(".toogleCard").click(function() {
    var status = $(event.currentTarget).attr('id');
    if ($(this).html() == "-") {
      $(this).html(" ");
    } else {
      $(this).html("-");
    }
    $("status").slideToggle();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toogleCard" id="uniqueid1">-</button>
<p id="uniqueid1">This is a paragraph.</p>

<button class="toogleCard" id="uniqueid1">-</button>
<p id="uniqueid2">This is a paragraph.</p>

<button class="toogleCard" id="uniqueid1">-</button>
<p id="uniqueid3">This is a paragraph.</p>

CodePudding user response:

The technique you're looking for is known as 'Don't Repeat Yourself', or DRY.

To achieve it in this case you can make the HTML structures identical, and therefore infinitely repeatable, by using the same class on the button and p elements. Then in the JS you can use jQuery's DOM traversal methods, in this case next(), to relate the element which raised the click event to the required target element to be shown/hidden.

Try this:

jQuery($ => {
  $(".toggleCard").click(e => {
    let $toggle = $(e.target);
    $toggle.text((i, t) => t === '-' ? ' ' : '-');
    $toggle.next('.para').slideToggle();
  });
});
.toggleCard { display: block; }
.para { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toggleCard">-</button>
<p class="para">This is a paragraph.</p>

<button class="toggleCard">-</button>
<p class="para">This is a paragraph.</p>

<button class="toggleCard">-</button>
<p class="para">This is a paragraph.</p>

  • Related