How can you toggle the visibility of a div based on detecting a specific class while scrolling?

My webpage features a sticky header that gains an extra .header-scrolled class when users scroll down. I am looking to switch the logo displayed in the header once it has been scrolled.

Below is a simplified version of my HTML code:

<header class=".header-sticky">
  <div class="logo1">
    <img src="../image1.jpg">
  </div>
  <div class="logo2">
    <img src="../image2.jpg">
  </div>
</header>

Is there a way for me to hide the entire <div class="logo2"> until the .header-scrolled class is applied to the <header>, and vice versa - conceal <div class="logo1"> and show <div class="logo2"> when the corresponding class appears after scrolling?

Answer №1

With the power of CSS, you can achieve this effect without relying on JavaScript:

.logo1 { display: block; }
.logo2 { display: none; }

.header-scrolled .logo1 { display: none; }
.header-scrolled .logo2 { display: block; }

By the way, make sure your .header-sticky class attribute is written as header-sticky (without the dot) in your HTML code.

Answer №2

Utilize CSS to manipulate the display property on your elements by selecting the elements using their respective classes

Check out the example below:

const changeClass = function() {
  let elem = document.getElementsByClassName('header-sticky')[0].className = "header-scrolled";
}
.header-sticky .logo1 {
  display: block;
}

.header-sticky .logo2 {
  display: none;
}

/* When header-sticky changes to header-scrolled, swap the display properties */

.header-scrolled .logo1 {
  display: none;
}

.header-scrolled .logo2 {
  display: block;
}
<header class="header-sticky">
  <div class="logo1">
    <img src="../image1.jpg" alt="Logo1">
  </div>
  <div class="logo2">
    <img src="../image2.jpg" alt="Logo2">
  </div>
  
  <button onclick="changeClass()">Change to scrolled</button>
</header>

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

Is There a Workaround for XMLHttpRequest Cannot Load When Using jQuery .load() with Relative Path?

My current project is stored locally, with a specific directory structure that I've simplified for clarity. What I'm aiming to do is include an external HTML file as the contents of a <header> element in my index.html file without manually ...

Running Angular without dependencies causes it to malfunction

I recently ventured into the world of AngularJS and started by creating a module without any services or factories. Everything was running smoothly until I decided to introduce services and factories into my code. Suddenly, things stopped working. Here is ...

What steps are involved in integrating QuickBlox on your website?

I am completely new to web development and have a question about integrating QuickBlox into my website using JavaScript. I have included the necessary JavaScript files in my website and set up the QuickBlox admin application, but I'm not sure how to p ...

Changing the style of Vuetify v-list-item when hovering over it

I just started using Vuetify and I came across a v-list sample that I need help with. Here is the link to the Vuetify v-list sample on Github. My v-list: Code: <template> <v-card max-width="500" class="mx-auto" > <v-toolba ...

Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section locat ...

align the text below a single element

Whenever I attempt to designate the character c as sub-aligned within a table row, the subsequent bar text also becomes sub-aligned (which is very counterintuitive). <table> <tr> <td>test</td> <td>foo<sel style= ...

Resolved the z-index problem with the header and sidebar placement

Hello there! I have come across an issue that I need some help with. I have a fixed sidebar and header on my website, both of which have drop shadows applied to them. However, I don't want the header to cast a shadow on the sidebar as I want them to ...

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

How do I handle the error "Uncaught TypeError: Cannot read property 'func' of undefined in React JS

Hey there, I've encountered an issue while setting up a date picker on my project. I tried using these resources: https://github.com/Eonasdan/bootstrap-datetimepicker Would appreciate any help! https://codesandbox.io/s/18941xp52l render() { ...

What is the process of adding a phone number with an extension on an iPhone web application?

When building a web application, inserting the following number: <a href="tel:888-123-4567">call now</a> The iPhone will automatically convert that link into an instant call function when clicked. But what should I do if the number includes ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

What are the best practices for integrating PrimeVue with CustomElements?

Recently, I decided to incorporate PrimeVue and PrimeFlex into my Vue 3 custom Element. To achieve this, I created a Component using the .ce.vue extension for the sfc mode and utilized defineCustomElement along with customElements.define to compile it as a ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

Adjusting the text color of cells in a table based on their values using Ruby on Rails

I have a cell within a table that is formatted like this: <td><%= play_result.timestamp.strftime("%H:%M:%S") + ' ' + play_result.status + ':' + ' ' + '[' + play_result.host + ']' + ' ' ...

Thumbnail vanishes upon being selected

To access my template site currently, please click here. Currently, the first thumbnail on my website is set up to display a gallery of images in FancyBox once clicked, similar to a question asked on StackOverflow that you can view here. Below is a snipp ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Separating vendor and application code in Webpack for optimized bundling

Recently, I created a React+Webpack project and noticed that it takes 60 seconds to build the initial bundle, and only 1 second to append incremental changes. Surprisingly, this is without even adding my application code yet! It seems that the node_modules ...

Eliminate the cushioning on a single item

I'm currently working on a website and running into a small issue. The main page has a background with a white body in the center, containing padding for the text to prevent it from being right at the border. #content { width: 900px; overflow: h ...