A specific div remains in place as the user scrolls

Imagine a div that is positioned 60px from the top of the screen. What if, as you scroll down, it stops when it reaches 10px from the top and remains there for the rest of your scrolling session? And then, when you scroll back up, it goes back to its original position at 60px. I've searched extensively for a solution to this unique functionality but haven't found anything yet. However, there is a code snippet that can calculate the distance from the top:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

Answer №1

Check out this method using only vanilla JavaScript. If you prefer, you can swap out certain selectors like document.getElementById with jQuery selectors like $("id").

window.onscroll = function(){
  var el = document.getElementById('sticky'),
      s = window.pageYOffset || document.documentElement.scrollTop, // amount page has scrolled
      t = document.getElementById('main').getBoundingClientRect().top; // top of the main div
      
  if(s > t){
    el.style.position = 'fixed'; // change position to fixed from absolute
  }else{
    el.style.position = ''; // clear styles when back to original position
  }
}
body { 
  min-height: 200em; 
  margin: 0;
  padding: 0;
}

header {
  background: black;
  color: white;
  padding: .5em;
}

#main { position: relative; } /* important for sticky box positioning */

#sticky {
    background: cornflowerblue;
    padding: .5em;
    position: absolute;
    right: 1em;
    top: 1em;
    width: 10em;
    color: white;
}
<header>This is just a page header or toolbar.</header>

<section id="main">
  <div id="sticky">This should stick to the top when scrolled.</div>
</section>

Answer №2

If the distance from the top of the page is more than 10px, this jQuery solution will add an is-sticky class to the element for styling with CSS.

// save the element in a variable
var element = $('.item'),
    visible = false;

// when scrolling
$(window).scroll(function() {

  /**
   * saves the scroll distance in px
   * from the top of the viewport
   */
  var scroll = $(window).scrollTop();

  /**
   * if the scroll is greater than or equal
   * to 10px, add a class of .is-sticky to the element
   * otherwise, we are less than 10px from the top
   * of the document and therefore do not want
   * the element to have the .is-sticky class
   */
  if(scroll >= 10) {
    if(!visible) {
      element.addClass('is-sticky');
      visible = true;
    }
  } else {
    if(visible) {
      element.removeClass('is-sticky');
      visible = false;
    }
  }
});

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

What is the correct way to run javascript on a DOM element when ng-show is triggered?

For those who prefer shorter explanations, there's a TLDR at the end. Otherwise, here's a detailed breakdown. I have a form that consists of multiple inputs organized into different "pages" using ng-show. What I aim to achieve is when ng-show r ...

Modify session variable upon link click

Here is an extension of the question posed on Stack Overflow regarding creating a new page for different PHP ORDER BY statements: Create a new page for different php ORDER BY statement? The task at hand requires changing a session variable and refreshing ...

Cannot Get jQuery .flip() to Work Automatically Every 2 Seconds

There are 3 words that I want to rotate on their x-axis every 2 seconds (repeating). Using jQuery: $(function () { count = 0; wordsArray = ["Innovation", "Creativity", "Success"]; setInterval(function () { count++; $("#words").text(wordsArray[co ...

Navigation bar's active area does not span the full height

I'm facing some issues with the navigation bar on my responsive website. One issue is that the clickable area for the links does not extend to the full height of the nav bar, and I would like it to cover the entire height. Another problem arises whe ...

The jQuery Select2 Plugin for Dynamic Dropdowns with Ajax Integration

Utilizing the Select2 plugin with Ajax to connect to my employee database has been quite helpful. It allows setting up a meeting and selecting all the employees you wish to invite. Here is an example of the code: $("#requiredAttendees").select2({ ...

Show the JSON data that was returned

I'm encountering a problem trying to access and display the returned object. Since it's cross-domain, I'm using jsonp, but I'm unable to retrieve the returned object for some reason. $(function(){ var API = "https://ratesjson.fxcm. ...

Bring in the content to Notepad utilizing jQuery

How can I export data to Notepad? I have fields for Name, Age, and WorkingStatus that are input as text and textarea. Is there a demo or code available to help me insert this data into Notepad? ...

How do I adjust the ul size to be proportionate to the header?

I have a list with corresponding hyperlinks in my code, and I am trying to make these elements the same size as the header. I attempted adding auto padding and height auto but it did not produce the desired result. Here is the HTML snippet: <header id ...

Tips for displaying images dynamically in HTML using AngularJS

src={{logo}} var logo = 'localhost:3000/modules/images/default.png' I'm trying to display the image path dynamically, but it's not showing up in the HTML. Do I need to use quotes for src? Can someone please assist me with this issue? ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Navigate to a specific position with a single click by accessing a class from another Vue component

Clarification of the issue When a user clicks on the login link, the view should automatically scroll down to the login window where they can input their credentials. I know how to achieve this in a single file using document.getElementById('login-w ...

When the flex-grow property is set to 1, the height of the div extends beyond the space that

Here is an example of some HTML code: .container { height: 100%; width: 100%; display: flex; flex-direction: column; padding: 10px; background-color: aqua; } .box { width: 100%; height: 100%; flex-grow: 1; background-color: cadetb ...

Adjust the header and menu color as you scroll

Starting fresh with JavaScript, I'm seeking advice on a specific piece of code. Working on a Joomla 3.2 website using the Gantry template by default. My goal is to achieve the following: When a user accesses a submenu (e.g., 01, 02, 03) derived from t ...

Responsive HTML and CSS Image Gallery without Clickable Images

As I embark on the creation of an HTML and CSS based Gallery, I am eager to make my images more interactive by enabling them to expand into full-screen mode upon clicking. Is it necessary for me to incorporate additional plugins to achieve this functiona ...

Is there a way to style alternate iframes using CSS?

I need to select every second iframe in the image provided. Is it possible to achieve this using nth-child? I have tried with the following code (unsuccessfully): #main iframe:nth-child(2n+2) ...

What would be an effective method for sending a multitude of parameters to a controller?

I am currently working on an application that utilizes Java with the Spring framework and Javascript with AngularJs framework. The application features a table displaying a list of objects along with two text fields for filtering these objects. The filteri ...

React is throwing an error because it cannot access the property 'length' of an undefined value

TypeError: Cannot read property 'length' of undefined When I try to run my React app, I keep getting this error message from the compiler. What steps should I take to resolve this issue? request = (start,end) => { if(this.state.teams.lengt ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

Is there a way to stop these symbols (♈♉♊♋♌♍♎♏♐♑♒♓) from being substituted with emojis?

I am currently working on a project involving the simulation of the Prague Astronomical Clock (). My goal is to display the glyphs representing signs of the zodiac, which are in the Unicode range U+263C-2653 along with other astronomical symbols. My prefe ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...