skip to Main Content

I’m working on creating a button that sends a customer to the review field in Woocommerce using the scrollIntoView() function in Javascript.

I’m also working on hiding and showing the button when the reviews section comes into the viewport, and it’s working, but I want to take it a step further. The button as soon as the bottom of the browser hits the ID, which I don’t want. I want the button to show when the ID hits the top of the browser.

Here’s the basic HTML:

<button onClick="scrollToComment()" id="scroll-btn">Leave a Review</button>

<div id="reviews">

  //a bunch of reviews and comments go here

  <div id="review_form"></div>

</div>

Here is the JS:

window.addEventListener('scroll', function() {
    var element = document.querySelector('#reviews');
    var position = element.getBoundingClientRect();
    var scrollBtn = document.querySelector('#scroll-btn');

     if(position.top < window.innerHeight && position.bottom >= 0) {

        scrollBtn.style.display = 'block';
    }

    else {

        scrollBtn.style.display = 'none';

    }
});


function scrollToComment() {
    var button = document.querySelector('#review_form');
    button.scrollIntoView();

}

Any help would be appreciated!

2

Answers


  1. Why won’t you just test against the position of the frame when it hits the top ?

    // if position.top is between -1 and 1 it means it's on top
    // don't use '=== 0' to avoid pixel perfect glitches
    if (position.top > -1 && position.top < 1) {
      scrollBtn.style.display = 'block';
    }
    
    Login or Signup to reply.
  2. Use IntersectionObserver.

    var observer = new IntersectionObserver(callback, options);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search