Attempting to assign an active class to a menu item

I've been struggling for 2 hours to create a dynamic menu, but unfortunately, I haven't had any success. That's why I decided to seek some assistance. I have an HTML menu along with some JS and CSS...

$(function() {
  var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/") + 1);
  $("#index li a").each(function() {
    if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
      $(this).addClass("active");
  })
});
.active { font-weight:bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='index'>
  <div class='container'>

    <div class='top'>
      <h1><a href='/' title='The Maths Project'>The Maths Project</a></h1>
    </div>
    <ul class='section active_section' id='section_2'>
      <li><span id='section_title_2' class='section_title'><a href='#' id='section_link_2'>Against the odds.</a></span>
        <ul>
          <li id='exhibit_106' class='exhibit_title'><a href="../against-the-odds/introduction"> &rarr; Introduction</a>
          </li>
          <li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> &rarr; Deriving functions</a>
          </li>
          <li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> &rarr; Exploiting odds</a>
          </li>
        </ul>
      </li>
    </ul>
    <ul class='section' id='section_3'>
      <li><span id='section_title_3' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_3'>Remembering everything.</a></span>
        <ul>
          <li id='exhibit_104' class='exhibit_title'><a href='../against-the-odds/black-swans'>black swans</a>
          </li>
          <li id='exhibit_72' class='exhibit_title'><a href='../against-the-odds/in-here-it-is-yesterday'>in here it is yesterday </a>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

Despite my efforts, I can't seem to get the "a" link of the current page to appear bold in the menu. Any help would be greatly appreciated,

Sincerely,

Jack

Answer №1

I'm not entirely sure what you're asking, but it sounds like you want to add an active class to a menu item. Try using the code snippet below:

$('#navlist a').click(function(e) {
    e.preventDefault(); 
    $('#navlist a').removeClass('selected');
    $(this).addClass('selected');
});
.nav { 
    color: green;  
}
.selected { 
    color: red; 
}
.san ul li{
    float:left;
    margin-right: 25px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<div class="san">
    <ul id="navlist">
        <li><a class="nav" href="">Home</a></li>
        <li><a class="nav" href="">About Us</a></li>
        <li><a class="nav" href="">Services</a></li>
        <li><a class="nav" href="">Contact</a></li>
    </ul>
</div>

Answer №2

This code snippet is used to fetch the page name:

var pgurl = window.location.href.substr(window.location.href
                  .lastIndexOf("/") + 1);

The same logic needs to be applied to all links on the page to check for a match:

$("#index li a").each(function() {

  var aurl = $(this).attr("href").substr($(this).attr("href")
                    .lastIndexOf("/")+1);

  if (aurl == pgurl || aurl == '')
    $(this).addClass("active");
})

Adjusted version of the snippet below (adjusted for location.href mismatch)

$(function() {
  //var pgurl = window.location.href.substr(window.location.href
  //                  .lastIndexOf("/") + 1);
  var locationhref = "mysite.com/against-the-odds/introduction"
  var pgurl = locationhref.substr(locationhref.lastIndexOf("/")+1);
  $("#index li a").each(function() {
    var aurl = $(this).attr("href").substr($(this).attr("href")
                      .lastIndexOf("/")+1);
    //console.log(aurl)
    if (aurl == pgurl || aurl == '')
      $(this).addClass("active");
  })
});
.active { font-weight:bold;color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='index'>
  <div class='container'>

    <div class='top'>
      <h1><a href='/' title='The Maths Project'>The Maths Project</a></h1>
    </div>
    <ul class='section active_section' id='section_2'>
      <li><span id='section_title_2' class='section_title'><a href='#' id='section_link_2'>Against the odds.</a></span>
        <ul>
          <li id='exhibit_106' class='exhibit_title'><a href="../against-the-odds/introduction"> &rarr; Introduction</a>
          </li>
          <li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> &rarr; Deriving functions</a>
          </li>
          <li id='exhibit_83' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> &rarr; Exploiting odds</a>
          </li>
        </ul>
      </li>
    </ul>
    <ul class='section' id='section_3'>
      <li><span id='section_title_3' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_3'>Remembering everything.</a></span>
        <ul>
          <li id='exhibit_104' class='exhibit_title'><a href='../against-the-odds/black-swans'>black swans</a>
          </li>
          <li id='exhibit_72' class='exhibit_title'><a href='../against-the-odds/in-here-it-is-yesterday'>in here it is yesterday </a>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

Answer №3

Make sure to give this a try and see if it functions properly.

$(function() {
    var currentPage = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
    $("#index li a").each(function() {
        var href = "";
        if($(this).attr("href") != '')
            href = $(this).attr("href").substr(($(this).attr("href").lastIndexOf("/")+1);
            if (href == currentPage || href  == '')
                  $(this).addClass("active");
      })
  });

Answer №4

To update the font weight of links, loop through all the links and change them to normal when clicked. Then set the font weight to bold for the link that was clicked.

$().ready(function () {
        $("ul>li").click(function () {
            $("ul>li").css("font-weight", "normal");
            $(this).css("font-weight", "bold");
        });
    });

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

How is a scrollbar's color determined in Firefox?

Short version: Firefox displays an intriguing behavior where it automatically styles the scrollbar in lime green but not light green. The question arises, why does it render one color but not the other? While responding to another query, I discovered that ...

"Comparison: Utilizing HTML5 Video Player with IE8 Embed Fallback versus Implementing Fixed

This dilemma has me at my wit's end. In an HTML5 Video element, I've included an mp4, ogg, and an embedded mp4 fallback. However, on the embed fallback in IE8, all my attempts to position the fixed element (#fixed) above it with z-indexing have f ...

Utilizing React Recharts to create personalized tooltips

In my current project, I am looking to create a custom tooltip to replace the default one in recharts. The default tooltip that I want to change is shown below: https://i.stack.imgur.com/TjTiL.png I would like the new custom tooltip to look like this: ...

Vue data set is displaying as undefined

Having an issue passing the value and index of an object to a vue method. The method successfully displays the value, but the index remains undefined. Looking for guidance on where the mistake might be. JAVASCRIPT: <div class="select is-info"> ...

Running a 2D JavaScript game script on a React page - A step-by-step guide!

I am facing a challenge with my website that features a game coded entirely in javascript. Despite my efforts to switch the site from an HTML layout to a more modern React design, I can't seem to get the game to display correctly. In the original HTM ...

What is the best way to implement conditional hook usage in React?

Having two hooks at my disposal, useLocalStorage and useQuery, I find myself wondering about conditionally utilizing one of them based on an input prop. I'm considering writing the following: const [value, setValue] = localStorage ? useLocalStorage() ...

What is the best way to transfer a querystring received in Node.js to a page being shown through res.render?

I have a nodejs file where I am rendering a page named foo.html. Within foo.html, I am using ajax to retrieve variables from a querystring and load an appropriate xml document based on those variables. The issue arises when I run my nodejs server, which is ...

Ever since I switched to a different monitor, my Javascript has suddenly stopped functioning

I'm encountering an issue where my JS stops working every time I switch displays within a single HTML file. I've attempted to replace the HTML onclick call with a JavaScript function, but the problem persists. Update: Apologies for the unclear e ...

Show schedule in an HTML chart

I'm currently working with a table that displays the current status of a request. An example of how the table looks in HTML is shown below: https://i.sstatic.net/daDHy.png The table itself is quite simple, but I am having trouble figuring out how to ...

Is it possible to create a dedicated page in Next.js using static site generation (SSG)?

The static-site generation (SSG) feature of Nextjs allows for fetching data at build time, resulting in pre-rendered pages using getStaticProps and getStaticPaths. Imagine having a blog with numerous articles that remain static, while some may be updated ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

Using Firebase Realtime Database, this React dropdown menu is populated with options in real-time. Combining the features

I'm currently facing an issue with a dropdown that is supposed to loop through data fetched from the Firebase realtime database. The goal is to assign a selected value to a Formik form for saving it to another object in the database. In my database, ...

Accessing a JSON string correctly using JavascriptSerializer in JavaScript

When working with JavaScript, I encountered an issue where the data retrieved from a data table and converted to javascriptSerializer was not refreshing correctly when changing dataset selection parameters. The problem occurred when trying to populate a ne ...

Utilizing Laravel 8 for seamless file uploads with AJAX on onchange event

I'm trying to implement a feature in my Laravel 8 application where users can upload multiple files using the onchange event. Is it possible to achieve this functionality with just the onchange event? Below is the HTML form I currently have. Any assis ...

Is there a way to show an alert indicating the location of the element that was clicked on the screen?

Here is an example I am working on: link HTML CODE: <ul> <li id="#bar"> <img src="http://theimageconference.org/wp-content/uploads/2014/01/images-50x50.png"width=50 height=50></img> <p>ELEMENT 1</p&g ...

Retrieving the value of a radio button using JavaScript

I am working with dynamically generated radio buttons that have been given ids. However, when I attempt to retrieve the value, I encounter an issue. function updateAO(id2) { var status = $('input[name=id2]:checked').val(); alert(status); ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

The responsive design of Bootstrap NavBar seems to be malfunctioning when viewed on an iPhone device

Having an issue in Bootstrap Studio that I can't seem to resolve. I've seen recommendations to add the following meta tag to the <head> section: meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0", bu ...

CSS3 problem with using transparent PNGs as border images

Currently, I am implementing the border-image property using a PNG image that contains a transparent section. The issue arises when the background-color of the div is set to black. Upon applying the border-radius, the transparent section of the pattern dis ...