I’m coding a ‘read more’ hyperlink in a box for it then to expand out with further text, it works but whenever you click the ‘read more’ or ‘hide’ button the whole page scrolls to the top, how do i fix this?
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
var coll = document.getElementsByClassName("coll3");
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";
}
return false;
});
}
</script>
<style>
a {
font-size: 16px;
}
.hide-link {
font-size: 16px;
}
</style>
<a href="#" class="hide-link">Hide</a>
</div>
2
Answers
Please give more context to the problem or code. The problem can be
the
href="#"
in "a tag" makes the page scrolls to the top of the page. Useevent.preventDefault()
on clicking the "a tag".The problem is when you click on a link with href="#", it navigates to the top of the page by default.
So maybe you can try it with
and then update your JavaScript to select the buttons and handle the click events javasript: