Adjust the header image as you scroll

Currently, I have a static image in the header of the page. I'm looking to have the image change to a different one when half the page has been scrolled.

Do I need to utilize JavaScript for this functionality or is it achievable with CSS alone?

body {
    height:1200px;
    width:100%;
    background-color:#fbfbfb;
}
.header_nav {
    width:100%;
    height:150px;
    background-color:#666;
    position:fixed;
    top:0;
    left:0;
    color:#fff;
    background-repeat: no-repeat;
    background-position: center center;
}

img {
  width: 150px;
  display: block;
  margin: 0 auto;
}
<div class="header_nav"><img src="https://i.picsum.photos/id/244/200/200.jpg?hmac=Q1gdvE6ZPZUX3nXkxvmzuc12eKVZ9XVEmSH3nCJ2OOo"></div>

Answer №1

To change the image precisely, you can utilize the scrollTop() method.

$(function () { 
    $(window).scroll(function () {
        if ($(this).scrollTop() > 600) { 
            $('.header_nav img').attr('src','https://i.picsum.photos/id/912/200/200.jpg?hmac=tYYyMFni6bya5yEVkwmmFekjWGedHVByLtPI5q1lcyw');
        }
        if ($(this).scrollTop() < 600) { 
            $('.header_nav img').attr('src','https://i.picsum.photos/id/244/200/200.jpg?hmac=Q1gdvE6ZPZUX3nXkxvmzuc12eKVZ9XVEmSH3nCJ2OOo');
        }
    })
});
body {
    height:1200px;
    width:100%;
    background-color:#fbfbfb;
}
.header_nav {
    width:100%;
    height:150px;
    background-color:#666;
    position:fixed;
    top:0;
    left:0;
    color:#fff;
    background-repeat: no-repeat;
    background-position: center center;
}

img {
  width: 150px;
  display: block;
  margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="header_nav"><img src="https://i.picsum.photos/id/244/200/200.jpg?hmac=Q1gdvE6ZPZUX3nXkxvmzuc12eKVZ9XVEmSH3nCJ2OOo"></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

Creating a floating div that remains in place without disturbing the layout of the surrounding elements on

I am trying to place a div within a page at specific coordinates without affecting the rest of the content on the page. My initial approach was to give the parent container a position: absolute and the floating div a position: relative, then setting the p ...

Transfer information from the server to the client using NodeJS and Express

I am encountering an issue with sending data from my express server to the client side. I have implemented app.post and app.get, however the problem is that the request needs to originate from the client side. My requirement is to send the data from the se ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

Retrieving details of a row in Codeigniter using a link with a foreach loop

After nearly a month of trying, I am still unable to figure out how to extract the "details" for each row from my table in the view. The table is populated using a foreach loop and I want to display these details on another page when clicking the link labe ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

Obtain the URL for the JavaScript code that is currently running

Can anyone help me find the URL of the JavaScript currently being executed? I am aware of using window.location.href for the current page, but that doesn't necessarily provide the path to the script that is running. Any assistance would be greatly ap ...

Having trouble with the Angular router link suddenly "failing"?

app.routes.ts: import { environment } from './environment'; import { RouterModule } from "@angular/router"; import { ContactUsComponent } from './static/components/contact-us.component'; import { HomeComponent } ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

Angular: Verify that all services are fully executed before proceeding to the next step

We have adopted Angular for our project. Our component receives data from an API, which is then processed by Data Services. These services transform the data by combining first and last names, rounding dollar amounts, performing calculations, etc. The fina ...

Issue with CSS3 gradient display in Firefox and IE, functioning correctly only in Chrome

I recently developed a text gradient class that looks great in Google Chrome but unfortunately doesn't display correctly in Firefox and Internet Explorer. In these browsers, there is a visible background gradient behind the text which is not the desir ...

Guide on enabling users to input slide number and URL address to load content using Ajax

Is there a way to customize the number of slides in a slider and choose which content is loaded into each slide using AJAX calls in jQuery? Currently, my slider uses the jQuery .load() method to dynamically load content into each slide when it becomes vis ...

Inquiries about JavaScript and the YouTube API

Being very resourceful, I am currently exploring ways to feature my YouTube links on my website in an elegant manner. Tired of the redundancy of posting on both platforms, I am seeking a solution that seamlessly integrates these posts. Despite my efforts, ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...

Retrieve a JSON object from a JSON array using a specific key

I am facing a situation where I have a json array containing multiple json objects. Let's take the example of a course object with the following structure: {"name": "Math", "unit": "3"} The json array looks something like this: [{"name": "Math", "u ...

Facing a challenge in configuring MongoDB automatic data expiration based on specific time zones

I am currently facing an issue with clearing data in MongoDB at the start of each day. For example, on July 15, 2020 at 00:00:00, data is deleted from the database based on a specific time. I am having trouble properly assigning the expiresAt attribute in ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Tips for implementing a "loading spinner" for each new ajax call using jQuery

Each time an ajax call is made, I want to display the loading icon/image. However, in my current code, the image only appears once and then disappears. Even when there are multiple ajax calls within a for loop, the image only shows once and vanishes after ...

What is the best way to extract all <tr> elements from a <tbody> and then convert them into a String?

Below is an example of an HTML table: <table id="persons" border="1"> <thead id="theadID"> <tr> <th>Name</th> <th>sex</th> <th>Message</th> </ ...

What is the best way to align <h2> and <img> elements that are set to display as inline-block?

I've been experimenting with aligning h2 and img (icon) elements and although I added display: inline-block, they ended up shifting to the left of the section. Is there a way I can center them instead? HTML: <h2>Coffee</h2> <img src=&q ...

Spacing before input text is found to be unnecessary and can be removed

Hello there, I've encountered a slight issue with a text input field that has border radius. The first character typed seems to protrude slightly outside the input field due to the border radius. Is there a way to add some extra whitespace before the ...