Tips for identifying a webpage and making class modifications based on it

I am working on a customized bar with 4 distinct parts. Each part corresponds to a different page on the website. I want each part of the bar to change color based on which page the user is currently browsing. For example, if the user is on page A, I want the background of the service-specificBar-tab to be red, and if they are on page B, I want it to be purple.

How can I achieve this functionality? Is there a way to change the color of the service-specificBar-tab without explicitly detecting the current page?

#gray {
background: #f9f9f9;
width: 100%;
height: 700px;
position: relative;
}
#service-specificBar-container {
position: relative;
top: 300px;
width: 100%;
padding: 25px 0;
}
#service-specificBar {
width: 100%;
height: 100px;
border: 1px solid black;
}
.service-specificBar-tab {
width: 25%;
height: 100%;
display: inline-block;
margin: 0;
padding: 0px;
}
.service-specificBar-tab:nth-child(2) {
background: blue;
}
.service-specificBar-tab:nth-child(4) {
background: green;
}
<div id="gray">
<div id="service-specificBar-container">
<div id="service-specificBar"><div class="service-specificBar-tab">A
</div><div class="service-specificBar-tab">B
</div><div class="service-specificBar-tab">C
</div><div class="service-specificBar-tab">D
</div>
</div>
</div>
</div>

Answer №1

To obtain the exact URL, utilize window.location.href, and then create a switch statement to modify the color of a specific div accordingly. It is advisable, though not obligatory, to assign an id to each service-specificBar-tab.

For instance:

switch( window.location.href ){
    case "http://sample.com/myInitialPage":
        $("#initialItemId").addClass("active");
        break;

    case "http://sample.com/myOtherPage":
        $("#otherItemId").addClass("active");
        break;
}

If you prefer distinct colors for each active tab, define it in your CSS file

#initialItemId.active {
    background-color: blue;
    /* active styles */
}

If there is a chance that the URL may have a hash attached to it, you can remove it using this method:

var url = window.location.href.split("#")[0];

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

Use CSS to apply hover effects to multiple sections of text at the same time

Is there a way in CSS to apply the hover state to one part of HTML text when another part is hovered over, both sharing the same class? I have a block of text in HTML that is broken down into individual words, each word linked to a specific CSS class. It ...

Is it possible to personalize a select button for both iOS and Android mobile platforms?

I've implemented a dropdown on my website for the desktop version and it works fine. However, I want to replace this dropdown with a select button on iPad and iPhone, as I prefer how it looks on those devices. Is it possible to style the select butto ...

Choosing several checkboxes and populating an array with values - HTML and JavaScript

I am working on a modal dialog that displays a table with checkboxes next to user names. My goal is to link these checkboxes to the respective names so that when a box is checked next to 'Jon' in the table, the name 'Jon' gets selected. ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Animate a div component sliding out while seamlessly introducing a new one using React

For my signin page, I've set it up so that users first enter their username and then click next to trigger a fluid slide animation which reveals the password field from the right. Although the separate components are already coded and the animation wo ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

Issue with Magento cart not updating after making a POST request using JQuery's ajaxSubmit function

Recently, I encountered a unique requirement that led me to use ajaxSubmit in order to add products to the Magento shopping cart. Despite using return true; as a callback, the shopping cart page displays empty until manually refreshing the page from the br ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

Tips for adjusting the size of Bootstrap 5 card to fit various image sizes responsively

I am facing an issue where I have four images of different sizes placed in 4 cards in a row. Due to the varying heights of the images, the cards appear untidy. I am looking for a way to fix this problem while ensuring that the layout remains responsive. Be ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project. In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the stati ...

Incorporating text into the border without increasing the spacing

I managed to create a unique CSS shape using clip paths as the border of a div. However, I am now facing an issue where I cannot add text to this border without it getting cut off due to the way the shape was created (possibly because of overflow: hidden). ...

Material design for Angular applications - Angular Material is

Recently, I decided to explore the world of Angular and its accompanying libraries - angular-material, angular-aria, and angular-animate. I'm eager to experiment with this new styling technique, but it seems like I've hit a roadblock right at the ...

Attempting to retrieve the current time using JavaSscript

const currentTime = new Date(); const hours = now.getHours(); Console.log(hours); This block of code is returning an error message... Uncaught ReferenceError: now is not defined Please note that this snippet is written in JavaScript. I attempted to us ...

Basic HTML code that displays either one or two columns based on the width of the screen

My monitoring website displays dynamic rrd graphs in png format with fixed dimensions. I am looking to adjust the layout based on browser window size - showing the graphs in 1 column if the width is below a certain threshold, and in 2 columns if it exceed ...

Leveraging createMuiTheme to customize default styles for divs, paragraphs, and the body element

Seeking guidance on customizing a Material UI Theme I aim to modify the default styles for elements like <body>. Currently, at the root of my React tree: import theme from './mui-theme' ReactDOM.render( <Router> <ThemePr ...

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

IDEA 2021.2 NPM SCRIPTS: Looks like there are no scripts available

Searching through the npm scripts, I am unable to locate any, however package.json does contain: ...