I want to toggle the content class independently when I click the collapsible class button associated with it. I read briefly on using this in event handlers. The way I’ve used it so far, I end up toggling the collapsible class (i.e the button) instead.
JavaScript
x
53
53
1
<head>
2
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
4
<title></title>
5
<style>
6
.collapsible {
7
background-color: #777;
8
color: white;
9
cursor: pointer;
10
padding: 18px;
11
width: 100%;
12
border: none;
13
text-align: left;
14
outline: none;
15
font-size: 15px;
16
}
17
18
.active, .collapsible:hover {
19
background-color: #555;
20
}
21
22
.content {
23
padding: 0 18px;
24
overflow: hidden;
25
display: none;
26
background-color: #f1f1f1;
27
}
28
</style>
29
<script type="text/javascript" charset="utf-8">
30
$(document).ready(function(){
31
$(".collapsible").on("click", function(){
32
$(".content").toggle();
33
});
34
});
35
</script>
36
</head>
37
38
<body>
39
<button type="button" class="collapsible">Open Section 1</button>
40
<div class="content contentDisp">
41
<p>Hello There.</p>
42
</div>
43
<button type="button" class="collapsible">Open Section 2</button>
44
<div class="content contentDisp">
45
<p>Hello there.</p>
46
</div>
47
<button type="button" class="collapsible">Open Section 3</button>
48
<div class="content contentDisp">
49
<p>Hello there.</p>
50
</div>
51
52
</body>
53
This is close to what I want but instead of toggling the button I want to toggle the div when I click the button.
JavaScript
1
8
1
<script type="text/javascript" charset="utf-8">
2
$(document).ready(function(){
3
$(".collapsible").on("click", function(){
4
$("this").toggle();
5
});
6
});
7
</script>
8
Advertisement
Answer
You can use this
in conjunction with next()
by specifying the class name of the button.
JavaScript
1
5
1
$(document).ready(function(){
2
$(".collapsible").on("click", function(){
3
$(this).next('.content').toggle();
4
});
5
});
JavaScript
1
22
22
1
.collapsible {
2
background-color: #777;
3
color: white;
4
cursor: pointer;
5
padding: 18px;
6
width: 100%;
7
border: none;
8
text-align: left;
9
outline: none;
10
font-size: 15px;
11
}
12
13
.active, .collapsible:hover {
14
background-color: #555;
15
}
16
17
.content {
18
padding: 0 18px;
19
overflow: hidden;
20
display: none;
21
background-color: #f1f1f1;
22
}
JavaScript
1
17
17
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<body>
4
<button type="button" class="collapsible">Open Section 1</button>
5
<div class="content contentDisp">
6
<p>Hello There.</p>
7
</div>
8
<button type="button" class="collapsible">Open Section 2</button>
9
<div class="content contentDisp">
10
<p>Hello there.</p>
11
</div>
12
<button type="button" class="collapsible">Open Section 3</button>
13
<div class="content contentDisp">
14
<p>Hello there.</p>
15
</div>
16
17
</body>