Set a fixed element and scroll another - jQuery

jQueryWeb DevelopmentFront End Technology

Let’s say the following is our fixed element div −

<div class="fixedElement">
   Fixed
</div>

The CSS style to fix the above element −

.fixedElement {
   position: fixed;
   background-color: skyblue;
   top: 0;
   left: 0;
   right: 0;
}

Following is our element, which will be scrolled −

<div id="scrollDemo">
   David Miller
</div>

Now, use the window.scrollTo().

Example

Let us see the complete code −

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
   .fixedElement {
      position: fixed;
      background-color: skyblue;
      top: 0;
      left: 0;
      right: 0;
   }
  html,
  body {
      height: 1000px;
   }
   #scrollDemo {
      position: relative;
      top: 500px;
   }
</style>
<body>
   <div class="fixedElement">
      Fixed
   </div>
   <div id="scrollDemo">
      David Miller
   </div>
</body>
<script>
   window.scrollTo(0, document.getElementById('scrollDemo').offsetTop - document.getElementsByClassName('fixedElement')[0].offsetHeight);
</script>
</html>

This will produce the following output. The element is fixed above and other is visible on scroll as shown below −

raja
Published on 09-Nov-2020 12:00:18
Advertisements