Flipping back and forth between two images within a single HTML file

I am looking to customize my top navbar for two different webpages, the root URL (/) and firstpage (/firstpage). The top navbar contains 2 images that I want to switch based on which page the user is currently on. Here is the code snippet:

<img class="dark" src="/images/icons/IMAGE_home.png">
<img class="light" src="/images/icons/IMAGE1_page2.png">

When a user is on the homepage, they should see the first image and the second image should be hidden. Conversely, when the user navigates to the second page, they should see the second image and hide the first.

Are there any CSS, Angular, or JavaScript techniques that can help achieve this functionality?

Thank you in advance!

Answer №1

Traditionally, a task like this would be handled by a backend script, but it is feasible to achieve using JavaScript and CSS.

To begin, ensure that both images are initially set to be hidden:

.light, .dark {
  display: none;
}

Next, extract the page name from the URL by examining window.location:

var path = window.location.pathname;
var page = path.split("/").pop();

Subsequently, compare against the current page within a conditional statement:

if (page == 'selectedpage') {
   document.getElementsByClassName("light")[0].style.display = 'block';
}
else {
  document.getElementsByClassName("dark")[0].style.display = 'block';
}

In this example, /selectedpage will feature IMAGE_page.png, while all other pages will showcase IMAGE_default.png. The root directory (indicated by a trailing slash) can be verified using if (page) {}.

I trust this explanation proves helpful! :)

Answer №2

Learn how to use jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

JavaScript code:

$( document ).ready(function() {
    if (location.pathname == "/firstpage") {
        $(".light").hide();
        $(".dark").show();
    } else {
        $(".dark").hide();
        $(".light").show();
    }
});

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

Tips for inserting an element into every tier of a multi-layered array

I am faced with a challenging task of assigning an id field to objects within an array that has infinite levels. The rule is simple - for every level, the ID should correspond to the level number starting from 1. { "name": "Anything2&quo ...

Node.js SQLite3 - DB.each() not running the subsequent code block

When running the code snippet below, I am getting the following output: var db = new sqlite3.Database("database.sqlite") console.log("2") db.each("SELECT * FROM gban WHERE id = '"+id+"'", async functi ...

Inquiring about utilizing res.render and invoking functions within an EJS template

Exploring node, I created a practice function in a separate file and imported it to my server.js. With express as my framework, passing the function in the res.render object with a parameter works seamlessly. app.get('/projects', (req, res) => ...

Execute Two Functions When OnClientClick is Triggered

This is a snippet of my current code in progress <asp:LinkButton ID="lnkDel1" Text="Delete" runat="server" OnClientClick="return confirm('Delete this alert?','Confirm');" onClick="lnkDelete1_Click" CssClass="del_lnk" CommandArgumen ...

Resolve the issue of text overlapping on an image when zooming in

There seems to be an issue with overlapping text and images when zooming the page. I have included a screenshot for reference, please take a look and provide a solution. Thank you in advance.https://i.sstatic.net/oVlGN.png Here is the CSS code causing the ...

Navigating to the default landing page using basic authentication middleware in Express

I'm currently working on implementing basic authorization for an entire website using Express. The goal is to have users enter their credentials, and if correct, they will be directed to the standard landing page. If the credentials are incorrect, the ...

Finding the correct index number for the active class - a step-by-step guide

I am currently troubleshooting an issue with my demo. I am having trouble retrieving the correct index number of .carousel-item.active. Even when the second slide is displayed, I continue to receive the index of the first slide. var totalItems = $(&apos ...

Remove any nulls or undefined values from the object

I have developed a custom function that eliminates null and undefined values from an object. However, it seems to be mistakenly removing keys where the value is 0 as well. For instance: { key1: 'value1', key2: 0 } Even though it shouldn&ap ...

Achieving the desired alignment of text and button can be easily done using Bootstrap

Is there a way to align text buttons both to the left side and right side using bootstrap? I have included a screen and code below. I apologize if this question seems simple, but I am new to this field. I would like to know how to achieve this, and it woul ...

Creating an Angular directive that handles asynchronous attribute interpolation

I am facing an issue with my custom directive. In the link function attributes, I am trying to access the value of attributes.user. Here is how the directive is used in my view page: <div my-directive user="{{user.name}}"></div> The user obje ...

Enhancing static SVG with dynamic tooltips using D3.js

Our challenge involves adding tooltips dynamically to a static SVG image when a hover event occurs on an object within the SVG using d3.js in the context of an AngularJS application. The SVG image we are working with is a floorplan, which is quite intrica ...

The limitations of modifying a scope within an ng-if statement versus using a function call in AngularJS

Here are the code snippets demonstrating the toggling of the hideQA value. The value changes correctly in both conditions, but the divs are not hiding properly when using - `<button ng-click="hideQA = !hideQA">Reset</button>` However, if I ch ...

"Tips for positioning the center of a map with the help of external latitude and longitude

I have developed a program that extracts an address from a database. To obtain the latitude and longitude of the address, I utilized geocoder (https://www.npmjs.com/package/geocoder). Now, every time I click a button to retrieve the address, I want the map ...

Photo frame edge

I am in the process of creating a basic website using HTML and CSS. My current task involves taking an image and using it as a page border. Unfortunately, I am unable to share my progress at this moment because I am unsure of where to begin. I understand ...

What are the steps to integrating a repository into the clean architecture design pattern?

I have been following Uncle Bob's clean architecture principles in developing my medical application's API. However, I am facing some challenges in determining where certain components should be implemented. Within my application layer, I have a ...

Creating a bezel design in CSS or Vue: A step-by-step guide

Embedding: https://i.sstatic.net/YfvQP.png Is there a CSS property that can be used to create the same angle as shown in the layout? I looked everywhere in the program but couldn't find this specific property. Tried searching here !: https://i.s ...

Modify the CSS class by adding attributes dynamically instead of directly to the element

I encountered a situation where I needed to apply a css property to a class rather than an element. For example: $('.class_with_css').css({display:'none'}); This code would add the style "display:none" to all elements with the cl ...

Issue encountered while configuring input in ReactJS: the label is conflicting with the input value, causing it to be overwritten when using material.ui components

Hello fellow developers! I am currently facing an issue in my reactJS project. I am using the react-form-hook along with Material-UI's TextField. The problem arises when I input data into a field named cep, triggering a function that fetches content ...

Avoiding the addition of identical objects in the array

I have expertise in JSON, and I need to be able to select multiple skills from a dropdown using model.skills. I have a function called multipleSkills() that pushes the selected values into an array called arrayvalues[], but I want to ensure that duplicate ...

Endless Loading in Node.js on Google App Engine

I have deployed a standard nodejs app (free tier) using cloud shell, but when I try to access https://[ID].du.r.appspot.com/ , it keeps loading indefinitely. app.js: const express = require('express'); const path = require('path'); co ...