1

My script should scroll down to an element 2 seconds after the page is loaded. It should work only on mobiles.

window.HTMLElement.prototype.scrollIntoView = function() {};

if (window.innerWidth < 500) {
  setTimeout(function() {
    let toogleElement = document.getElementsByClassName('eapps-google-maps-bar-toggle');
    toogleElement.scrollIntoView({
      behavior: 'smooth'
    });
  }, 2000);
}
#padding { height: 1000px; }
<div id="padding"></div>
<div class="eapps-google-maps-bar-toggle" eapps-link="barToggle">Foo</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • remove this ```window.HTMLElement.prototype.scrollIntoView = function() {};``` try again? – ikhvjs Jul 13 '21 at 10:35
  • Your `scrollIntoView()` function doesn't do anything...? The issue itself is because `getElementsByClassName` returns a collection, not a single element. You need to either loop through all of them, or access one by index directly, eg. `toogleElement[0].scrollIntoView(...` – Rory McCrossan Jul 13 '21 at 10:41
  • @RoryMcCrossan It removed error but script doesn't scroll to element (I have no console errors now) – Stack Stack Jul 13 '21 at 10:50
  • Right, because you defined the function, but it contains no logic to actually perform the scroll operation. – Rory McCrossan Jul 13 '21 at 10:51
  • I had this error https://stackoverflow.com/questions/53271193/typeerror-scrollintoview-is-not-a-function and solution of this question helped me so I made empty function. What should I write in it? – Stack Stack Jul 13 '21 at 11:02

1 Answers1

2

First, you need to remove window.HTMLElement.prototype.scrollIntoView = function() {}; because you don't need to define your own funciton.

Second, document.getElementsByClassName return HTML collection and you can access the element your want by using toogleElement[0].

Example below

if (window.innerWidth < 2000) {
  setTimeout(function() {
    let toogleElement = document.getElementsByClassName('eapps-google-maps-bar-toggle');
    toogleElement[0].scrollIntoView({
      behavior: 'smooth'
    });
  }, 2000);
}
#padding { height: 1000px; }
<div id="padding"></div>
<div class="eapps-google-maps-bar-toggle" eapps-link="barToggle">Foo</div>
ikhvjs
  • 5,316
  • 2
  • 13
  • 36