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

Pass user input values to PHP via AJAX and display the outcome on a designated div

I am currently working on a project where I need to send an input value to a PHP script and display the returned value in a div using AJAX. However, I seem to be struggling with getting it to work properly. Any assistance or suggestions would be greatly ap ...

send additional form elements to the AJAX suggestion box script

** shifted to this location: Numerous similar AJAX suggestion boxes without IDs I enlisted the help of a developer to create a jQuery AJAX suggestion box script some time ago, and it has been working flawlessly. Now, I am striving to understand it better ...

Arranging fixed-width <div>s in rows of four for a sequential display

Below is the code that I am working with: <div style="margin: 0 auto; display:block; width: 916px; overflow: auto;"> <?php echo ""; echo "<i>Owned: $line->phone </i><br><br>"; $query ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

Problem with Chrome Compatibility for Bootstrap Carousel

My webpage features a carousel implemented as a slider. It seems to be working fine in Firefox and mobile browsers, except for Chrome where it doesn't show up at all. I can't seem to figure out what's causing the issue. Here is the syntax I& ...

Switch Image to Background Image on Mobile Devices

I am currently working on a website that needs a special page for an upcoming event. Typically, the pages on this site have a mast banner image that stretches across the full width of the page. However, for this particular page, it is necessary for the ima ...

use jquery to dynamically switch CSS class on navigation with animated arrows

Looking to update arrows to display a right arrow when the parent list item has the .active class. Here is the jQuery code: jQuery(function(){ initAccordion(); }); function initAccordion() { jQuery('.accordion').slideAccordion({ opener ...

Discover the best method for transferring MySQL data between pages

Can anyone help guide me in the right direction on how to allow a user to click a link within a PHP While Loop generated MySQL table and pass that data to another page? I've searched through similar questions but haven't found a solution that fit ...

Having trouble with Python Selenium CSS Selector? If your element is not visible, it

My goal is to search for all hyperlinks on a webpage that contain an XML download link and download them in a continuous loop. When I click on these hyperlinks, a form pops up that needs to be completed before I can proceed with the download. However, I ...

Leveraging oembed for dynamic content integration with SoundCloud in JSON

I'm looking to retrieve the latest 10 tracks of a user using oembed with json. $.getJSON("http://soundcloud.com/oembed", {url: "https://soundcloud.com/aviciiofficial", format: "json"}, function(data) { console.log(data.html); }) The d ...

Can <p> be utilized without creating empty space at the top or bottom?

Is there a way to use paragraph breaks without any space at the top or bottom when there's no text above or below it? body { font-family:arial; background:#222; } #wrapper { width:100%; margin-top:100px; } .post_container { ba ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

"Utilizing AJAX for Data Retrieval in a Form with Dynamically Generated

Hey there, I'm trying to figure out how to make my ajax data call dynamic. Here's what I've attempted: var opt_name = $(".NAME").data('opt_name'); var opt_business = $(".BUSINESS").data('opt_business&ap ...

The action method does not get triggered when using $.ajax POST if the text being sent includes the character "<"

On my company's intranet site, I am facing an issue with displaying and submitting text. Here is the code snippet that I am using: @Html.TextAreaFor(model => model.Text) The problem arises when the text in the textarea contains XML-like formattin ...

Use a function to handle button click events rather than relying on the id

Hello everyone, I am a beginner and I have a question about using a function on two buttons with #ID. The problem is that I have to write the same function twice for different button IDs. I want to call the function with Onclick so that I only have to writ ...

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

By harnessing a JSON response

After sending an ajax request, the server's response is as follows: {"error":false,"success":true} The ajax code used: $.ajax({ url: '/update', type: 'post', data: $(this).serialize(), success: function(response) ...

Issue with Bootstrap 5 navbar dropdown: It opens easily but struggles to close

I am currently using Bootstrap 5 to design a website and have incorporated a dropdown feature into the navigation bar. On desktop, when hovering over the dropdown, it should open, while on mobile, clicking the dropdown should toggle its visibility (open/cl ...

What are some ways to enhance the appearance of the initial two items in a list through CSS?

Is it possible to enhance the appearance of the first 2 elements in a list using CSS for IE8 compatibility? Here is an example of the format: <ul id="list1" style="margin-left:-20%;font-weight:bold" > <li class="xyz"> Element1 </li> ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...