TaouBen
TaouBen

Reputation: 1315

How to scroll back to the top left using only Javascript?

My problem is simple: I have a div container, with a property of overflow:auto, in mobile I see the scroll bar because my elements are out of the container, I can scroll to the right or left. I want that when I click an item in the top right, it gets placed in the head of the list (unshift), and the container goes back to its default position where the scrollLeft is 0. What I am doing is :

myElement.scrollLeft = 0;

But it is not working. This is the whole code I have:

function showDetails(i) {

  // Important 
  cdiscountHeaderOptions.scrollLeft = 0;

  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
    let updatedData = data.filter(function (item) {
      return item.id - 1 !== i;
    });
    let selectedItem = data.filter(function (item) {
      return item.id - 1 === i;
    })[0];
    updatedData.unshift(selectedItem);
    renderData(updatedData);
  }

  detailsContainers.style.display = 'flex';

}

I tried also:

myElement.scrollTo(0,0); 

But I got an error: scrollTo is not a function.

Any help would be much appreciated.

Upvotes: 1

Views: 162

Answers (1)

Abdul
Abdul

Reputation: 73

What I would do is place an empty div at the top <div id="scrollToTop"></div> of your HTML page and then in your js code, you can simply say document.getElementById("scrollToTop").scrollIntoView();


UPDATED ANSWER

Try putting a div where you want to scroll, make it position absolute so it's at a specific position, then you can use the .scrollIntoView(); function


UPDATED ANSWER

window.scrollTo(0,0)

Upvotes: 1

Related Questions