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

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

Vue.js has encountered a situation where the maximum call stack size has been exceeded

I have implemented a method called cartTotal that calculates the total price of my products along with any discounts applied, and I am trying to obtain the final value by subtracting the discount from the total. cartTotal() { var total = 0; var di ...

Fetching data from local JSON file is being initiated twice

I need some help understanding why my code is downloading two copies of a locally generated JSON file. Here is the code snippet in question: function downloadJson(data, name) { let dataStr = 'data:text/json;charset=utf-8,' + encodeURICompo ...

Stepping up Your Next.js Game with the Razorpay Payment Button Integration

When using the Razorpay payment button on a website, it provides a code snippet like this: <form> <script src = "https://cdn.razorpay.com/static/widget/payment-button.js" data-payment_button_id = "pl_FNmjTJSGXBYIfp" data ...

Tips on Extracting Data from a JSON Object with an Embedded Array

Check out this example of a Json Object: {"UserName":Mike,"IsActive":0,"ChbxIsActive":false,"MyAccountsAvailable":[{"Id":"157A","MyAccount":"CHRIS MCEL","MyCheckBox":false,"Tags":null},{"Id":"157B","MyAccount":"DAN BONE","MyCheckBox":false,"Tags":null} He ...

Using an HTML5 image icon as an input placeholder

Is there a way to incorporate an image icon into an input placeholder and have it disappear when the user starts typing, across all browsers? In trying to achieve this, I successfully implemented a solution for webkit (Safari+Chrome) using ::-webkit-input ...

Monitor elements in real-time as they are inserted into the DOM using a Chrome Extension

In the process of developing a Chrome extension, I am tackling the task of removing or hiding specific elements based on their id/class. While accomplishing this after the DOM is loaded poses no issue, it does result in a noticeable "blink" on the page dur ...

Achieving proper variable-string equality in Angular.js

In my Angular.js application, I am utilizing data from a GET Request as shown below. var app = angular.module('Saidas',[]); app.controller('Status', function($scope, $http, $interval) { $interval(function(){ ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Subject: Enhancing Page Filters with jQuery Multiple Checkboxes

Here I am continuing the discussion from a previous question on jQuery Multiple Checkbox Page Filter. This is my own unique question. My objectives are threefold: I aim to create a list of checkboxes for filtering page content. I want only the content t ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Managing the URLs of single page applications

Typically in a Single Page App (SPA), there is usually one main page that contains a side navigation menu with various anchor tags. These anchor tag URLs are managed by the angular/react/sammy js router, and the content of the main section is updated based ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

Activate an update of a jQuery color selector plugin when there is a change in the input field

Currently, I am utilizing the jQuery .click() method to update 15 text fields with basic color hex values like this: document.form1.top_menu_bgcolor.value = '#FFFFFF'; In addition, I have incorporated ExColor for jQuery from which showcases an ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...