Search code examples
jqueryhtmlhidden

hide active and show one using jquery css


I'm trying to create an auto hide option that allows users to click on links to reveal/display items, but I want to be able to automatically close active displays when the users choose a different subject.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   
    $("#myp-0", ).click(function(){
        $("#loose-0").toggle(600);
    });
});
$(document).ready(function(){
   
    $("#myp-1", ).click(function(){
        $("#loose-1").toggle(600);
    });
});
$(document).ready(function(){
   
    $("#myp-2", ).click(function(){
        $("#loose-2").toggle(600);
    });
});
</script>
</head>
<body>
<p id="myp-0">click</p>
<p id="loose-0"> I will disappear.</p>
<p id="myp-1">click</p>
<p id="loose-1"> I will disappear.</p>
<p id="myp-2">click</p>
<p id="loose-2">I will disappear.</p>

</body>
</html>

So, the example shows links that displays the content. How do I hide the content until a link is clicked and when I tap a link, show the content, but make the jquery check to see if any other links are active and close them automatically?


Solution

  • Use wild card with hide method and next to toggle.

    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script>
        $(document).ready(function() {
          $('p[id*="myp"]').click(function() {
            $('p[id*="loose"]').hide();
            $(this).next('p').toggle(600);
          });
        });
      </script>
    </head>
    
    <body>
      <p id="myp-0">click</p>
      <p id="loose-0">If you click on me, I will disappear.</p>
      <p id="myp-1">click</p>
      <p id="loose-1">If you click on me, I will disappear.</p>
      <p id="myp-2">click</p>
      <p id="loose-2">If you click on me, I will disappear.</p>
    
    </body>
    
    </html>