Tips for keeping a div element at the top of the page

I am looking to have a div stick to the top of the page when someone scrolls down

When the page is scrolled, the green div with class stickdiv should automatically stick to the top

var left = document.getElementsByClassName("stickdiv");

for( var i = 0;i<left.length;i++){
var stop = (left[0].offsetTop);

window.onscroll = function (e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    if (scrollTop >= stop) {
     left.className += " stick"; //adding a class name
    } else {
        className = '';
    }

}
}

Why does adding the stick class to the div not work? - https://jsfiddle.net/kzk5qab2/1/

I want the div to stick at the top like the yellow div in this example - http://jsfiddle.net/qc4NR/

Answer №1

You've entered the array of left elements, but forgot to specify the array index when attempting to apply the class name to the element.

var left = document.getElementsByClassName("stickdiv");

for (var i = 0; i < left.length; i++) {
  var stop = (left[0].offsetTop);

  window.onscroll = function(e) {
    var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    
    if (scrollTop >= stop) {
      left[0].classList.add('stick'); //applying a class name
    } else {
      left[0].classList.remove('stick');
    }
  }
}
.stickdiv {
  height: 50vh!important;
  width: 100vh!important;
  background-color: green!important;
}
.stick {
  position: fixed;
  top: 0;
  margin: 0 0
}
#right {
  float: right;
  width: 100px;
  height: 1000px;
  background: red;
}
.des {
  height: 300px;
  width: 100%;
  background-color: #000;
}
<div class="des"></div>
<div class="stickdiv"></div>
<div id="right"></div>

If you directly select the item, you don't even need to loop through, as shown below:

var left = document.querySelector(".stickdiv");
var stop = (left.offsetTop);

window.onscroll = function(e) {
  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

  if (scrollTop >= stop) {
    left.classList.add('stick'); //applying a class name
  } else {
    left.classList.remove('stick');
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to effectively manage multiple asynchronous operations while retrieving emails and attachments using IMAP and JavaScript

Currently, I am utilizing the IMAP library along with JavaScript to retrieve emails from a server. This is my approach: Retrieve emails based on email address, subject, and a specified time frame. Determine the total number of emails received. For each e ...

Selenium's xpath feature is designed to target only the elements that are currently visible

When using Selenium xpath, it only matches visible elements on the HTML page. Even though there are many other elements present but not visible, the xpath will only return those that are currently visible. This is in contrast to checking the xpath in the ...

Troubleshooting Issue with Public File Serving in ExpressJS Deployment (NodeJS/Express)

The directory structure of my project is organized as follows: my_project server.js app.js | | - public | ----------| images | javascripts | stylesheets | -------------- imgs ---scripts.js ---styles.css | | - routes | | - views | ...

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

Is there a way to adjust the theme color in _variables.scss by recompiling Bootstrap while working with Angular and CSS?

I've been trying to update the primary color in my Angular project by editing the SCSS file node_modules/bootstrap/scss/_variables.scss. However, after stopping npm and running the front-end again, I noticed that the changes I made are not reflected i ...

Explain the mechanics of the calculator code operating by inputting numerical values in a string format

Recently, I attempted to create a calculator in JavaScript and encountered a requirement to place the button values within single quotes as if they were strings. It's fascinating how these string values can work alongside operators to produce the desi ...

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...

Uploading Files Using the Dropbox API Version 2

Before, I integrated the Dropbox API V1 into my web application to upload files to my personal Dropbox account. The app was configured to use only one specific dropbox account for file uploads. Previous Process: I registered an app on the dropbox develo ...

Experience the smooth CSS3 transition effects on iOS devices such as iPhones and iPads. Elevate the appearance of DOM objects with

I have a basic image contained within a div tag. I use JavaScript to add a transition effect to the div element: <div style="transition: opacity 0.8s linear; opacity: 0.5;"><img src="..." /></div> At the end of the transition duration ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

Incorporating server-side rendered components into a Vue.js parent component

I have a server-side rendered page that includes information about "orders" and a root Vue object initialized as the "parent object." Is it feasible to assign the rendered HTML orders as children of that parent Vue object? Vue.js is known for its dynamic ...

Preventing Repeated Clicks in AngularJS

Looking for a better approach to handle double clicks in AngularJS other than using ng-disabled. I have a solution to disable double/multi-click functionality on button click and re-enable it after completing an ajax process. Any suggestions? When our cod ...

Can the color of a highchart graph be altered simply by clicking on the line?

Greetings! I am currently working on plotting a graph using highchart and I was wondering if there is a way to allow users to change the color of the plotted line by simply clicking on it and selecting a color from a color picker tool. I do not want to lim ...

The Guide to Utilizing Autonomous Models in Directive

Hey there! I have a question regarding a radio button directive. In this directive, I pass a model for the collection that will be set to the selected radio button. var app = ChartsModules.getInstance().getModule("amkaiCharts.directives"); ...

Modify dates on constant URL and run the link

I've got a link that looks like this: Is it possible to create an HTML form with two input date fields and merge them into a single link similar to the one above? I want to select dateFrom and dateTo separately, then click GO to access the link. I&a ...

Unexpected behavior with ng-show binding

I am currently working on implementing a toggle feature in my form. The idea is that when I click one button, it should display a section with the corresponding name, and hide the other sections. However, I am facing an issue related to scope. When I do no ...

How can Angular be used to dynamically show or hide an element based on its height?

Is there a way in Angular to display a "Read More" link once the height of a paragraph reaches 200px? I'm looking for an elegant solution. Here are my elements: <section class="mynotes" ng-if="MyController.mynotes"> <p ng-bind="MyController ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; Interestingly, when accessing the ...

Utilizing Firebase messaging onMessage function is exclusively enabled within a window environment

Incorporating Firebase Cloud Messaging into my project allowed me to send and receive push notifications successfully. While I can receive the push notifications, unfortunately, I am encountering issues with getting the notification events to function prop ...

Issue with MUI Grid item not functioning properly when using overflowY: "auto"

I am encountering an issue while using MUI with React. I have a <Paper> element wrapping a <Grid> with 3 children elements. The problem arises when I set the overflowY property of the bottom grid item to "auto" - instead of showing the scroll b ...