-1

When I click one of these two buttons it toggles both the #hide and the .contact p at the same time. I tried adding a class to the ("button") selector.

$(document).ready(function(){
  $("#hide").hide();
    $("button").click(function(){
        $("#hide").slideToggle("display");
   });

  $("#contact p").hide();
    $("button").click(function(){
        $("#contact p").slideToggle("display");
   });
});

https://codepen.io/Shalise/pen/BmmEQJ/

2
  • 1
    add all relevant code in OP use <> instead of an external link
    – guradio
    Nov 29, 2017 at 5:29
  • Yes, it toggles both, because you've written it like that.
    – 31piy
    Nov 29, 2017 at 5:38

4 Answers 4

0

You're querying $("button") which grabs an element. You will either want to query a class or an id. For example I added an id of #btn1 and #btn2 to two buttons respectively. Below is modified JQuery:

 $(document).ready(function(){
  $("#hide").hide();
    $("#btn1").click(function(){
        $("#hide").slideToggle("display");
   });

  $("#contact p").hide();
    $("#btn2").click(function(){
        $("#contact p").slideToggle("display");
   });
});
1
  • This fixed it, thank you! I feel like I tried this but probably had a small error that led me to believe it wasn't going to work.
    – Shalise
    Nov 30, 2017 at 6:23
0

use separate class or id in every button. ex: HTML

<button class="button-1">First</button>
<button class="button-2">Second</button>

JS:

$(document).ready(function(){
  $("#hide").hide();
  $("button.button-1").click(function(){
      $("#hide").slideToggle("display");
  });

  $("#contact p").hide();
  $("button.button-2").click(function(){
     $("#contact p").slideToggle("display");
  });
});
0
  1. If you want to hide those elements, you can add a class for example a class="hidden" and style it display: none instead of using jQuery hide method.

  2. You're using a general button selector, if you have a specific id for each of those buttons, you can target them specifically.

  3. Here is a good resource for using slideToggle: http://api.jquery.com/slidetoggle/

0

You add both functions to all buttons. That's why both functions where triggerd when you click any button.

As you say: Add a class or a id to the buttons to tell them apart and only add one function to each button

HTML

<button id="first">First</button>
<button id="second">Second</button>

JS

$(document).ready(function(){
  $("#hide").hide();
  $("button#first").click(function(){
    $("#hide").slideToggle("display");
  });

  $("#contact p").hide();
  $("button#second").click(function(){
    $("#contact p").slideToggle("display");
  });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.