In my code, you will see one button and a collapsible element. If the button is clicked then the page will be scroll to collapsible.
Is it possible to open collapsible after user clicks on the button? I thought about using viewport but then collapsible is going to open every time when it is in viewport.
Live editor: https://www.w3schools.com/code/tryit.asp?filename=GD9IMIC5QGTK
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active,
.collapsible:hover {
background-color: #555;
}
.content {
padding: 0 18px;
display: none;
overflow: hidden;
background-color: #f1f1f1;
}
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br><br>
<br>
<br>
<br><br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br><br>
<br>
<br>
<br><br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br><br>
<br>
<br>
<br><br>
<br>
<br>
<br>
<h2>Collapsibles</h2>
<div id="section2">
<p>A Collapsible:</p>
<button type="button" class="collapsible">Open Collapsible</button>
<div class="content" id="section2">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>