Update the class name of an element depending on the URL

Hey there! I'm working on customizing the style of some elements (specifically tds within a table) based on the current URL. Here are the pages I'm targeting:

http:\\domain\site\welcome.html
http:\\domain\site\press.html
http:\\domain\site\contact.html

All these pages share a common table structure and I need to tweak the styling of the tds accordingly.

Here's the HTML setup:

<table>
    <tr>
        <td id="welcome" class="default">Welcome</td>
        <td id="press" class="default">Press</td>
        <td id="contact" class="default">Contact</td>
    </tr>
</table>

And here's the CSS for it:

.default {
//custom settings
}
.current {
//custom settings
}

Basically, if the URL contains the word welcome, I want the td with an id of welcome to have a class of current. I've tried using jQuery but it doesn't seem to be working as expected:

<script src="jquery-1.4.2.min.js">
$( document ).ready(
    function() {
    if (document.URL.indexOf("welcome") > -1)
    {
        document.getElementById("welcome").className = "current";
    }
    else if (document.URL.indexOf("press") > -1)
    {
        document.getElementById("press").className = "current";
    }
    else if (document.URL.indexOf("contact") > -1)
    {
        document.getElementById("contact").className = "current";
    }
});
</script> 

Answer №1

give this a try

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$( document ).ready(
    function() {
if (document.URL.indexOf("homepage") > -1)
{
    document.getElementById("homepage").className = "active";
}
else if (document.URL.indexOf("about") > -1)
{
    document.getElementById("about").className = "active";
}
else if (document.URL.indexOf("contact") > -1)
{
    document.getElementById("contact").className = "active";
}});
</script>

Answer №2

When you pass the src to <script>, your code gets ignored. Update it with the following:

<script src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
     /* add the rest of your code here */
</script>

Answer №3

// Include jQuery library and insert the following code after the HTML in a script tag
var currentPath = window.location.pathname;

function getFileName(url) {
  var lastSlashIndex = url.lastIndexOf("/") + 1;
  var filenameWithExtension = url.substr(lastSlashIndex);
  var fileName = filenameWithExtension.split(".")[0]; 
  return fileName;                                    
}

var pageName = getFileName(currentPath); 
$( "#"+pageName ).addClass( "active" );

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

The image source is not functioning properly to display the image, even though it is working perfectly on

I'm currently attempting to retrieve an image from Instagram. Everything seems to be in order with the image link on Instagram. However, when I try to use it within an img tag, it fails to fetch. One thing worth noting is that this particular image d ...

What is the best way to enable duplicate entries in ng-repeat?

When utilizing stringify, the json data gets formatted and appears in an alert message. However, when attempting to display it in an actual link, it is not showing up. Upon checking the console, an error was displayed stating that "duplicates are not allow ...

Acquire Table Element Using Javascript

I have a HTML table that contains information such as names, addresses, and phone numbers. Within each row of the table, there is a link that can be clicked to open a popover. When a popover is opened, I want to save the name from that particular row. The ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

Utilizing Jquery for draggable/droppable functionality in combination with custom overflow styles

Encountering a challenge with a drag and drop system that utilizes CSS overflow properties to enable vertical scrolling of a list of values. The issue arises when dragging an item between selected and unselected areas, causing the dragged item to disappear ...

Automatically populating form fields with Selenium (less-than-stellar HTML present)

My current task involves: Entering my email Clicking submit If the message "check again later" is displayed, repeat until the message changes to "you are in!" Here's the code snippet I have written so far: PATH = "D:\Program Files (x86)&bs ...

The POST request is coming back as null, even though it includes both the name and

Having issues with a login PHP code where the post method is returning an empty string. Here is my HTML code: <form action="iniSesion.php" method="post"> <div class="form-group"> <input type="email" name="email_" class ...

Troubleshooting Problems with Retrieving Data Using jQuery and

Having trouble fetching information from a JSON file, as the data variable is empty. I have already downloaded the JSON file, so it's not an issue with the server connection. Can anyone point out where I might be going wrong? function handle_geolocat ...

Prevent the automatic inflation of bubbles on the D3 World Map

Currently, I am developing a D3 world map with a zoom feature that allows users to zoom in up to the boundary level of any country or county by clicking on it. I have successfully added bubbles that point to various counties in Kenya, and these bubbles en ...

What is the best way to display JSON data in a Listview control?

What is the best way to display JSON data in a list format? Currently, I am able to retrieve JSON data and display it in an alert dialog. The JSON data looks like this: [{"_id":"5449f20d88da65bb79a006e1","name":"name3","phone":"888888","service":"service ...

Submitting forms automatically with the help of jQuery

I am currently working on creating an autosubmit form similar to Google Instant. The script I am using right now looks like this: $(document).ready(function() { $('#string').change(function(){ var url = $(this).val(); $(&apos ...

Zeroclipboard will fail to copy the text

I seem to be encountering an issue with the Zeroclipboard system. I suspect there might be an error in my code. Even though it indicates that the content has been copied, it actually hasn't been. The code I am currently using is as follows: <scri ...

Access the Windows directory through a custom HTML link

Currently, I am in the process of creating a personalized "website" that contains a collection of links leading to specific items on my computer. When I click on a link, the folder opens within the browser. Is there a way for these links to open Windows Ex ...

Scraping HTML data without <div> tags with Scrapy - how to do it?

After spending hours attempting to extract a specific data set for use with Scrapy in a web scraping project, here is the current python code: bedrooms_info = house_listing.css( '.search-results-listings-list__item-description__charact ...

Technique for Retrieving Hyperlinks from HTML Resulting in Repetitive

I have been working on a web-crawler and encountered an issue while parsing the HTML content to extract links. The method I am using seems to be returning duplicate links, even though the HTML content is correct. Here is the code snippet: public static Ar ...

Focus on the image displayed through instafeed.js

Using the Instafeed.js plugin to create a dynamic Instagram feed. Everything is working smoothly, but I'm struggling to center the images being retrieved by Instafeed. Despite trying various methods, I can't seem to get it to display as desired. ...

Exclusively Bootstrap-Timepicker

Is there a way to create a textbox with a time picker only? I am looking for guidance on how to do this using the following example: http://jsfiddle.net/RR4hw/11/ jQuery("#startDate").on("dp.change",function (e) { jQuery('#endDate').data("DateTi ...

How can Django implement dynamic CSS for a single item that changes its background dynamically?

I am looking to create a single CSS style that can dynamically change its background based on a Django variable. This becomes more challenging when dealing with a:hover. The initial static style.css code appears as follows: .titles-button h2 a { marg ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...