david-s
3/26/2019 - 3:07 PM

JavaScript Scroll To ID - using ES6 Classes

/**
* Scroll functionality
* @function
*/
class Scroll {
  /**
  * Constructor.
  * @param {Element} scrollBlock - The scroll to element
  */
  constructor(scrollBlock) {
    this.scrollComponent = scrollBlock.getAttribute('href');
    scrollBlock.addEventListener('click', event => this.animateToComponent(event));
  }

  /**
  * Animate scroll to element
  * @param {event} event - Prevents default action of click event
  */
  animateToComponent(event) {
    event.preventDefault();
    $('html, body').animate({scrollTop: $(this.scrollComponent).offset().top}, 500); // Using jQuery here for IE support
  }
}

/**
 * Scrolls to element on page.
 *
 */
export class ScrollTo {
  /**
   * Constructor.
   *
   */
  constructor() {
    this.initialisedScrollElements = [];
    const scrollButtons = document.querySelectorAll('.js-scroll-button');

    for (let i = 0; i < scrollButtons.length; i++) {
      const scrollButton = scrollButtons[i];
      this.initialisedScrollElements.push(new Scroll(scrollButton));
    }
  }
}