1

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);
}
6
  • Hi. Welcome to SO! Please visit How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output, preferably in a Stacksnippet Commented Sep 7, 2021 at 7:07
  • Try to run the code after some timeout after adding the 'd-block' class to element. the code ran before the element actually loaded into the dom Commented Sep 7, 2021 at 7:08
  • Does this answer your question? How do I scroll to an element using JavaScript? Commented Sep 7, 2021 at 7:12
  • Take a look at this issue: stackoverflow.com/questions/5007530/… Commented Sep 7, 2021 at 7:12
  • @VijayKumawat thanks for that. Setting a timeout worked for me, but currently the wait length is hardcoded. How can I make it such that the timeout will wait until the element is loaded in the dom? Commented Sep 7, 2021 at 7:56

1 Answer 1

1

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);
  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.