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

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Tips for evaluating style modifications on mouseover using cypress

Trying to test hover styles on table rows but encountering issues: Here is the code snippet I am testing: it("Table rows should display correct hover styles", () => { cy.get("table>tbody>tr").each(($el, index, $list) =&g ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

The scrollHeight property for a textarea element that is set as

Currently, I am working on enhancing a form results page by implementing a readonly textarea to showcase the submitted email address. My main goal is to allow the textarea to dynamically adjust its height in order to display the full email instead of trunc ...

Toggling designs with a simple click

I'm currently working on a ReactJS project and I'm trying to figure out how to change the color of a button when it's clicked. I've heard about the Ripple API, but I find it quite complex to use. Can anyone offer some advice on how I ca ...

What is the method for changing the color of a specific section of a header?

My header design consists of two lists of buttons, one on the left and one on the right. I am looking to customize the background color of the "Sign Up" button to make it stand out. Below is an example of what I want and the current design of my header alo ...

Issue: Unable to locate module 'js-yaml' while executing npm start command

Unable to locate module 'js-yaml' Require stack: D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\loaders.js D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\createExplore ...

Bug with the button and text input feature in Firefox

I am facing a strange issue where the button and input have the same CSS (except for the background), but Firefox is displaying them differently. This problem does not occur in IE or Chrome. #searchInput { width: 80%; margin: 0 auto; display: ...

The deprecated body parser is throwing an error due to the lack of the extended option

I am encountering an issue with my code and I'm not sure how to resolve it. Since I am new to the codebase, I feel completely lost and clueless about what steps to take. body-parser deprecated undefined extended: provide extended option index.js:20:2 ...

Calculator: Show individual digits once more following a calculation

After clicking the 'equal' button, the result is displayed. However, if I click another number, it doesn't clear the result. I want the result to stay when operation symbols like '+' or '/' are pressed. While working on t ...

SwiperJS continuously applies additional right margin to every slide

My Swiper carousel seems to be adding an unnecessary 5px margin-right to each slide, resulting in the cards not fitting into one frame. I attempted to fix this by setting the margin-right to 0px for the .swiper-slide class using !important, but it didn&ap ...

What are the best ways to integrate markdown into my Vue.js projects?

Is there a way to utilize markdown within the context of vue.js instead of regular HTML paragraphs? ...

Is there a way to determine if my great-grandfather has a class attribute that includes a specific word?

Looking for some assistance with my HTML code snippet: <div class='one two three and etc.'> <div> <div> <div class='my_target'> </div> </div> ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Selecting an option from dropdown1 to retrieve a specific value from a JSON file

I currently have 2 dropdown lists to fill with data from a JSON file: $scope.categories = [ {name:"Blouse", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Shirt", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Pants", size ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

In JavaScript, a prompt is used to request the user to input a CSS property. If the input is incorrect,

Implement a while loop that continuously prompts the user to enter a color. If the color entered matches a CSS property such as blue, red, or #000000: The background will change accordingly, but if the user enters an incorrect color, a message will be dis ...

Tips on creating a blurred background effect when an HTML popup modal is activated

Whenever I click on a button, a popup window appears. What I want is for the background to be blurred when this popup modal opens. <div class="modal" id="myModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...