Search code examples
javascriptjquerybuttonslidetoggle

jQuery button click function toggles both sections


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/


Solution

  • 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");
       });
    });