0

I wanna to do scroll down to next div by pressing button on pure JS. But this code:

var hiddenElement = document.getElementById("box");
var btn = document.querySelector('.btn');

function handleButtonClick() {
   hiddenElement.scrollIntoView({block: "center", behavior: "smooth"});
}

btn.addEventListener('click', handleButtonClick);
.big {
   background: #ccc;
   height:100vh;
}

.btn {
   font-size: 14px;
}

.box {
   background: lightgreen;
   height: 100vh;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="script.js"></script>
    <title>Document</title>
</head>
<body>
     <button type="button" class="btn">Press</button>
    <div class="big"></div>
    <div id="box" class="box">Hidden Block</div>
</body>
</html>

didn't work when i opened it on my PC BUT it is working on JSfiddle. Why? Here is the link: jsfiddle

danilakds
  • 49
  • 5
  • 3
    jsFiddle wraps the script into onload function. You're executing this script before the body is parsed, the script can't find elements which don't exist yet. – Teemu Apr 20 '20 at 09:43
  • thanks. How can i fix this? – danilakds Apr 20 '20 at 09:45
  • 1
    Easiest... put your script before closing `

    `, or [read this](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event), for jQuery [read that](https://learn.jquery.com/using-jquery-core/document-ready/).

    – skobaljic Apr 20 '20 at 09:46

0 Answers0