skip to Main Content

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


  1. 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. Use event.preventDefault() on clicking the "a tag".

    Login or Signup to reply.
  2. 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

    <button class="hide-link">Hide</button>
    

    and then update your JavaScript to select the buttons and handle the click events javasript:

    buttons = document.querySelectorAll(".hide-link")
            buttons.forEach(button => {
            button.addEventListener("click", function() {
            var content = this.nextElementSibling;
            content.style.display = content.style.display === "block" ? "none" : 
            "block";
             });
             });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search