Home > DeveloperSection > Forums > jQuery hide() hides what it shouldn't
Brad Pitt
Brad Pitt

Total Post:61

Points:429
Posted on    January-28-2015 10:21 PM

 ASP.Net JQuery  JavaScript 
Ratings:


 1 Reply(s)
 778  View(s)
Rate this:

I've got problem... jQuery should only hide divs under each h2, but it hides those h2 aswell... What should I do?

<!DOCTYPE>

<html>

<head>

    <title>Yolo</title>

    <script src="js/jquery-1.11.2.min.js"></script>

</head>

<body>

    <main>

        <div class="faq">

            <h2>Opcja 1</h2>

            <div class="answer">

                <p>Paragraph under option 1!</p>

            </div>

            <h2>Opcja 2</h2>

            <div class="answer">

                <p>Paragraph under option 2!</p>

            </div>

            <h2>Opcja 3</h2>

            <div class="answer">

                <p>Paragraph under option 3!</p>

            </div>

        </div>

    </main>

 

    <script src="js/jquery-1.11.2.min.js"></script>

    <script src="js/szkrypt.js"></script>

</body>

</html>

And there is jQuery. I did this via course in book, there it worked, maybe there was something with css classes there... Or maybe it was that, it was done under older version of jQuery.

$(document).ready(function() {

 $('.answer').hide();

 $('.faq h2').toggle(

        function() {

           $(this).next('.answer').slideDown();

        },

        function() {

           $(this).next('.answer').fadeOut();

      }

    );

}); 



Pawan Shukla
Pawan Shukla

Total Post:29

Points:203
Posted on    January-28-2015 10:45 PM

The toggle function you're trying to use is deprecated and removed !

The only toggle() function that is left in jQuery, is the one that toggles visibility, and that's why it's hiding everything.

$('.faq h2').toggle();

... hides every visible h2 element, and shows every hidden h2 element

You'll have to create your own toggle

$('.answer').hide();

$('.faq h2').on('click', function() {

    var flag = $(this).data('flag');

 

    if ( !flag ) {

       $(this).next('.answer').slideDown();

    } else {

      $(this).next('.answer').fadeOut();

    }

 

    $(this).data('flag', !flag);

});

Also, remove the script tag that is loading jQuery in the head, once is enough ! 


Don't want to miss updates? Please click the below button!

Follow MindStick