0

I've read through the similar questions but I can't find an answer. I have the following jquery code for a sliding panel. I want to use classes instead of an id, but nothing seems to work:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script> 
$(document).ready(function(){
  $("#flip").click(function(){
    $("#panel").slideToggle("slow");
  });
});
</script>
<style> 
#flip {
  padding: 5px;
  text-align: center;
  background-color: #e5eecc;
  border: solid 1px #c3c3c3;
}

#panel {
  padding: 50px;
  display: none;
}
</style>


<body>
<div id="flip">Click to slide the panel down or up</div>
<div id="panel">Hello world!</div>
</body>
1
  • I believe the short way to answer is $(".className"); Commented Jan 2, 2020 at 4:43

2 Answers 2

2

First add class attribute in html element as like class="flip"

Now you can use class in jquery using dot (.) so you have to use as $(".flip")

Also you can give css with class in same way

See below answer.

$(document).ready(function(){
  $(".flip").click(function(){
    $(".panel").slideToggle("slow");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<style> 
.flip {
  padding: 5px;
  text-align: center;
  background-color: #e5eecc;
  border: solid 1px #c3c3c3;
}

.panel {
  padding: 50px;
  display: none;
}
</style>


<body>
<div id="flip" class="flip">Click to slide the panel down or up</div>
<div id="panel" class="panel">Hello world!</div>
</body>

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry I think I wasn't clear: I want the style associated with the IDs as well, is that possible? Because I can't reuse the IDs. My goal is to have the script function and associated style applied to multiple DIVs.
Weird it wasn't working for me earlier. I think I must have accidentally skipped a step. Thanks though!
0

Use next with class to slideToggle your div like below.

$(".flip").click(function() {
  $(this).next(".panel").slideToggle("slow");
});
.flip {
  padding: 5px;
  text-align: center;
  background-color: #e5eecc;
  border: solid 1px #c3c3c3;
}

.panel {
  padding: 50px;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div class="flip">Click to slide the panel down or up</div>
  <div class="panel">Hello world!</div>
  <div class="flip">Click to slide the panel down or up</div>
  <div class="panel">Hello world!</div>
</body>

Using next with this works with multi pal div. Catching class for toggle break your code for multi pal div.

1 Comment

Thanks I'll research this more, I'm new to coding. Much appreciated!

Your Answer

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