Using jQuery to dynamically add a class depending on the current page's URL

I'm facing a challenge with what seems like a straightforward question, but I just can't seem to figure it out.

All I am trying to accomplish is to incorporate some javascript into the webpage that assigns a class to the main page container based on the URL.

Let's take, for example, a site located at root.com and having the following HTML structure (roughly speaking):

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  </head>
  <body>
    <div id="main" class="wrapper">
      Blah, blah, blah
  </body>
</html>

What I aim to achieve is a script that, when the page equals something like root.com/technology, will apply a class to the main div. This would result in the div appearing as follows:

     <div id="main" class="wrapper tech">

Since I have loaded jQuery, I prefer to use it for this task.

Answer №1

To retrieve the current URL, you can utilize window.location and create a conditional based on its value:

$(function() {
  var currentURL = window.location.href; // obtains the complete URL
  if(/products/.test(currentURL)) {
    $('#main').addClass('highlight');
  }
});

This method employs a regular expression to check if the URL includes a specific term (in this case: products), and if it does, it applies a class to the #main element.

Answer №2

If I were to tackle this problem, here's the approach I would take:

switch (window.location.pathname) {
    case '/technology':
        $('#main').addClass('tech');
        break;
    case '/something':
        // code block
        break;
    case '/somestuff':
        $('#main').addClass('some');
        break;
    default: 
        // code block
}

By following this method, you maintain a tidy codebase and have the flexibility to add new cases effortlessly.

To understand more about window.location.pathname, refer to this resource.

Answer №3

Could a solution like the following be beneficial? As mentioned in another response, simply by executing

console.log(window.location)

, you can access a plethora of information pertaining to your location object

     if(window.location.href=== "root.com/technology") {
         $("#main").addClass("tech");
     }

Answer №4

Utilize the location object in JavaScript to extract the complete URL or specific components of it.

Answer №5

      $(function(){
        var currentUrl = window.location.href;
         $(".swatch-type-selector__list a").each(function(){
                 if ($(this).attr("href") == currentUrl){
                         $(this).addClass("active-swatch");
                 }
         });
    });

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

Webpack can generate separate compiled files in addition to the bundle

Currently, I am utilizing the webpack loader ts-loader to convert typescript source files into a javascript bundle. My goal now is to not only save the compiled javascript bundle but also the individual compiled javascript files. While I have experience ...

Guide on integrating module css with typescript in a Gatsby project

I am working on a GatsbyJS application and currently facing an issue with integrating TypeScript. Although I have resolved most of the problems, I am unable to get the CSS modules to work properly. In my file, I have this import statement that functions c ...

Drop-down functionality in Bootstrap Form becomes unresponsive after screen width is decreased

I recently encountered a strange issue with my simple Bootstrap form. When I resize my browser width to mobile size or view it on a mobile device, the form stops functioning properly. Unfortunately, I am unable to provide any specific code examples at this ...

Modify content of elements by clicking on them with jQuery

Currently, there is a button that triggers the loading of an HTML page into a div with the ID "myDiv". Once loaded, I would like to be able to change the text content of specific tags when they are clicked. For example, clicking on the text within an h2 ta ...

Determine whether a variable includes an alphabetic character

I need to eliminate any results from an array that include alphabetic characters. To do this, I am using the following code: if(gtin.toString().length != 13 || /[a-z\-]+/ig.test(gtin) == true) { gtin = "null"; } Although it works for some variab ...

What is the best way to give this CSS button a "highlight" effect when it is clicked using either CSS3 or JavaScript?

In the HTML page, I have two buttons implemented with the following code: <!-- Button for WIFI projects: --> <a title="WIFI" href="javascript: void(0)" id="showWifi_${item.index}" class="showWifi"> <div class="news_box news_box_01 hvr-u ...

Troubleshooting: Issue with Button Layout in Ionic's ItemSliding Component

How can I create a list item that allows swiping to reveal an archive button? The requirement is for the icon to appear to the left of the text. I'm referring to the documentation on Button Layout: https://ionicframework.com/docs/api/components/item ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

The process of accessing XMLHttpRequest in Angular

How can I enable XMLHttpRequest in Angular? I am trying to access getData.php and encountering the following error: Access to XMLHttpRequest at 'http://localhost:8888/*****/****/getData.php' from origin 'http://localhost:4200' has been ...

develop the following application and execute the npm run dev command, but encounter the error message: "Command failed with exit code 1."

After executing npx create-next-app@latest followed by npm run dev, I encountered the error message Command failed with exit code 1.. Additionally, when trying to access https://localhost:3000, an error stating ERR_CONNECTION_REFUSED was displayed. Further ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

What is the best way to extract multiple values from an input field using jQuery?

Looking to retrieve input field values that are within a foreach loop using jQuery? Below is the HTML structure: @foreach ($products as $product) <div class = "form-row"> <input type="text" name="quantity" ...

Is there a way to add items to an array in React's state using the setState method?

I need assistance with updating an array in React by inserting elements at specific indexes. Here is the current state of my array: this.state = {arr: ['', '', '', '' ]} My goal is to convert arr[index] = 'ran ...

Why does parsing the GET response fail intermittently with Jquery, ajax, and JSON?

Currently, I am encountering an issue with ajax calls using jQuery where the response being returned is a JSON array. In certain scenarios, everything works perfectly fine. However, in other cases specifically in browsers like Firefox and IE11, there seems ...

Ending a tag every x cycle of iteration within Svelte

I am currently developing an application that requires Svelte to close the Row and start a new one every time there are 3 bookmarks. The components I am using are from sveltestrap, including tags such as "Row", "Col", and "Card". <Row> {#each boo ...

Retrieve the element located within a "block" element that is relative to the user's click event, without the

I'm pondering whether it's feasible, but here's my concept: Within my page, there are multiple identical blocks with the same classes, differing only in content. I am unable or unwilling to assign IDs because these blocks are dynamically g ...

stop the interval if conditions are not satisfied

Essentially, I am facing the challenge of clearing an interval for a function called newsCheck when the user is not on the home page. While it may sound simple in theory, this issue has caused significant complications for me. The use of a history API is p ...

"Troubleshooting issue with Ajax call failure to local file on Windows phone 8 when using Cordova version 2.3.0rc

I recently came across an article on this site about porting a WebApp built in PhoneGap to Windows Phone 8. Intrigued, I decided to follow a Getting Started guide available here. In my project, I am utilizing Marionette.js and Cordova 2.3.0rc2. One specif ...

Gulp JS task is generating a NodeError due to the callback being triggered more than once

Error Encountered in Gulp JS Task - NodeError: Callback called multiple times Among the five Gulp JS tasks that I have, one specific task named js_bundle is causing a NodeError. The exact error message is: NodeError: Callback function called multiple ti ...

Dynamic loading with asynchronous JavaScript and XML, along with the ability to drag and drop files

I am looking for help with an issue that I have been unable to solve. The problem I am facing involves creating an UPLOAD DIV on my webpage. I have written the following code: JS Fiddle of my code Code : $(document).on('dragover dragleave dragenter ...