The jQuery CSS menu is having trouble highlighting the active link

Can you help me figure out what's wrong with this code and how I can fix it?

I'm working on a CSS menu (horizontal) where I want the background and font to change when an item is selected. I found some jQuery code from another post that should make it work, but even after adding the code, the background and font don't change when I select an item. Any suggestions on how to solve this?

Here is the HTML snippet:

<ul id="menu_nav" class="buttons">
  <li>
    <a href="#" onclick="' . $menu_path . '">Item 1</a>
  </li>
  <li>
    <a href="#" onclick="' . $menu_path . '">Item 2</a>
  </li>
  <li>
    <a href="#" onclick="' . $menu_path . '">Item 3</a>
  </li>
</ul>

And here is the corresponding CSS code:

ul#menu_nav
{
    float:left;
    width:790px;
    padding:0;
    margin:0;
    list-style-type:none;
    background-color:#000099;
}
ul#menu_nav a
{
    float:left;
    text-decoration:none;
    color:white;
    background-color:#000099;
    padding:0.2em 0.6em;
    border-right:1px solid #CCCCCC;

    font-family: Tahoma;
    font-size: 11px;
    font-style: normal;
    font-weight: bold;
    position: relative;
    height: 21px;
    line-height:1.85em;
}
ul#menu_nav a:hover {
    background-color:#F1F4FE;
    color:#000099;
    border-top:1px solid #CCCCCC;
}
ul#menu_nav li {display:inline;}

.selected {
    background-color:#F1F4FE;
    color:#000099;
    border-top:1px solid #CCCCCC;
}

Lastly, here is the jQuery script being used:

$(function(){
  $(".buttons li>a").click(function(){
    $(this).parent().addClass('selected'). // <li>
      siblings().removeClass('selected');
  });
});

Answer №1

Due to the way CSS inheritance works, the ul#menu_nav a css rule will take precedence over the .selected rule. You might want to try adjusting the selector

#ul.menu_nav a.selected{

}

Answer №2

Appreciate the advice, it really helped me simplify my approach...below is the CSS and jQuery code that successfully resolved my issue.

In essence, I defined two classes and toggled between them using jQuery selectors to achieve the desired effect.

$(function(){
              $(".menu_buttons li>a").click(function(){
                $(this).addClass('selected').removeClass('button'). // <li>
                  parents().siblings().children("a").removeClass('selected').addClass('button');
              });
            });

The finalized CSS appears as follows:

ul#menu_nav
{
    float:left;
    width:790px;
    padding:0;
    margin:0;
    list-style-type:none;
    background-color:#000099;
}
ul#menu_nav a.button
{
    float:left;
    text-decoration:none;
    color:white;
    background-color:#000099;
    padding:0.2em 0.6em;
    border-right:1px solid #CCCCCC;

    font-family: Tahoma;
    font-size: 11px;
    font-style: normal;
    font-weight: bold;
    position: relative;
    height: 21px;
    line-height:1.85em;
}
ul#menu_nav a:hover {
    background-color:#F1F4FE;
    color:#000099;
    border-top:1px solid #CCCCCC;
}
ul#menu_nav li {display:inline;}

.selected {
    background-color:#F1F4FE;
    color:#000099;
    border-top:1px solid #CCCCCC;

    float:left;
    text-decoration:none;
    padding:0.2em 0.6em;
    border-right:1px solid #CCCCCC;

    font-family: Tahoma;
    font-size: 11px;
    font-style: normal;
    font-weight: bold;
    position: relative;
    height: 21px;
    line-height:1.85em;
}

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 trouble with jQuery Animate when trying to change the background-color property?

So, I was experimenting with the jQuery .animate() function and decided to change the background color of a div based on how many pixels the user scrolled. Surprisingly, it didn't work as expected. After switching to the .css() function instead, every ...

Customizing React-Data-Grid styles using Material-UI in a React application

Imagine a scenario where we have a file containing themes: themes.js: import {createMuiTheme} from "@material-ui/core/styles"; export const myTheme = createMuiTheme({ palette: { text: { color: "#545F66", }, }, }); In ...

Can ajax requests be made without a web browser?

Currently, I am in the process of developing JavaScript tests using mocha and chutzpah, which means conducting all my tests without a browser. However, I have encountered an issue where all my AJAX calls are resulting in empty strings. Even when using the ...

Animating background color change with scroll in React using fade effect

Can someone help me with implementing a fading animation for changing the background color on scroll in React? I have successfully achieved the background change effect, but I'm struggling to incorporate the fading effect. import React from "reac ...

The jQuery show/hide functionality is malfunctioning

In my PHP code, I have the following loop: foreach ($sid as $key => $value) { $sql = " a sql query "; $vehicle->rowQuery($sql); $numRows = $vehicle->rows; while ( $data = $vehicle->result->fetch_assoc()) { $ ...

Selecting a dropdown value dynamically after a form submission in ColdFusion using jQuery

I created a basic form with the use of an onload function to populate market values by default. However, I encountered an issue where after selecting a market value from the drop-down list and submitting the form, the selected value does not stay selected ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

Extracting the magnifying glass from the picture

After implementing a function to add a magnifying glass (.img-magnifier-glass) on button click, I am now looking to remove the glass by clicking the "cancel" button. However, I am unsure of how to write this function to interact with the "magnify" function ...

Is it possible to modify CSS properties by clicking on buttons?

Hello, I really need help with this task. I want to change the style of a button (which is actually a link) by clicking on it. These buttons are housed within a dynamic child div that changes each time, but the name of the dynamic child div remains con ...

Empty response received from AJAX .post request to PHP backend

I'm having trouble with creating a system to check the availability of usernames. I'm not receiving any response back and even though there are no errors in the console, all I get is a 200 OK status without any response, which should be stored in ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

"Trouble arises when event listener fails to function following an append operation

Recently, I delved into the world of HTML/CSS and jQuery in an attempt to create a simple web game. Below is a snippet of my HTML code: function playGame() { var theLine = "<div id = \"line\">"; for (var i = 0; i < 9; ...

Modify File Name with Fine Uploader: Personalize Your File Titles

When attempting to save files with a specific directory structure in my S3 bucket, I am encountering an issue where the getName method only returns the reference instead of the actual value of the file name. The output of getName is displayed as [object O ...

Mysterious failure of JavaScript regular expression when encountering the term "tennis"

We developed a JavaScript script to detect duplicates or potential duplicates, but it seems to have some issues with certain words like "tennis." The script functions correctly in most cases, but fails when analyzing phrases related to the word "tennis" fo ...

Display search results within the same page using jQuery, without redirecting to a new page

I am currently working on creating a custom search form for an e-commerce platform using Magento. This search form consists of multiple dropdown select boxes. While the form is operating correctly, once the form is submitted with selected search criteria, ...

Trigger next animation after the completion of current animation using Jquery animate callback

Is there a simpler way to achieve this task? var index = 0; while (index < 5) { $(this).find(".ui-stars-star-on-large:eq(" + index + ")").animate({ width: w + 'px' }, 200, "swing"); index++; } ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

Monochrome tabletop solid in one hue

I'm trying to eliminate the space between the columns in my table so it looks solid. Here's the CSS style I've been using: <style> tr, th, td {margin:0;padding:0;border:0;outline:0;font-size:90%;background:transparent;} table{ margin: ...

Adjusting the view to focus solely on the visible portion of the webpage

Is there a way to achieve zooming in and out on a website similar to how it works on the site ? I want only the visible area to zoom in or out when users interact with their browser. I searched online for a solution but couldn't find one. Any suggesti ...