简体   繁体   中英

How to scroll to an element using Javascript?

I'm trying to scroll to a particular card when a button is clicked. I'm using scrollIntoView for that, but its not working.

.js file :

document.getElementById("general_details_edit").addEventListener("click", function(){
  this.style.display = "none";
  document.getElementById("general_details_card").classList.remove("d-none");
  document.getElementById("general_details_card").classList.add("d-block");

  console.log("start");
  document.getElementById("general_details_card").scrollIntoView({behavior : 'smooth'});
  console.log("end")
  //not working

All of the other javascript code is working. How can i resolve this? I get the console messages "start" and "end" as well.

Also, when i run the same line from browser's console, it works.

EDIT :

Vijay's comment about using a timeout worked for me. But how i can wait for the element to load instead of waiting for a specific amount of time?

Current code :

const scroll = (el) => {
  setTimeout(function () { el.scrollIntoView( {behavior : 'smooth', block : 'end'}); }, 500);
}

One way would be to change the waiting time to zero milliseconds once the DOM is fully loaded.

var mSeconds = 500;

window.addEventListener('DOMContentLoaded', function(event) {
  mSeconds = 0;
});

const scroll = (el) => {
  setTimeout(function () { 
    el.scrollIntoView( {behavior : 'smooth', block : 'end'});
  }, mSeconds);
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM