Regular User
Regular User

Reputation: 511

scrollIntoView is not a function JS

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>

Upvotes: 1

Views: 2971

Answers (1)

ikhvjs
ikhvjs

Reputation: 5947

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>

Upvotes: 2

Related Questions