Adjusting the navigation image as it passes through various div elements during scrolling

Is it possible to dynamically change an image in the navigation bar based on the user's scroll position? For example, I want pic1 to be displayed when the page content is at the top, then switch to pic2 once the user reaches the footer, and then back to pic1 if they scroll back up.

I attempted the following code but couldn't get it to work. How can I modify it to achieve the desired effect?

var scrollContent = $("#content").offset().top;
var scrollHero = $("#hero").offset().top;

var scrollPos = $(document).scrollTop();

if (scrollPos > scrollContent) {
    $(".image-test").css({
        "background-image": "url('')"
    });
}  else if(scrollPos < scrollContent) {
    $(".image-test").css({
        "background-image": "url('')"
    });

Check out my codepen link for reference

Answer №1

There are a couple of issues with the jQuery code you're attempting to use:

1. You are only checking the scroll position on page load - it should be continuously checked inside the scroll event like this:

$(window).on('scroll', function( /* handler function */));

2. Changing the image through CSS won't work since the image isn't displayed using CSS. Instead, you can change the src of the img element like so:

$(".image-test img").attr("src", imgUrl);

3. Make sure to check for the bottom of the page content element where the replacement image is supposed to be swapped back. Retrieve it using this method:

var contentTop = $(".page-content").offset().top;
var contentBottom = contentTop + $(".page-content").outerHeight(true);

4. Ensure you check if the scroll lies between these positions:

if (($(this).scrollTop() > contentTop) && ($(this).scrollTop() < contentBottom)) 

To make this responsive and functional even when the screen size changes post-page load (e.g., resizing the window), incorporate it within the scroll event handler as well.

Complete Code for the Function

// Get the URL of the image for swapping back
defaultImgUrl = $(".image-test img").attr("src");

// Check the scroll position during scrolling
$(window).on('scroll', function() {

  // Retrieve the top and bottom positions of the page content
  var contentTop = $(".page-content").offset().top;
  var contentBottom = contentTop + $(".page-content").outerHeight(true);

  // Verify if the scroll position is within the page content 
  if (($(this).scrollTop() > contentTop) && ($(this).scrollTop() < contentBottom)) {
    // Alter the image URL
    $(".image-test img").attr("src", "https://lorempixel.com/output/nature-q-c-100-50-2.jpg");
  } else {
    $(".image-test img").attr("src", defaultImgUrl);
  }
  
});

Working Example:

// Get the URL of the image for swapping back
defaultImgUrl = $(".image-test img").attr("src");

// Check the scroll position during scrolling
$(window).on('scroll', function() {

  // Retrieve the top and bottom positions of the page content
  var contentTop = $(".page-content").offset().top;
  var contentBottom = contentTop + $(".page-content").outerHeight(true);

  // Verify if the scroll position is within the page content 
  if (($(this).scrollTop() > contentTop) && ($(this).scrollTop() < contentBottom)) {
    // Change the image URL
    $(".image-test img").attr("src", "https://lorempixel.com/output/nature-q-c-100-50-2.jpg");
  } else {
    $(".image-test img").attr("src", defaultImgUrl);
  }

});
.section1,
.section2,
.page-content {
  height: 100vh;
}

.section1 {
  background-color: green;
  padding-top: 50px;
}

.section2 {
  background-color: red;
}

nav {
  height: 50px;
  background-color: grey;
  position: fixed;
  width: 100%;
  display: flex;
}

.image-test img {
  width: 100px;
  height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div class="image-test">
    <img src="https://lorempixel.com/output/nature-q-c-100-50-5.jpg" alt="">
  </div>
  <div>
    <p>Change me to a different picture once I reach the top of the page content. Then change me back to the same picture as the one I had in the hero once I reach the footer.</p>
  </div>
</nav>
<div class="section1" id="hero">
  <h1>Hero</h1>
</div>
<div class="page-content">
  <h1>Page Content</h1>
</div>
<div class="section2">
  <h1>Footer</h1>
</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

utilize ng-include in angularjs to include a page

For some reason, I am having trouble including a file using ng-include. The file is supposed to be included when a button is pressed: <button type="submit" class="btn btn-primary" ng-click="getPartial()">Compare</button> This is the function ...

The React-native application initialized using npx create-react-app encountered an error and could not launch

Hello there, A couple of months back, I developed an app using create-react-app. However, when I tried to run it with npm start, I encountered the following error message: react-scripts start It seems like there's an issue with the project depende ...

What are the best ways to enhance change detection efficiency in Angular?

One issue I am facing involves two components and a service. It appears that when moving from the view of a routed component to elements in different components like a matMenu and an input field, the routed component seems to refresh itself. This becomes p ...

The datepicker UI triggers the onChangeMonthYear event before executing the beforeShowDay function

I am currently using the jQuery Datepicker UI (http://jqueryui.com/datepicker/) My goal is to dynamically color specific days based on data retrieved from an AJAX call. This is the current setup: $(document).ready(function() { getAllDays(); $("# ...

Guide to implementing an ES6 template within an HTML anchor tag href

Hello there, this is my first time seeking assistance here. I have an ajax request returning a JSON response. Now, I am aiming to use the response data to dynamically generate recipe titles and also create clickable links with that data. $( window ).load( ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Tips on dynamically changing the position of a div: Utilize absolute positioning within a for loop

Is there a way to extract the position x value of my div and store it in a variable? How do we then iterate over it within a for loop? <div id="object"></div> <style> #object{ position:absolute; width:10px; height:10px; ...

Select2 version 4.0.3 encountering issues when trying to automatically populate additional select2 fields with data fetched through ajax

I'm encountering an issue with Select2. Essentially, I need to populate other form fields with data retrieved from Select2's Ajax search. Even after following an example found here: Select2 4.0 - Push new entry after creation I'm still un ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Button in Laravel Vue JS staying enabled after redirection

I am facing an issue with a button on my webpage. Whenever the button is clicked, it should become disabled and have aria-disabled="true" added to it. However, upon page reload, the button does not remain disabled even though I pass a boolean true value to ...

Tips for crafting HTML emails that avoid users inadvertently selecting extra spaces while copying and pasting

There is an email that I send out with a specific string that needs to be copied and pasted only once. The issue arises when users copy the string from Outlook as they tend to unintentionally include an extra space at the end of it. Although I understand ...

Angular: Customizing table cell color based on condition

I am having trouble with changing the cell color of an object in my html table if a certain variable changeColor is true. I am utilizing angular for this task. <tr ng-repeat="list in results"> <% if (!{{list.changeColor}} ) %> <% { ...

Steps for serializing HTML tags contained within a Form along with the Form itself

I am currently working on a form that allows users to input information for publication on the site. The form utilizes a combination of inline editing with contenteditable=true on editable HTML tags, as well as standard form inputs like selects and text fi ...

What is the correct way to include a variable such as /variable/ in a MongoDB query?

I need help passing in a searchTerm from a variable, what is the best way to do this? const mongoquery = { description: { $in: [ /searchTerm/ ] } }; I attempted it like this initially: const mongoquery = { description: { $in: [ `/${searchTerm}/` ] } }; H ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

Stop flex items from expanding larger than their sibling elements

Is there a way to prevent a flex item from growing bigger than its siblings? Check out the example on CodeSandbox: LINK Here is the sample code: <div class='wrapper'> <div class='box one'></div> <div class ...

Unable to send multiple cookies using custom headers in Next.js configuration

I am using custom headers to set the cookie in my next.config.js file. The refresh token is successfully set, but for some reason the second token is not being recognized. key: 'Set-Cookie', value: `RefreshTokenKey = " ...

Constructor-generated element doesn't reflect changes upon component re-rendering

Why doesn't the <select> I create in the constructor update correctly when I select a different flavor? The other select and text update, but not this one. class ConstructorComponent extends React.Component { constructor() { super(); ...

Updating the state in React can be achieved by using the `

Upon obtaining a list of search results, each result is equipped with an onclick function. My goal is to exhibit the user-selected results on the screen by adding them to an array upon click: let selectedData = [] function addFunc(resultdata){ consol ...