You're having some syntax errors in this code. First, I suggest you name the function arguments something other than this
because this
is a reserved keyword in JavaScript.
Secondly, I recommend consulting with W3School with such simple problems before reaching out, as most of the time, there is a simple solution :)
Here's a link that solves exactly the problem you're describing.
https://www.w3schools.com/howto/howto_js_collapsible.asp
And, here's an example and how you can achieve this:
let content = document.getElementById("content");
function handleClick() {
if (content.classList.contains("hide")) {
content.classList.remove("hide");
} else {
content.classList.add("hide");
}
}
.my-content {
display: block;
}
.my-content.hide {
display: none;
}
<button onclick="handleClick()">Toggle</button>
<div class="my-content" id="content">Hello, some content</div>
EDIT If you decide to introduce jQuery to your project, you can achieve it even with fever lines of code:
$("[data-collapse]").on('click', function () {
let target = $(this).data('collapse');
$(target).toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-collapse="#content">Clicker</button>
<div id="content">
My Content
</div>
This makes it abstract and reusable, even allowing you to do things like separate containers:
$("[data-collapse]").on('click', function () {
let target = $(this).data('collapse');
$(target).toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-collapse="#target1">Collapse #1</button>
<button data-collapse="#target2">Collapse #2</button>
<div id="target1">
<h1>I'm Target #1</h1>
</div>
<div id="target2">
<h1>I'm target #2</h1>
</div>