Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling.

const targetElement = document.getElementById('sidebar');

window.addEventListener('scroll', () => {
  if (window.scrollY > targetElement.offsetTop) {
    console.log('Element passed');
  }
})

Here is the sample code you can refer to: https://codepen.io/RomanKomprs/pen/LMrPNJ

UPDATE: The initial code provided seems to have an issue. The condition for detecting when the scroll position surpasses the sidebar's offsetTop is not triggering as expected. Any pointers on what might be incorrect?

Answer №1

Swap out window.scrollTop for getBoundingClientRect().top

const elementTarget = document.getElementById("sidebar");

window.addEventListener("scroll", () => {
  if (window.scrollY > elementTarget.getBoundingClientRect().top) {
    console.log("passed an element");
  }
});

Give it a go here!

Answer №2

To begin, you must ensure that the elements have unique ids; Additionally, make sure to utilize .offsetTop to retrieve the offset value;

if (window.scrollY > elementTarget1.offsetTop) {
  console.log('passed an element');
}

codepen.io/anon/pen/LMrYMZ

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

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...

Having trouble getting an Angular directive to bind a click event to an external element?

I've been working on creating a unique custom event for toggling with Angular. The directive I'm using is called toggleable. It may sound simple at first, but the tricky part is that I want to be able to use any button or link on the page for to ...

Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML. function sendData() { var formData = new FormData( document.querySelector("form") ); var xmlHttp = new XMLHttpRequest(); xmlHttp.open("post", "test.php",true); ...

Adjust the position of the xAxis on the Highcharts chart to move it downward or

I recently inherited some code from the previous developer that uses highcharts.js (v3.0.1). I'm having trouble with the xAxis appearing within the graph itself (see screenshot). Despite my efforts to recreate this issue in jsfiddle, I can't seem ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

A guide on adjusting a function to pause execution until a line is complete

In the code snippet below, there is an angularJS function named myFunc: $scope.myFunc = () => { myModule.getConfig().update(params); myModule.go(); myModule.log('ok'); }; Additionally, there is a go function defi ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

Is it possible to execute a function when the AJAX request is successful and returns a status code of

I am looking to implement the success function to only run a certain function if the status code is 200. I have come across this example: $.ajax ({ success: function(data,textStatus,jqXHR){ external(); } )}; However, I have not found a clear ...

JSON parsing error within the HTML Sidebar list

I have a JSON file that contains data I need to parse in order to display information in my sidebar. When a user clicks the button labeled "List all sessions", the goal is to showcase all of the available session details grouped by Session ID and location. ...

React error: Objects cannot be used as children in React components

Upon trying to display data using REACT, an error message stating "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead" is encountered. The issue arises when fetching records from a MongoDB collect ...

Dealing with currency symbols in Datatables and linking external sources

I'm having trouble linking an external link to the "customer_id" field. The link should look like this: /edit-customer.php?customer_id=$customer_id (which is a link to the original customer id). I am creating a detailed page with most of the informati ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

Ways to invoke a specific component within ReactDOM.render in React

Currently, I am facing an issue where 2 components need to be rendered present in a single div using myProject-init.js, but both are getting called at the same time. In myProject-init.js file: ReactDOM.render( <div> <component1>in compone ...

Determine the total number of hours along with the precise minutes

Could you assist me with calculating minutes? Here is an example: var time_in = '09:15'; var break_out = '12:00'; var break_in = '13:00'; var time_out = '18:00'; var date = '2018-01-31'; var morning = ( ...

checking the validity of serialized information in Ajax

I am facing a specific issue where I need to validate data before it is saved through an ajax call. When the user switches to a different URL, the save_ass_rub function is triggered. Within my application, there is a custom Window that allows users to inp ...

Retrieve the stylesheet based on the presence of a specific class

Is there a way to dynamically add a CSS stylesheet based on the presence of a specific class on a page? For example, instead of checking the time and loading different stylesheets, I want to load different stylesheets depending on the class present in the ...

Using the directive in AngularJS and passing ng-model as an argument

Currently, I am creating a custom directive using AngularJs, and my goal is to pass the ng-model as an argument. <div class="col-md-7"><time-picker></time-picker></div> The directive code looks like this: app.directive(' ...

Adjust the dimensions of the initial cell

I need to adjust the size of the initial "generated" cell in a grid. The grid is not present in the HTML markup until JavaScript prints RSS information on it, making it difficult to target specific rows or cells directly. Note: The first element is hidden ...

Show specific elements in a listview using JavaScript

I have created a dynamic listview using jQuery Mobile that currently shows 4 list items. The list is generated through JavaScript. $( document ).ready(function() { var data = [{ "name": "Light Control", "category": "category", "inf ...