S
S
sasha_jarvi2019-05-16 12:32:24
JavaScript
sasha_jarvi, 2019-05-16 12:32:24

How to perform a "sticky sidebar" with the scroll stopping on a certain element and returning the scroll when scrolling through this element?

There is the following code:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
</head>
<body>
  <header>Header</header>
  <main>
    <div class="container">
      <div class="row justify-content-around">
        <div class="col-12 col-sm-8 col-md-6 col-lg-5 content-1">Content 1</div>
    <div class="col-12 col-sm-8 col-md-6 col-lg-5" id="sidebar">Sidebar</div>
        <div class="col-12" id="large-content-block">Large content</div>
        <div class="col-12 col-sm-8 col-md-6 col-lg-5 content-2">Content 2</div>
        <div class="col-lg-5"></div>
      </div>
    </div>
   </main>
  <footer>Footer</footer>
</body>
</html>


CSS:

body {
  color: #fff;
}

header, footer {
  background-color: green;
  padding: 50px 25px 50px;
}

.content-1, .content-2 {
  background-color: lightblue;
  padding: 50px 20px 50px;
  height: 800px;
  margin-top: 30px;
  margin-bottom: 30px;
}

#sidebar {
  background-color: lightblue;
  padding: 50px 25px 50px;
  height: 200px;
  margin-top: 30px;
  margin-bottom: 30px;
}

#large-content-block {
  background-color: red;
  padding: 50px 25px 50px;
  height: 200px;
  margin-bottom: 30px;
}


You need to do the following:

  1. Make #sidebar sticky, and the scroll of this element should stop when it reaches #large-content-block.
  2. After we scroll the #large-content-block element, the #sidebar should scroll again. The scroll should stop when it reaches the footer.


How can this functionality be implemented?
Codepen: https://codepen.io/anon/pen/byqQyp

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-05-16
@sasha_jarvi

here on the first question
https://codepen.io/anon/pen/OYpYZE
(I had to slightly change the html)
about the second question, "we will scroll the #large-content-block element" starting from what moment?
to make the sidebar appear below the red box when scrolled to the top of the red box?
I think it will be necessary to catch this moment through js event scroll, and move the sidebar block from one place to another

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question