Question

I am new to jQuery. I am trying to make it so that flash cards flip when clicked on.

jQuery Code

$(document).ready(function () {
    $("div").click(function () {
        $(this).next().toggleClass("hidden");
    });
});

relevant PHP code

#returns the HTML out for the cards based on the two input arrays
            function get_cards_html($terms, $answers) {
                $number_of_cards = count($terms);
                for($i = 0; $i < $number_of_cards; $i++) {
                ?>
                <div class="card">
                    <p class="term"><?php echo $terms[$i]?></p>
                    <p class="answer" class="hidden"><?php echo $answers[$i]?></p>
                </div>
                <?php
                }
            }
        ?>

Relevant CSS code

.hidden {
    display: none;
}

As it is right now my code acts on the next div when clicked on rather then on the paragraphs inside the div. My goal is to get the text inside the divs to alternate between being displayed. I thought a good way to do this was to apply a hidden class and use the toggleClass function but it does not seem to working as I expected it to.

Was it helpful?

Solution

Ohh there is more than 1 way to do it. I will suggest as below. Try if it fits your scenario.

$(".card .term").click(function () {
    $(this).next().toggle();
});

OTHER TIPS

Try

<div class="card">
    <p class="term">t1</p>
    <p class="answer hidden">a1</p><!-- you had 2 class attributes here, merge them to 1 with space as a separator-->
</div>

then

jQuery(function ($) {
    //target the term element instead of card then toggle the next element's class
    $("div.card .term").click(function () {
        $(this).next().toggleClass("hidden");
    });
});

Demo: Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top