Switch the ID Class Depending on the URL - Image Replacement with URL Detection -

My Goal: I am attempting to dynamically assign a different class to the div element "logoswap" based on the current URL (e.g., foo.com/item1).

Below is the code I have put together, but it appears to be flawed. While I am more proficient in XHTML/CSS and have some experience with PHP, I am not an expert in JavaScript. Unfortunately, I cannot utilize PHP for this task even though I know it could be done with PHP. I have a PHP version that accomplishes what I need, but I am struggling to integrate the PHP functionality properly.

Essentially, I am trying to display a different logo depending on the directory or URL. The image does not necessarily have to be called in as a background element using a CSS class, I just need it to change based on the URL parameter mentioned above...

  $(function() {
  var url = location.pathname;

  if(url.indexOf('item1') > -1) {
    document.getElementById("logoswap").className += " class1";
   }

  elseif(url.indexOf('item2') > -1) {
    document.getElementById("logoswap").className += "class2";
   }

  elseif(url.indexOf('item3') > -1) {
    document.getElementById("logoswap").className += "class3";
   }

  elseif(url.indexOf('item4') > -1) {
    document.getElementById("logoswap").className += "class4";
   }

  elseif(url.indexOf('item5') > -1) {
    document.getElementById("logoswap").className += "class5";
   }

  else {
    document.getElementById("logoswap").className += "class1";
   }

  });

This is my current implementation which may not be the most aesthetically pleasing.

I have reached out because I require assistance in improving it.

Answer №1

Applying CSS Class Based on URL Pathname

You can check out the solution in action on jsfiddle.

Here's an example where utilizing numeric expressions could be beneficial, although it doesn't directly relate to the previous question.

$(function() {
  var rgx = /item(\d+)$/,
      url = location.pathname,
      id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
  $("#logoswap").addClass("class" + id);
});

UPDATE:

Given the new information, you might require an array of values that align with the intended class names.

$(function(){
  // Creating a string array
  var matches = "brand1 brand2 brand3".split(" "),
      url = location.pathname.match(/\w+$/)[0], // retrieving the last item
      id = matches.indexOf(url),
      className = matches[(id > -1) ? id : 0];
  $("#logoswap").addClass(className);
});

To put this into effect, certain prerequisites must be met such as ending paths with a number as specified here and ensuring image accessibility along with defining styles for each possibility.


CSS Configuration

#logoswap {
  height: 200px;
  width: 200px;
}
.class1 {
  background-image: url(/path/to/default.jpg);
}
.class2 {
  background-image: url(/path/to/second.jpg);
}
.brand1 {
  background-image: url(/path/to/brand/1/logo.jpg);
}
...

Without jQuery

If jQuery isn't being utilized, you can turn to using window.onload.

(function(){
  var old = window.onload;
  window.onload = function(){
    old();
    var r = /item(\d+)$/,
        url = location.pathname,
        id = (r.test(url)) ? url.match(r)[1] : '1';
    document.getElementById('logoswap').className += "class" + id;
  };
})()

I want to emphasize the importance of understanding Regular Expressions for anyone working with code like this. They are incredibly useful across various programming languages.

Answer №2

There's absolutely nothing wrong with your current setup. However, you could enhance it by implementing the following:

$(function() {
    var currentURL = window.location.pathname;
    var logoElement = document.getElementById("logoswap");
    var index = 6;

    logoElement.className = "class1";

    while(index--)
    {
        if(currentURL.indexOf("item" + index) > -1) {
            logoElement.className = "class" + index;
        }
    }
});

I hope this solution proves to be helpful for you.

Answer №3

To include an id to the body of a webpage using solely HTML and CSS, you can do so by adding it (or appending it with JavaScript) in this manner:

<body id="item1">

In your CSS file, establish a selector like this:

#item1 #logoswap {
    // class1 CSS
}

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

What is the process for creating a loading screen using three.js?

I have a plethora of textures and models that need to be loaded into my project. In order to display a progress bar while everything is loading, I believe the LoadingManager will work perfectly as it monitors the progress of all loaded assets. Currently, ...

Having trouble with Next.js getStaticProps? Getting a TypeError that says "Cannot read properties of undefined (reading 'map')"?

My latest project was built using create-next-app as a base. In the Blog.js page, I attempted to fetch data from https://jsonplaceholder.typicode.com/posts by utilizing the getStaticProps() function. I followed the instructions provided in this guide: htt ...

Properly maintaining child processes created with child_process.spawn() in node.js

Check out this example code: #!/usr/bin/env node "use strict"; var child_process = require('child_process'); var x = child_process.spawn('sleep', [100],); throw new Error("failure"); This code spawns a child process and immediately ...

Retrieving every item from an unnumbered inventory in PHP

I have a list of tag clouds: <ul #id = "tag-cloud-list"> <li class = "items">Music</li> <li class = "items">Lion</li> <li class = "items">Dwarf</li< </ul> This tag cloud list was generated using ...

What is the best method for sending the styled and checked option via email?

Just finished customizing the checkboxes on my contact form at cleaners.se/home. Here's my question: If I select "telefon," how can I ensure that this option is sent to my email? In Contact Form 7, I used to simply type a shortcode. Is there a simila ...

Working with decimal numbers in jQuery and JavaScript: a basic guide

Following a button click, I have implemented a function that updates the displayed number: var initial_price = parseFloat($("#current_price").text()); var added_price = initial_price + 1.01; $("span#current_price").text(added_price); This is the ...

What are some methods to boost height in the opposite direction?

I'm looking for a way to make this div fold from top to bottom. How can I achieve this effect without the height increasing abruptly? var box = document.getElementById("box"); box.onmouseover = function(){ box.className = "expand"; } box.o ...

`Position the login page contents in the center`

Having some difficulty centering the content on my login page. Can you assist with styling? I would like to have the input fields centralized and compact, similar to a standard login page. Also, I am encountering an issue with using different Bootstrap ver ...

Creating a cutoff with CSS: A step-by-step guide

Is there a way to create something similar using only CSS? https://i.stack.imgur.com/N9c6W.png I have no clue on how to achieve this. Any assistance would be greatly appreciated. ...

Revamping the Bootstrap admin template

Is there a way to customize this Bootstrap 3 admin template? https://getbootstrap.com/docs/3.3/examples/dashboard/ I want to make some changes like removing the top fixed navbar and shifting everything up by 50px (as defined in dashboard.css). However, I ...

Encountering issues with @media queries: W3C CSS Validation Service is reporting an error

I attempted to adjust the width of the wrapper div using @media queries based on different screen sizes Here is where I implemented this code @media screen and (min-width:768px) and (max-width:1023px) { #wrapper { width:625px; padding-left: 50px; ma ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

GraphQL query must receive an object for the Mongo filter, but instead, it received a string

Is there a way to pass a filter option to MongoDB using GraphQL? I attempted to do it in a certain way, but encountered an error that stated: "message": "Parameter \"filter\" to find() must be an object, got {email: "<a href="/cdn-cgi/l/email ...

What is the best way to align bootstrap col-md-4 and col-md-5 in the center of a webpage?

I am facing an issue with my two bootstrap items, one col-md-5 and the other col-md-4. Despite trying to center them in the middle of the page, they are currently positioned with col-md-4 on the left side and col-md-5 in the middle. Does anyone have a solu ...

What is the best approach to create a customized array using or not using spread syntax in this scenario?

Any suggestions on simplifying and enhancing the code provided below? The current code works as intended when myarr.length === 2: [...myarr[0].arrk.map(myfunc), ...myarr[1].arrk.map(myfunc), ...myarr[2].arrk.map(myfunc)] How can we adjust the above code ...

The feature for height is not functioning correctly on IOS devices, specifically iPhones

Recently, I designed a website on CodePen which you can view here. My goal was to make it responsive across all platforms, but I encountered an issue specifically with IOS. It seems like a single div covers the entire page on IOS and some height elements a ...

The blur() function in -webkit-filter does not seem to function properly in Vue.js

I'm having trouble implementing the -webkit-filter: blur() property. I tried using "filter" instead, but it still isn't working. Could this be a limitation of Vue.js or are there any other solutions available? <template> <div class=&qu ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...

Easier way to transform tables into panels for compact browser sizes

Currently, I am utilizing the ASP.NET MVC framework to develop an application. My goal is to showcase a table on a webpage that seamlessly transitions into a panel view for each individual record as depicted in the images below. For wider browser widths: ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...