scrollIntoView

by Kim Ara

HTML

<div class="sample" id="sample1">
  <h5>박스 요소를 기준으로 움직이는 예제입니다.</h5>

  <!-- ex -->
  <div class="jsample">
    <div class="box">
      <span>이 박스를 기준으로 움직입니다.</span>
    </div>
  </div>
  <!-- ex -->

  <div class="sampleBtn">
    <a href="#" class="btn1">scrollIntoView()</a>
    <a href="#" class="btn2">scrollIntoView(false)</a>
    <a href="#" class="btn3">scrollIntoView({block: "start"})</a>
    <a href="#" class="btn4">scrollIntoView({behavior: "smooth", block: "end"})</a>
    <a href="#" class="btn5">scrollIntoView({behavior: "smooth", block: "center"})</a>
    <a href="#" class="btn6">scrollIntoView({behavior: "smooth", block: "start"})</a>
  </div>
</div>

CSS

.sample {
  text-align: center;
  height: 1000px;
}

.jsample {
  padding-top: 200px;
}

.sample .box {
  margin: 20px auto;
  width: 400px;
  height: 200px;
  background-color: #ddedff;
  border: 1px solid #4390E1;
  color: #4390E1;
  padding: 20px;
  position: relative;
  overflow: auto;
}

.sample .small-box {
  width: 500px;
  height: 260px;
  background-color: #A2CBFA;
  border: 1px dashed #4390E1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sample .sampleBtn {
  border-bottom: 1px solid #e6e6e6;
  padding: 20px 20px 10px 20px;
}

.sample .sampleBtn a {
  border: 1px solid #e6e6e6;
  border-radius: 100px;
  white-space: nowrap;
  padding: 10px 20px;
  display: inline-block;
  margin-bottom: 10px;
  transition: all 0.2s
}

.sample .sampleBtn a:hover {
  border-color: #FF4B4B;
}

JavaScript

document.querySelector(".sampleBtn .btn1").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".sample .box").scrollIntoView();
});

document.querySelector(".sampleBtn .btn2").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".sample .box").scrollIntoView(false);
});

document.querySelector(".sampleBtn .btn3").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".sample .box").scrollIntoView({block: "start"});
});

document.querySelector(".sampleBtn .btn4").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".sample .box").scrollIntoView({behavior: "smooth", block: "end"});
});

document.querySelector(".sampleBtn .btn5").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".sample .box").scrollIntoView({behavior: "smooth", block: "center"});
});

document.querySelector(".sampleBtn .btn6").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".sample .box").scrollIntoView({behavior: "smooth", block: "start"});
});