Home > Enterprise >  How to prevent Read More/Read less button to jumping to the bottom?
How to prevent Read More/Read less button to jumping to the bottom?

Time:01-29

I've created a button for Read More/Read Less functionality but when I'm clicking on the show less it jumps to the bottom. Could you please tell me how to fix this?...it should go to the same position...I'm using oxygen builder (code for this [ https://codepen.io/nick7961/pen/qByYMXZ?editors=0010 ])

CodePudding user response:

One way of doing this is to grab the current scroll y value and divide it by the body height to get the scroll position as a percentage. You'll have to do this in the event listener, before changes are made. In my function, setScroll, you can get the new body height and multiply it by the percentage you grabbed earlier, to keep the scroll in the same relative position.

button.addEventListener('click', () => {
   const defaultValue = {
      element: arrowIcon,
      currentIcon: 'fa-chevron-down',
      newIcon: 'fa-chevron-up',
   };
  
  //show content  
  if (initial.showAllContent){

     showButton(buttonShowLess);
     showButton(buttonShowMore, false);

     content.classList.remove('gradientContent', 'maxContentHeight');
  }else{
    let relativeScroll = window.scrollY / document.body.clientHeight;

    showButton(buttonShowLess, false);
    showButton(buttonShowMore);

    defaultValue.currentIcon = 'fa-chevron-up';
    defaultValue.newIcon = 'fa-chevron-down';
    
    content.classList.add('gradientContent', 'maxContentHeight');
   
    setScroll(relativeScroll);
  }

  changeIcon(defaultValue);
  initial.showAllContent = !initial.showAllContent;  

});

function setScroll(relativeScroll) {
    let scrollValue = document.body.clientHeight * relativeScroll;
    window.scroll(0, scrollValue);
}

If you wanted to bounce the user back to the top, you could simply use:

window.scroll(0, 0);
  • Related