Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content.

While this solution works perfectly, I encountered a problem where the calculations for "const targetTopPos = targetEl.getBoundingClientRect().top" are incorrect when the page is already scrolled. I'm unsure why this issue is happening.

Another issue arises when the page is refreshed while scrolled down, causing the header to remain fixed until you scroll again.

Below is the code snippet:

I have included a console log for "targetTopPos" to help identify the issue.

Answer №1

The reason is that you are redefining targetTopPos as a constant in your onresize event handler. Simply assign the new value to targetTopPos

Please refer to the code snippet below

window.onresize = function(event) {
    targetTopPos = targetEl.getBoundingClientRect().top;
    console.log(targetTopPos);
};

const headerEl = document.querySelector('header')
const targetEl = document.querySelector('#target')

let targetTopPos = targetEl.getBoundingClientRect().top

let isHeaderFixed = true

document.onscroll = () => {
  const targetTopOffset = targetEl.getBoundingClientRect().top
  
  if (isHeaderFixed && targetTopOffset < 100) {
    headerEl.style.position = 'absolute'
    headerEl.style.top = `${targetTopPos - 100}px`
    isHeaderFixed = !isHeaderFixed
  }
  
  if (!isHeaderFixed && targetTopOffset >= 100) {
    headerEl.style.position = 'fixed'
    headerEl.style.top = '0px'
    isHeaderFixed = !isHeaderFixed
  }
}
body {
  padding: 0;
  margin: 0;
  position: relative;
}

header {
  position: fixed;
  height: 100px;
  width: 100%;
  background: lightblue;
}

.content {
  line-height: 100px;
}

.target {
  width: 100%;
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  Custom header
</header>
<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie...

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

Issue with custom function not being triggered by datepicker onSelect in Internet Explorer with JQuery

I have a datepicker set up like this: $("#startDate").datepicker({ onSelect: changeDate }); This is used with the following input field: <input type="text" id="startDate" value="" class="dateField"/> This setup works well in Chrome, but encou ...

Executing JavaScript in Rails after dynamically adding content through AJAX

Looking for advice on integrating JavaScript functions into a Rails app that are triggered on elements added to the page post-load via AJAX. I've encountered issues where if I include the code in create.js.erb, the event fires twice. However, removing ...

Using CSS to show only the central portion of an image

How can I display only the center part of an image with dimensions height=300px and width=520px using CSS or jQuery? I tried searching on Google, but didn't find a solution. Is it possible to show only a 200x130 section from the center of an image us ...

Ways to design each element in React

I'm currently working on a React code that involves CSS for Scrolling functionality. When I try to use props.children.map, I encounter an error saying "TypeError: props.children.map is not a function". Since I am in the process of learning React.js, t ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

Implementing hashing with resumable.js

Looking for a way to include hashing in resumable.JS by utilizing the "fileAdded" event hook. Any suggestions on how to add hash to each chunk? ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

What is the best way to retrieve a jobID from Kue?

I am currently working with Express and I'm facing a challenge in creating a job whenever someone posts to my route. My goal is to have the response include the job.id, but the job id is only generated within the callback of my queue.createFunction. I ...

Offering fields for modules, main, and browser that meet the needs of ESM, CommonJS, and bundlers

I have upgraded a number of my published npm packages to include both commonjs and esm builds. Some of these packages are meant for use in both node and the browser, and they are all compiled using webpack or rollup. Additionally, all of them are written i ...

What is causing onbeforeunload to consistently display a dialog box?

I'm facing an issue where my javascript code displays a confirmation dialog even when there is no unsaved data. I have simplified the problem to this bare minimum: window.addEventListener("beforeunload", (e) => { e.returnValue = null; retu ...

Adjust the speed of the remaining divs below to move up when one is deleted using Ajax and jQuery

My div elements are arranged from top to bottom, and when one selected div is removed or faded out, all other divs below it shift up suddenly to fill the gap. While this behavior is functional, I would prefer to slow down the movement of the divs shifting ...

ReactJS: Understanding the Interconnectedness of Components

In my application, I have two main components: Table (which is a child of Tables) and Connection (which is a child of Connections). Both Tables and Connections are children of the App component. The issue I am facing is that the Table component needs to be ...

Synchronize MySQL database structure with HTML5 local storage to enable querying

After researching HTML5 local storage, I am considering mirroring a MySQL database's structure for use in an application that requires a large amount of data for a single user. Why would I want to do this? As a web game developer in my spare time, I ...

What is the best way to show a nested div element within a v-for loop in Vue.js?

One interesting feature of my coding project is that I have an array nested within another array, and I iterate through them using two v-for loops. The challenge arises when I try to display a specific div in the second loop only upon clicking a button. ...

Angular causes HTML Dropdown to vanish once a null value is assigned

In my scenario, I have two variables named power and mainPower. Both of these variables essentially represent the same concept, with mainPower storing an ID of type Long in the backend, while power contains all attributes of this data transfer object. The ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

The mystery of the Accordion Effect: A Next.js/React.js issue where it slides up but refuses to

After implementing a custom accordion using next.js, I encountered an issue where the slide animation worked successfully when moving up and out upon clicking the button. However, when trying to move it back down into the content, it did not animate as exp ...

Struggling to perfectly center the NavBar within the wrap container

After working on my navbar and utilizing this site for guidance, I was able to center it using text align. However, there is an odd indent in the navbar that I can't seem to figure out. This indentation throws off the alignment when centered, giving i ...

Tips for creating a blur effect on all options except for the selected 2 out of 4 using jQuery

My goal is to choose 3 options from a list and once 3 options are selected, all other options will be blurred to prevent further selection. Please review the code snippet I have provided below. Link to File <!DOCTYPE html> <html> <head> ...

Can JSON encoding in a URL pose a risk of XSS attacks?

To ensure my application has URL-friendly capabilities, I am storing its context as a JSON within the URL. This results in something like: http://mysite.dev/myapppage/target#?context={%22attr1%22%3A{%22target_id-0%22%3A{%22value%22%3A%223%22%2C%22label%2 ...