Search code examples
javascripthtmlcssshow-hide

show/hide multiple hide buttons


is it possible to make this show/hide script work with multiple hide buttons or something similar? id="cv_cont should stay visible by default.

HTML

<button id="show_cv">Show</button>
<button id="hide_cv">Hide 1</button>
<button id="hide_cv">Hide 2</button>
<button id="hide_cv">Hide 3</button>
<button id="hide_cv">Hide 4</button>
<div id="cv_cont">Content Visible</div>

JavaScript

$("#hide_cv").click(function() {
    $("#cv_cont").hide();
});

$("#show_cv").click(function() {
    $("#cv_cont").show();
});

Original Location of the script. jQuery - failed show/hide buttons


Solution

  • The first problem here is all the hide buttons have the same ID's value, you can fix that by give them the same class's value and call it on the JavaScript code.
    The correct code will like this :

    <!DOCTYPE html>
    <html lang="fr">
    <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      <meta charset="utf-8">
      <title>Titre de la page</title>
      <link rel="stylesheet" href="style.css">
      <script src="script.js"></script>
    </head>
    <body>
      <button class="show_cv">Show</button>
    <button class="hide_cv">Hide 1</button>
    <button class="hide_cv">Hide 2</button>
    <button class="hide_cv">Hide 3</button>
    <button class="hide_cv">Hide 4</button>
    <div id="cv_cont">Content Visible</div>
      <script>
        $(".hide_cv").click(function() {
        $("#cv_cont").hide();
    });
    
    $(".show_cv").click(function() {
        $("#cv_cont").show();
    });
      </script>
    </body>
    </html>