Search code examples
javascriptjqueryhtmlcssmagento2.2

How to scroll the page body to the specific location by element id in Magento2 CMS?


I want to open a product tab on the product page with a click of an anchor tag in Magento2. The Magento2 CMS version is 2.2.5, below is the code:

require([
  'jquery'
], function($) {
  $(document).ready(function() {
    $('.mor-link').on('click', function(event) {
      // Prevent URL change
      console.log('clicked');
      event.preventDefault();
      // `this` is the clicked <a> tag
      $('[data-toggle="switch"][href="' + this.hash + '"]').trigger('click');
    });
  });
});
<a id="read_more" class="mor-link" href="#new3.tab">Read More...</a>

.

So here I want to open the FAQ's product tab with scroll down the page body. You can check on my website as well: https://example.com/staging/tinted-sunscreen.html My script is working fine to open the FAQ's tab but the page body is not scrolling down to the desired element location. Please let me know, how I can achieve this thing. I just want to open FAQ's tab after the click on the 'Readmore...' link and page body jump to that place.

Thanks in Advance, please help.


Solution

  • You can use the scrollIntoView method inside your click handler:

    $('.mor-link').on('click', function(event) {
      event.preventDefault();
      $('[data-toggle="switch"][href="' + this.hash + '"]').trigger('click');
      document.getElementById("tab-label-new3.tab").scrollIntoView();
    });