skip to Main Content

Every time the like button is clicked, the webpage scrolls to the top. Any ideas how to stop this from happening. The code is ,

<a href="/likeComment/{{../post._id}}/{{_id}}"> 
          <i class="fa-solid fa-thumbs-up"></i>
          {{likes.length}} Like
        </a> 

The like is registered and the number of likes is incremented. However, it jumps to the top of the webpage every time it is clicked. I want the webpage to stay where it is when the like is clicked.

2

Answers


  1. Chosen as BEST ANSWER

    Ok I solved this by adding onclick to the element

    <a href="/likeComment/{{../post._id}}/{{_id}}" id="test" onclick="updateLikes(event, '{{../post._id}}', '{{_id}}')"> 
          <i class="fa-solid fa-thumbs-up"></i>
          {{likes.length}} Like
        </a>
    

    then using AJAX to update the like count.

      // Prevent the default link behavior
      event.preventDefault();
    
    
      const url = `/likeComment/${postId}/${commentId}`;
    
      var xhr = new XMLHttpRequest();
    
     
      xhr.open('GET', url, true);
    
    
      xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          // The like count was successfully updated on the server
          // Now, reload the page to reflect the new like count
          location.reload();
        }
      };
    
    
      xhr.send();
    }`
    
    
    
     
    

  2. It’s the default behavior of an anchor <a> element with an href. When you click on it can cause the page to jump to the top.

    Changing it to: <button> or <div> should resolve the issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search