Using JQuery to apply a CSS class to a designated webpage

In an effort to achieve a responsive design, I am seeking to add an active class to an unordered list item based on the specific page that the user is viewing. Essentially, I want to implement conditional formatting using jQuery while learning on MAMP.

Currently, I am following a slow method...

HTML

<nav id="main-site-nav" class="main-menu">
 <ul>
  <li><a href="index.php" class="crnt-page">Home</a></li>
  <li><a href="/services.php">Services</a></li>
  <li><a href="/certification.php" >Certification</a></li>
  <li><a href="/customers.php">Customers</a></li>
  <li><a href="/contact-me.php">Contact Me</a></li>
 </ul>
</nav>

CSS

#main-site-nav .crnt-page {
 color: #E8A317;
 text-decoration:none;
}

I currently have to manually add the class for each list item. My goal is to streamline this process by implementing it in my main.js file at the bottom of the page. Any assistance would be greatly appreciated.


UPDATE!

This PHP solution worked well. However, I am considering migrating it to Wordpress.

<nav id="main-site-nav" class="main-menu">
  <ul>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo 'class="crnt-page"';?>href="index.php">Home</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'services.php')) echo 'class="crnt-page"';?>href="/services.php">Services</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'certification.php')) echo 'class="crnt-page"';?>href="/certification.php">Certification</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'customers.php')) echo 'class="crnt-page"';?>href="/customers.php">Customers</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'contact-me.php')) echo 'class="crnt-page"';?>href="/contact-me.php">Contact Me</a></li>
  </ul>
</nav>

Appreciate the prompt responses! Now I just need to familiarize myself with the pre-formatted code option in Stack Overflow :)

Answer №1

If you want to achieve this with PHP, here's an example:

Check out the PHP code snippet below:

<nav id="main-site-nav" class="main-menu">
 <ul>
  <li <?php if($_SERVER["SCRIPT_NAME"] == 'index.php') echo 'class="crnt-page"'; ?>><a href="index.php" class="crnt-page">Home</a></li>
  <li <?php if($_SERVER["SCRIPT_NAME"] == 'services.php') echo 'class="crnt-page"'; ?>><a href="/services.php">Services</a></li>
  <li <?php if($_SERVER["SCRIPT_NAME"] == 'certification.php') echo 'class="crnt-page"'; ?>><a href="/certification.php" >Certification</a></li>
  <li <?php if($_SERVER["SCRIPT_NAME"] == 'customers.php') echo 'class="crnt-page"'; ?>><a href="/customers.php">Customers</a></li>
  <li <?php if($_SERVER["SCRIPT_NAME"] == 'contact-me.php') echo 'class="crnt-page"'; ?>><a href="/contact-me.php">Contact Me</a></li>
 </ul>
</nav>

Answer №2

Consider implementing something like the code snippet below (although not verified):

var currentURL = document.location.href.split('/').pop().toLowerCase();

$('#main-navigation a').filter(
    function(){
        return currentURL == this.href.split('/').pop().toLowerCase();
    }).addClass('current-page');

However, it may be more efficient to handle this on the server-side (during page generation).

Additional Resources:

Answer №3

To quickly customize each page, consider assigning a class to the body tag on every page like so:

<body class="page-services">

Next, add specific classes to either list items or anchor tags as shown below:

<li class="page-services"><a href="..."></a></li>
<li class="page-certification"><a href="..."></a></li>

In your script, you can simply write:

$(document).ready(function() {
    var currentClass = $("body").attr("class");
    $("li."+currentClass).find("a").addClass("current-page");
});

There are various approaches to achieving this outcome, so feel free to explore other methods depending on your existing class structure.

Answer №4

Here is a solution that has been effective for me:

<style>.blue {background-color: blue;}</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
</head>
<body>
  <ul>
    <li><a href="home.html">Home</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="services.html">Services</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>

<script type="text/javascript>
  var page = /\/([^\/]+)$/.exec(document.location.href)[1];
  $('a[href="' + page + '"]').addClass('blue');
</script>

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

JavaScript form validation ensures that the data entered into a

My "this is required / missing fields" error message is triggering on focus out even though there is text entered into the field. I am confident it's a small issue that I am overlooking, but I can't seem to figure it out! I acknowledge that I am ...

Hide div element based on its identifier

I've come across multiple questions similar to mine, but none of the solutions seem to fit my specific needs. I require the collapsed content to be located outside of the header container. Here is how my setup looks: <div id="buttonRow"> &l ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

a solution to the focus/blur issue in Firefox's browser bug

I have created the following script to validate if a value entered in an input field already exists in the database. $('#nome_field').blur(function(){ var field_name=$('#nome_field').val(); $.ajax({ url: " ...

How do you retrieve the font-size value in percentages using jQuery's `css()` method for the element `e`?

When using the $(e).css('font-size')) method, how can I retrieve the font size as it appears (100% in my example)? It currently returns it as 100% of 16px which equals to 16px. jQuery ( function($) { alert($('div').css(&ap ...

Designing a uniquely shaped button

Is there a way to design a button with a slightly irregular shape? The current CSS for my button creates a basic rectangle like this: .btnclass { width:100; height:40; } However, I would like it to have a more unique appearance such as this: ...

Activate the zoom feature in jquery mobile

I am looking to implement the standard zooming effect in jquery mobile for my iOS iPhone app using jqm 1.3.2. After attempting the following: <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-s ...

What is the purpose of applying the two unique class names (root and disabled) to the DOM in order for it to function correctly?

When it comes to customizing components using material-ui, the process can be a bit tricky. Here's how you can do it: const styles = { root: { '&$disabled': { color: 'white', }, }, disabled: {}, // This is i ...

Tips on revealing div elements using a slide-down animation exclusively with JavaScript

I am looking to display a div with a slide-up effect using JavaScript (not jQuery) when clicked. Here is the HTML code I have: <div class="title-box"><a href="#">show text</a></div> <div class="box"><span class="activity- ...

Launching Links in Browser Using Cordova in Android Platform

I am facing an issue with the inAppBrowser on Android. Despite setting it up correctly, using _blank or _system still results in the webpage loading within the app instead of opening in an external browser. Here is the relevant code: <a href="#" rel=" ...

Exploring hierarchical information within a JSON response from a Wiki API

As a newcomer to this field, I am currently exploring ways to access Wikipedia's API for extracting the value of "extract" and adding it to an HTML element dynamically. The challenge lies in the fact that the information is subject to change based on ...

Is it possible to fill dropdown menus on a webpage using jQuery or JavaScript without the need for an ajax call?

Currently, I am looking to populate multiple dropdown lists using jQuery when the page loads rather than relying on ajax responses to events. My Controller is responsible for creating several List objects that will be used for these dropdowns. Right now, I ...

Uploading files using C# and data streaming

I am exploring the various methods of file uploading in .NET, such as using HttpPostedFile and a HttpHandler. I want to delve into the technical details of how this process actually works. Specifically, I am curious about how the data is written to a file ...

Transfer a variable from one PHP page to another and navigate between the two pages

I am just starting to learn PHP and I have a scenario where I need to retrieve the last ID from the database. For each ID, I need to fetch the state and the associated link. If the state is equal to 1, then I need to extract some content from the link (whi ...

Can @keyframes percentage be determined using a CSS variable?

My animation is responsive to the number of characters present It functions properly with 20 characters: const text = '20 characters length' const speed = 0.1 const $container = document.querySelector('.wave') $container.style.setPr ...

transform ajax data into an array structure

I need to convert the values retrieved from an AJAX call into an array so that I can access and format them accordingly. $(document).ready(function() { $('#documenter_nav > li a').click(function(){ var url = $(this).attr('data- ...

Create a layout of div elements aligned to the right, utilizing a parent container div that automatically adjusts its size to fit the

My attempt at this design: https://jsfiddle.net/j75hxxa2/1/ The goal is to have the block positioned on the right side and eliminate the extra gray area. By applying float: right; To the parent element, the child elements become very small. Trying ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

Leveraging Excel VBA to manipulate the selection in a dropdown menu on a webpage

Is there a way to select a specific value using Excel VBA? <div class="drpCompanies"> <select class="selectBox homepage selectCompanies" style="padding-bottom: 10px; padding-left: 10px; padding-right: 10px; padding-top: 10px"> <op ...

Align text vertically in a responsive absolutely-positioned div using CSS

Is there a way to horizontally center text inside a responsive div without relying on new CSS3 tricks? Check out this fiddle for reference: http://jsfiddle.net/M8rwn/ .iosSlider { position: relative; overflow: hidden; width: 100%; height: ...