Ways to emphasize a navigation menu item that points to the same URL

One issue I am facing is with my navigation menu, where two items are pointing to the same URL.

<div id="LEFTmenu">
  <ul>
    <li><a href="app/link1">Page1</a></li>
    <li><a href="app/link2">Page2</a></li>
    <li><a href="app/link3">Page3</a></li>
    <li><a href="app/link2">Page4</a></li>
    <li><a href="app/link5">Page5</a></li>
 </ul>
</div>

This means that Page2 and Page4 are both linked to the same URL.

[Update]

I am now looking for a way to make the selected link stand out when the user clicks on either Page2 or Page4, taking into consideration that the request then goes to link2. This needs to be done without using click events and preventDefault.

Since it's an MVC application, the request goes through a servlet (controller) and renders a JSP file. In this case, both Page2 and Page4 are linking to the same JSP file.

Below are the relevant files:

nav.jsp -- Navigation menu link2.jsp -- Contents specific to link2

I apologize for not providing these details earlier.

Answer №1

By clicking, you have the ability to extract the href attribute from the current anchor tag and find it in your menu.

$(function() {
  $('#LEFTmenu a').on('click', function(e) {
    var $this = $(this),
        $ul = $(this).parents('ul'),
        href = $this.attr('href');
    $ul.find('a[href="'+href+'"]').css('background', 'lime');

    e.preventDefault(); // prevent going to the link
  });
});

See a live demonstration on JS Bin

Answer №2

If you're looking to specifically emphasize the link that is clicked, the solution provided in the previous response should work perfectly for you. However, if your goal is to highlight a specific Anchor based on its href attribute value, you can achieve this by checking for the href attribute using jQuery:

$('#LEFTmenu a').click(function(e){
  e.preventDefault();
  if ($(this).attr("href") == "app/link2") {
    $(this).css("color", "yellow");
  }
});

Answer №3

Try out this example:

HTML

<div id="LEFTmenu">
   <ul>
     <li><a href="app/link1">Page1</a></li>
     <li><a href="app/link2">Page2</a></li>
     <li><a href="app/link3">Page3</a></li>
     <li><a href="app/link2">Page4</a></li>
     <li><a href="app/link5">Page5</a></li>
   </ul>
</div>

JS

To see the changes, include e.preventDefault();.

$('a').click(function(e){
  $('a').css('background-color','');
  e.preventDefault();
});
$('a[href="app/link2"]').click(function(e){
     $('a').css('background-color','');
    $(this).css('background-color','yellow');
    e.preventDefault();
});

You can access the working solution here

Answer №4

$(function() {
  var $menuLinks = $('#LEFTmenu a');

  $menuLinks.on('click', function(e) {
     e.preventDefault();

     if ($(this).attr('href') === 'app/link2') {
       $(this).addClass('highlight');
     }
    
     $menuLinks.not(this).removeClass('highlight');
  });
});
.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<div id="LEFTmenu">
  <ul>
    <li><a href="app/link1">Page1</a></li>
    <li><a href="app/link2">Page2</a></li>
    <li><a href="app/link3">Page3</a></li>
    <li><a href="app/link2">Page4</a></li>
    <li><a href="app/link5">Page5</a></li>
 </ul>
</div>

You can enhance the conditional statement further by using pure Javascript instead of jQuery, depending on browser support (classList not supported in IE 9). While not necessary for performance, it's beneficial to reduce reliance on jQuery:

if (this.getAttribute('href') === 'app/link2') {
  this.classList.add('highlight');
}

UPDATE:

This dynamic alternative improves upon the previous method. By looping through all links except the clicked one using some(), the script checks if any of them match the current link. Based on the result (true or false), it determines whether to add the highlight class:

$(function() {
  var $menuLinks = $('#LEFTmenu a');

  $menuLinks.on('click', function(e) {
    e.preventDefault();
    
    var that = this;
  
    var linkHasDuplicate = [].some.call($menuLinks.not(this), function(elem) {
      return elem.getAttribute('href') === that.getAttribute('href');
    });
    
    if (linkHasDuplicate) {
      $(this).addClass('highlight');
    }
    
    $menuLinks.not(this).removeClass('highlight');
  });
});
.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<div id="LEFTmenu">
  <ul>
    <li><a href="app/link1">Page1</a></li>
    <li><a href="app/link2">Page2</a></li>
    <li><a href="app/link3">Page3</a></li>
    <li><a href="app/link2">Page4</a></li>
    <li><a href="app/link5">Page5</a></li>
 </ul>
</div>

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

Having difficulty with PHP code, attempting to output some HTML while also opening a file and displaying its contents

I'm completely new to PHP and I've been experimenting with some code to display button elements that, when pressed, should open a file and write a number to it. Unfortunately, the code doesn't seem to be working as expected and I'm stru ...

Custom 404 Page by Google

Could anyone provide information on the property #goog-fixurl for the custom 404 widget? I've searched but can't seem to find any documentation on it. I'm familiar with all the other property styles #goog-fixurl Any assistance would be grea ...

Encountering an issue when adding SASS Compass Breakpoint to my development project

I'm having trouble integrating breakpoints into my web project. I have SASS, Compass, and breakpoint all installed and I've followed the installation instructions, but it seems to be causing errors. Can someone help me troubleshoot the issue? He ...

Tips and tricks for locating the xpath of a header title using Selenium Webdriver and Java

Looking to locate the xpath of a header title that is only accessible through the 'inspect element' tab with its class and text content provided. The objective is to create an if statement to verify whether the page's title matches my desir ...

Creating reliable dynamic selects with a MySQL database, PHP, and jQuery

I am currently working on a project that involves three select elements representing states, cities, and banks. If you want to see a demonstration of the concept, you can check out this jsfiddle When a user selects a state, the link dynamically changes u ...

File.type cannot be obtained in IE 11 and IE Edge due to compatibility issues

"change .btn-file :file" : "getfileinfo", getfileinfo: function(e){ var fileInput = document.getElementById('fileupload'); var file = fileInput.files[0]; if(!file || (file.type != 'text/plain' && file.type != ' ...

Can React JSX and non-JSX components be combined in a single project?

I'm currently faced with a question: If I have a parent component in JSX but need to include an HTML tag like <i class="fa fa-window-maximize" aria-hidden="true"></i>, which is not supported by React JSX (correct me if I'm wrong), can ...

Using PHP and an HTML form to input multiple data entries into a MySQL database

I am currently working on a project that involves reading and inserting columns and rows from an HTML form into a MySQL database using PHP. When trying to execute the code, I encountered the following error: Undefined index: maintenance on line 28 Undef ...

Steps to create full screen jQuery tabs with overflow scroll feature in the content

I am in the process of creating a responsive web design using jQuery tabs. My goal is to make one page of the website occupy the entire screen (100% height and width), have a fixed height for the div.ui-tabs-nav, and enable scrolling for the content of div ...

What is the recommended alternative for the outdated or non-standard "align" element in use?

Here is the code I am working with in HTML: <td align="center"> After running ReSharper in Visual Studio 2008, I received this error message: "Element 'align' is obsolete or nonstandard" Can someone please advise on the correct replac ...

Navigating following an AJAX form submission

Currently, I am delving into a problem brought to my attention by a friend. My knowledge of AJAX and jQuery is not very strong. What I have gathered so far is that when this form is submitted, it goes to the current address set_var.cgi with an index of 94, ...

The Unshift function in Reactjs uses Jquery to dynamically generate new buttons whenever it is clicked

When utilizing ReactJS in combination with jQuery, the Unshift function is causing an issue where additional buttons are being created upon clicking. The code snippet was sourced from the renowned platform Stack Overflow, and it involves an array of three ...

Transferring a JSON payload to a PHP script without relying on AJAX

I apologize if this is a naive question, but as someone new to web development, I'm curious to know if there is a method for sending a JSON string to a PHP file without the use of AJAX. In one of my exams, I encountered a similar prompt: "Submit the ...

Matching CSS attribute values with another attribute

Can CSS be used to target elements based on the value of another attribute? For instance: <div data-attr1="abc" data-attr2="def"></div> <div data-attr1="abc" data-attr2="abc"></div> I am looking for something like this (although i ...

The collapsible menu does not toggle when I tap on the icon

I am currently troubleshooting an issue with this link "https://sampledemos.online/training/index.html" where the toggle feature is not functioning properly. Below are the codes I have written: <aside id="layout-menu" class="layout-menu m ...

Determine if the chosen option is present in any of the four arrays using Jquery/HTML, and execute a specific function based

I've been searching the web and other questions for assistance with this, but I can't seem to figure it out. I suspect that I'm not using the correct keywords. My goal is to create a functionality based on a value selected by a user from a ...

Revising a value that is influenced by the fluctuations of another value, and conversely

Currently facing a tricky issue with interdependent values in my code that I can't seem to resolve online. The problem lies in the fact that one value is affected by changes in another value, and vice versa. Here is a snippet of my code: <div cla ...

Detaching the jQuery event where the context is tied to the handler

My current challenge involves removing a jQuery event with a callback function bound using this. The issue arises from the fact that .bind() generates a new function each time it is called, causing difficulties when trying to remove the event. I am strugg ...

How to ensure an image or ad stays in a fixed position on the screen

Is there a way to keep a part of the screen fixed, regardless of what other elements are in that space? Do I need to merge code with the HTML code of the ad or image to achieve this? ...

Conceal portion in HTML until revealed

I am attempting to create 3 sections within a single HTML file using the <section id="id"> tag, and I want to be able to open each section by clicking a link in the header with <a href="#id">1</a>, and then close it when another section i ...