Search code examples
jquerytoggle

jquery toggle function for every element independently


I have many paragraphs and links, which should show/hide every paragraph independently.

<html>
    
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
            
        </script>
        <script>
            $(document).ready(function() {
                $(".showtext").hide();
                $("#click").click(function() {
                    $(".showtext").next("p").toggle();
                });
            });
        </script>
    </head>
    
    <body> 
        <a href="#" id="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p> <a href="#" class="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p> <a href="#" class="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p> <a href="#" class="click">Click for Show/hide</a>

        <p class="showtext">This text will show/hide</p>...etc dynamicly generated content

    </body>

</html>

EDIT:

Using $(this) does the job as it's pointing to the click event target.

click(function() { 
     $(this).toggle();
  });

Solution

  • here is working fiddle jsfiddle

      <p class="showtext">This text will show/hide</p> 
      <a href="#" class="click">Click for Show/hide</a><br/>
       $(".click").click(function() { 
         $(this).prev("p").toggle();
      });