user11730319
user11730319

Reputation:

How to use class instead of ID for jquery function

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>

Upvotes: 0

Views: 994

Answers (2)

4b0
4b0

Reputation: 22323

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.

Upvotes: 0

Devsi Odedra
Devsi Odedra

Reputation: 5322

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>

Upvotes: 2

Related Questions