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

Experimenting with media queries but struggling to make them function properly

I am relatively new to CSS and I am experimenting with media queries. Despite following advice on various Stackoverflow posts and other websites, I am unable to make them work. My goal is simple - to change the color of boxes when the screen width falls be ...

Text Changes Size when Expanding

Currently in the process of building a website and facing an issue with the banner placement under the navigation bar. Originally, both divs were perfectly positioned as desired but encountered a problem where upon resizing the browser window, the right di ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

Tips for obtaining the entire date and time on one continuous line without any breaks or separation

Is there a way to retrieve the current date and time in the format of years, months, days, hours, minutes, seconds, and milliseconds like this? 201802281007475001 Currently, I am getting something like: 2018418112252159 This is my code so far: var dat ...

Exploring the power of Angular 2 Directive scopes

When it comes to Angular2, Directives do not come with "scopes", unlike Components. However, in my specific case, I require a Directive to establish a scope. Take a look at my App component - it contains an HTML template, and the foo directive could potent ...

Issue with setting active class on current html page using Bootstrap 5 and Flask

I am currently developing a flask web application and I am focusing on customizing the navigation bar. Utilizing bootstrap 5 for styling purposes, I am attempting to apply the 'active' class when a specific navbar page is clicked with the followi ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

Engaging JavaScript Navigation

I am looking to create an interactive JavaScript menu or image map where users can press down, highlight, and hit enter on four different items to reveal hidden messages. However, I struggle with JavaScript and could really use some assistance. I have alr ...

Is it possible to incorporate Vue and Vuetify into an existing project that requires IE compatibility?

Currently in the process of enhancing a legacy project with new functionality. The front end is currently relying solely on jQuery for all the webpages. I have been tasked with adding another webpage and would like to incorporate Vuetify + Vue due to the i ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Bringing packages from around the world into your Node.js project

In my node.js application, I have several modules where I find myself importing the same package (e.g. moment npm). I'm curious if there is a more efficient way to handle imports by centralizing all dependencies in one place and using them as global ...

What methods do Google and Yahoo use to update the URL displayed in the browser's status bar?

Have you ever noticed that on Google and Yahoo search pages, the URLs of the search result links actually point to google.com or yahoo.com? It's a clever trick they use by adding extra arguments to the URLs that allow for redirection to the actual sea ...

NgOnChanges replaces form control value when user inputs text

In my autocomplete form control component: @Component({ selector: 'app-autocomplete', templateUrl: './app-autocomplete.view.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class AutoCompleteFilterComponent ...

Search for and swap out every item in a multi-tiered array

I am working with an array where the first column represents an id: var mainarray = [ ["1001","P6","P8"], ["1002","P7"], ["1003","P7","P8","P10"], ["1004","P6","P10"], ]; My goal is to replace each 'P' element with its corresponding animal from ...

If every single item in an array satisfies a specific condition

I am working with a structure that looks like this: { documentGroup: { Id: 000 Children: [ { Id: 000 Status: 1 }, { Id: 000 Status: 2 ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...

Enhancing Drag and Drop Functionality with jQuery and CSS Zoom Effect

I am facing an issue in my application with a div that has variable CSS zoom. Due to this, the coordinate space gets disrupted. The page pixel is no longer equal to 1px when hovering over the zoomable area :) This breakdown in the coordinate system is ca ...

What is the most effective method for enlarging elements using Javascript?

I have come across many different methods for expanding elements on webpages, such as using divs with javascript and jquery. I am curious to know what the most optimal and user-friendly approach is in terms of performance, among other things. For instance ...

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

Forming a header area by utilizing a 960 Grid container

I'm in the process of designing a website utilizing the 960 Grid system. The header consists of three parts: the logo, the navigation, and the login form. I've implemented media queries to center both the logo and the login section when the pag ...