Emphasize Links in Navigation Bar

I am in the final stages of completing the navigation for my website. I have included the jsfiddle code to display what I have so far. The issue I am facing is that my child links turn gray as intended, but I also want the top level link to turn gray when clicked. The structure of my pages is organized like this:

Page1
Page1a
Page1b
Page2
Page2a
.
.
.
ETC.

I am looking to make Page1 and Page2 turn gray like the sublevels do. Any assistance in resolving this matter would be greatly appreciated. Thank you for taking the time to help.

http://jsfiddle.net/gUmYP/

<script type="text/javascript">
    $('#body').ready(function(){
            var URL = location.pathname.split("/");

            URL = URL[URL.length-1];
            
            for(var i = 0; i < 11; i++){ 
                if ((URL.indexOf(i) != -1) && (!$('#i'+i).is(':visible'))) {
                    $('#nav ul:visible').slideUp('normal');
                    $('#i'+i).slideDown(0);
                    $('#i'+i)
                        .find('li')
                        .each( function() {
                            var current = $(this).find('a')[0];
                            if (current.href == window.location.href)
                                current.style.backgroundColor = "#ccc";

                            current.style.color = "#006";
                        });
                }
            }
        });
</script>

Unfortunately, the answers provided below have not resolved my issue. While some have enabled the parent link to highlight, it has affected other functionalities. I still require the menu to highlight in yellow on hover, the submenus to remain light blue when inactive, and all active links (parent or child) to display the gray highlight when selected. Does anyone have a solution that addresses all these concerns?

You can find a potential solution to this problem in this post... Active Link on javascript menu to work on parent link not just child link

Answer №1

I have simplified your jQuery code for better clarity. Check out the improved version on this jsfiddle link and let me know if it meets your requirements!

$("#nav > li").click(function () {
    if ( $(this).hasClass("selected") ) {
        $(".selected").removeClass("selected");
    } else {
        $(".selected").children("ul").slideToggle();
        $(".selected").removeClass("selected");
        $(this).addClass("selected");
    }
    $(".selected").children("ul").slideToggle();
});

http://jsfiddle.net/PBKxy/

Answer №2

If you want to achieve this effect, follow these steps: http://example.com/custom-style

$('#menu li a').each(function(){
            $(this).css('backgroundColor', '#006');
            $(this).css('color', '#CCC');
        });
        $(this).css('backgroundColor', '#ccc');
        $(this).css('color', '#066');

Answer №3

It seems that your control logic for determining when to re-color menu items may require some review. I have made changes to the code to update the colors accordingly. Check out this fiddle to see the effect specifically applied to menu item #2.

Take note that if the location.pathname ends with a /, you may need to reference URL[URL.length-2] instead of URL[URL.length-1].

<script type="text/javascript">
    $('#body').ready(function(){
            var URL = location.pathname.split("/");

            URL = URL[URL.length-1];
            //<![CDATA[
            for(var i = 0; i < 11; i++){ // 4 = number of items, if you add more, increase this number by 1
                if ((URL.indexOf(i) != -1) && (!$('#i'+i).is(':visible'))) {
                    $('#nav ul:visible').slideUp('normal');
                    $('#i'+i).slideDown(0);
                    $('#i'+i)
                        .find('li')
                        .each( function(idx, ex) {
                            var current = $(ex).find('a');
                            if (current.href == window.location.href) {
                                current.css({
                                      backgroundColor: '#ccc'
                                    , color:           '#006'
                                });
                                $('#i'+i).prev('a').css({
                                      backgroundColor: '#ccc'
                                    , color:           '#006'
                                });
                            }
                        });
                }
            }
        });
</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

Using Node to upload various large JSON files into mongoDB

Currently, I am dealing with the task of parsing numerous large JSON files into my mongoDB database. To accomplish this, I have been utilizing the stream-json npm package. The process involves loading one file at a time, then manually changing the filename ...

What is the process for right-aligning components in BootStrap 5.0?

Currently, I am enrolled in an online course where the instructor utilizes Bootstrap 4. However, I decided to challenge myself by using Bootstrap 5.1 instead. I have been struggling with configuring my navigation bar elements to look like the ordered list ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

The attempt to follow or favorite the item at http://127.0.0.1:8000/follow/fav/8/1/ has resulted in a 403

I can't figure out why this error keeps happening. I have a favorite app, and it seems like the ajax functionality is breaking down. The error occurs when I click a button that should be working but isn't functioning properly at the moment. My su ...

When a form added by jQuery is submitted, the associated JavaScript does not run as expected

After clicking a button on my page, jQuery removes one form and replaces it with another. However, when I try to submit the second form, the associated JavaScript does not execute as expected. Instead of running the JavaScript function, the form submissio ...

Combining NodeJs with Mysql for multiple queries using a chained method

Hey everyone, I'm struggling with running mysql queries repeatedly in my Node.js application. I need to shape the second query based on the results of the first one. The code example I have below is not working as expected. Can anyone provide guidance ...

Desktop media queries are functioning properly, yet experiencing issues on mobile devices

I've come across this same question multiple times, but the solutions I've found so far haven't been helpful. My media queries are working perfectly on desktop, but they don't seem to take effect on three different android devices. It&a ...

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

text box with an immobile header

As the browser window size decreases, the layout changes. However, when scrolling down, the search text box moves up and is no longer visible due to its lack of fixation. How can I make the search text box stay fixed as I scroll down? I tried implementing ...

Is there a way to eliminate the auto-opening feature of WordPress Shortcode Ultimate Accordion on mobile devices with the help of jquery

Currently, I am utilizing the Accordion feature of Wordpress Shortcode Ultimate plugin. Although the plugin does offer an option to open the accordion on page load, I would like to have them closed by default on mobile devices. How can I achieve this usin ...

Transferring $scope information to resolve in $stateProvider.state

In the app.teams.show parent state, "team" is stored in $scope.data.team. From within a controller, I can access $scope.data.team and thus $scope.data.team.organization_id. The question is: How can I retrieve $scope.data.team.organization_id from inside t ...

Tips for successfully parsing JSON data during an Ajax call

After making an Ajax call, the response.responseText I receive looks like this: . "[ columns :[ { "id":"name", "header":"User name" }, { "id":"birth", "header":"Date of birth" } ], ...

What could be causing my carousel slider images to not adapt to different screen sizes?

I recently added a carousel slider to my website, and while it looks great on larger screens like desktops and laptops, I noticed that the images are not scaling properly when viewed on smaller screen widths. This has resulted in non-responsiveness which i ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

What is the best way to retrieve the href and id values dynamically from a card in React JS?

Hello everyone, I'm new to stackoverflow and still in the process of learning how to code. Please bear with me if this question sounds like a newbie one. My question is about having dynamic values for href and id when mapping data using axios to crea ...

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

Utilizing AJAX and PHP to Showcase Data

Instructions for program flow: 1. When the page loads, the chart will display the total sales from all branches. 2. Upon selecting a specific branch from the dropdown menu, the chart should show the total sales for that particular branch. I am encounterin ...

Angular.js page failing to reflect changes following Firebase request completion

myApp.controller('RegistrationController', ['$scope', function($scope) { var auth = firebase.database().ref(); // console.log("auth::"+auth); $scope.login = function() { $scope.message = "Welcome " + $scope.user.ema ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...