text show and hide with button php/js

160 Views Asked by At

How can I apply the multiple texts? With a text it works:

<dl>
    <dt>
        <img class="empfehlung-bild" style="max-width: 300px; height: auto; float: left; margin-right: 15px; margin-bottom: 15px;" src="<?php echo $bild; ?>" />
        <h1><?php echo $title; ?></h1>
        <p>
            <?php echo $text; ?>
        </p><br/>
        <button id="<?php echo $i; ?>" style="float:right;">Details</button><br/><br/>
    </dt>
    <dd style="float:left;">
        <h2><?php echo $secret_title; ?></h2>
        <button id="<?php echo $i; ?>" style="float:right;">X</button>
        <p>
            <?php echo $secret_text; ?>
        </p>
    </dd>
</dl>

The script:

<script type="text/javascript">
    $(document).ready(function() {
        $("button").click(function() {
            $("dd").slideToggle("slow");
        });
    });
</script>

dd style is display: none. $i is a counter (while)

The problem is, if I have more than one dl, it closes and opens all of them.

1

There are 1 best solutions below

3
On BEST ANSWER

This will select and toggle all instances of dd on the entire page.

$("button").click(function () {
  $("dd").slideToggle("slow");
});

This will select and toggle the intended instance of dd, closest to the button you pressed.

$("button").click(function () {
  $(this).closest('dl').find('dd').slideToggle("slow");
});

It takes the button you actually pressed with ($this), finds the parent dl with .closest('dl') and then looks for the dd inside that instance of dl with .find('dd').