Measure the Gap Between Elements as You Scroll

Utilizing jQuery, I have successfully implemented a functionality to change the position of a fixed div at the top of the screen (top:0) when scrolling reaches a specific point. This involves dynamically switching classes and modifying CSS styles.

However, I am exploring alternative methods for this task. The current approach relies on specifying a fixed height, which poses limitations when triggering the transition 30px away from a content block:

$(function(){
  $(document).scroll(function() {
    var x = $(this).scrollTop();
    if(x > 2025) {
      if($(window).width() > 950) {                
        $('.topFullWidthWhite').addClass('nonStick');
      }
    } else {
      $('.topFullWidthWhite').removeClass('nonStick');
    }
  });
});

SO...

I'm curious if there's a more flexible approach that could be based on a condition like:

if(x <= 20 from /* HTML ELEMENT */){
    //DO WHATEVER HERE
}

It would be great if there is a method that allows this relative positioning with respect to other elements rather than relying on document height alone.

Thank you!

Answer №1

Utilize the offset().top method on the specific element you wish to modify the CSS for.

$(window).on("scroll", function() {
  var two = $(".two").offset().top;
  if ($(this).scrollTop() > two - 20) {
    $(".two").addClass("reached");
  } else {
    $(".two").removeClass("reached");
  }
})
body {
  margin-bottom: 400px;
}

.one {
  height: 150px;
  background: green;
  margin-bottom: 20px;
}

.two {
  height: 100px;
  background: blue;
}

.two.reached {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one"></div>
<div class="two"></div>

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

Change the Vue3 PrimeVue theme or CSS file with a simple click or upon page load

One way to incorporate themes is by importing them in the main.js file at the root of the app: import 'primevue/resources/themes/arya-orange/theme.css'; However, I am exploring ways to dynamically switch CSS files based on the user's system ...

Enclose text with a background color that is positioned to the right

My Objective: I aim to accomplish the following outcome: div { text-align: right; } span { display: inline-block; background: #000; color: #fff; } <div> <span>abc</span><br/> <span>Hello world this is some tex ...

Capture XHR requests and alter the response body

I'm in the process of developing a script that serves as a proxy/wrapper for the conventional XMLHttpRequest object. This will allow me to intercept it, alter the responseText, and then return it back to the original onreadystatechange event. The mai ...

What is the best way to incorporate currency formatting into a table using sumtr and datatables?

I have a table where I am utilizing sumtr for the table footer, and displaying all the information within datatables. My requirement is to show all the values as currency. However, I am unable to modify the values after sumtr because it won't be able ...

Display a collection of objects by combining them with a single string

I am encountering an array of objects like this: const array = [<Button>abc</Button>, <Button>def</Button>] When I render them using: return array I end up with a row of buttons displayed next to each other. It looks somewhat lik ...

Loss of value in .net Jquery CheckBox onchange event

My JQuery code for CheckBoxes is causing some unexpected behavior: $(document).ready(function () { $('#chk_AGVS').change(function () { if ($(this).is(":checked")) { '<%Session["chkAGVS"] ...

Steps for importing a React component as an embedded SVG image

I have developed a SVG component in React by converting an SVG file to a React component using the svg-to-react cli tool. In order to load and display additional svg files within this component, I am utilizing the SVG image tag as demonstrated below. This ...

Building a simple messaging platform with the power of Socket.io and Node.js

After following the guide at http://socket.io/get-started/chat/, I attempted to create a basic chat application. However, upon running npm install --save socket.io I encountered the error message below. How can I resolve this issue? npm WARN package.jso ...

Using *ngFor in Angular for Parent-Child component interaction

Is there a way to iterate through a child component multiple times with different data each time? For instance, in my 'sitelist' component (parent), I aim to loop through my 'summary' component (child) as many times as needed based on ...

Setting up TypeScript in an Angular 2 project and integrating Facebook login

Currently, I am in the process of familiarizing myself with Angular 2 and typescript. Although things have been going smoothly so far, I have hit a roadblock while attempting to implement a Facebook login message. In my search for a solution, I stumbled up ...

Is it necessary to download the PDF file for accessibility purposes?

Currently, I am working on a website that includes downloadable PDF links. We are utilizing a parameter at the end of the file download URL to instruct the browser on how to handle the file: https://example.com?ref=0&download=y By using the download= ...

Is there an issue with the JavaScript Mapping provided?

const assetMap = { General: { name: 'Common', bkgHex: '#eee', fontHex: '#aaa', }, ... const getAsset = (name, type) => { return assetMap.name.type; } console.log( getAsset('General', 'nam ...

What steps can be taken to ensure that the JavaScript fetch() function is consistently accessing and updating the new data that is being added to the

I'm facing an issue with my JSON data file that I want to display on the screen. I have a function with a fetch() request that executes every time I click a button. Initially, it works perfectly by fetching the data and displaying it correctly. Howeve ...

Exploring the behavior of the Express NodeJS router

Here is a functioning route: router.post('/addlog', multipartMiddleware, function(req,res){ controller.postLog(req,res); }); However, if I modify the call like this: router.post('/addlog', multipartMiddleware, controller.postLog(r ...

Tips for building a custom error handling function specifically designed for parsing and handling errors in

Is there a way to reduce redundancy in my code, such as: let name = ""; try { name = data[" "][0][" "][0][" "][0][" "][1][" "][0][" "][1]["C"]; } catch (error) { if (error instanceof TypeError) { console.log("name TypeError"); } } I have consid ...

What is the reason behind react-router-dom not supplying location.key during the initial page load?

In my component screen using react-router, I heavily rely on the parameter location.key to identify paths and other elements (using location.pathname did not resolve the issue). However, I noticed that when I first load my app, react-router does not have ...

What is the best way to position the sign-in modal form on the top right corner of my website?

Hey there, I'm facing a bit of an issue and can't seem to figure out what went wrong. Recently, I inserted a Bootstrap Sign In modal in my HTML file. Here's the code: <div class="text-center"> <a href="" class ...

Exploring the incorporation of the elasticsearch javascript library within your Aurelia application

Transitioning from the angular realm to aurelia has been a learning experience. However, I've hit a roadblock trying to figure out how to integrate elasticsearch.js into my aurelia app. Does anyone have any tips on how to achieve this? Or perhaps a ...

Contrasting text-transform: uppercase; and the use of all capital letters

Could you explain the distinction between <span style="text-transform: uppercase;">some text</span> and <span>SOME TEXT</span> They appear identical visually, but I've come across a suggestion that it's preferable to k ...

Exploring the dynamic duo of HTML and JQuery within the Webstorm IDE

I'm facing a simple issue with my webstorm project. It consists of an HTML file, CSS file, and JS file. In my project, I tried creating a circle using a "div" element and attempted to make it fade out upon clicking with JavaScript. However, the funct ...