Highlight the current element based on the page that is currently active

After searching for similar questions without success, I am turning to you for help. This is what I need:

When a user visits the "about" page, I want the li element to become active so that the CSS styles will apply. The same should happen when they click on "service," and so on.

Note 1: This menu is included in the main body using require_once("path/to/navmenu.php"), and I am not sure if this has any impact.

Note 2: I understand that jQuery is the solution here, but I have tried codes from similar questions on Stack Overflow with no luck. A JSFiddle demonstration would be greatly helpful.

HTML CODE:

<nav class="flexy-menu">
    <li class="active"><a href="index.php">home</a><div  class="menu-space"></div></li>
    <li><a href="about-us-style1.php">about</a><div class="menu-space"></div></li>
    <li><a href="service-style2.php">service</a><div class="menu-space"></div></li>
</nav>

CSS CODE:

 .flexy-menu li:hover > a,
 .flexy-menu li.active a {
   background: #c68f50;
   color: #fff;
 }

Answer №1

One way to customize your menu using PHP is by defining a PHP variable on each page. For example, you can set a variable for the about page like this:

$about_page = 1;

Then, you can use this variable to highlight the menu item when the user is on that specific page:

<li><a href="about-us-style1.php" class="<?php if($about_page == 1) { echo 'highlighted'; } ?>">about</a><div class="menu-space"></div></li>

Make sure to define the highlighted class in your CSS:

.highlighted {
   background: #c68f50;
   color: #fff;
}

This is just one approach to achieve this effect, but there are more advanced solutions out there!

Answer №2

Personally, I find using PHP for separate files like the NavBar is a good practice. However, with JQuery, you can achieve the same result with the following code snippet:

function updateMenu()
{
   var checked = false;
   $(".flexy-menu li").removeClass('active').each(function()
   {
       if(checked == false && window.location.href.indexOf($(this).find('a').attr('href')) != -1)
       {
           $(this).addClass('active');
           checked = true;
       }
   });       
}

You can invoke updateMenu(); at any point after the menu is displayed. It's recommended to call it within the $(document).ready() function.

Answer №3

If you are directing your user to a different page, it’s important to include server-side code that checks the current page and applies the appropriate class to the link.

However, if you are not redirecting, just let me know and I can provide the necessary code for that scenario.

// Server Side Code

<?php
    $page_name = str_replace('.php', '', $_SERVER['PHP_SELF']);

    $page_array = array(
            'index'=>'',
            'about'=>''
    );
    $page_array[$page_name] = 'active';
?><html>
    <head>
        <title>Active Menu</title>
    </head>
    <body>
        <nav>
            <a href="#" class="<?php echo $page_array['index']?>">Home</a>
            <a href="#" class="<?php echo $page_array['about']?>">About</a>
        </nav>
    </body>
</html>

Note: This example is purposely kept simple to help grasp the main concept of what we are trying to accomplish. There are various ways this can be enhanced, but for beginners, this serves as a good starting point.

Answer №4

When redirecting users, it's important to check the page name and highlight the li element with an anchor link that matches the value of the href attribute once the page has loaded. The code snippet below can help achieve this:

$(document).ready(function () {
    var pagename = location.pathname.split('/').slice(-1)[0];
    $(".flexy-menu li a").each(function (index) {
        if($(this).attr("href").indexOf(pagename)==0){
            $(this).parent().addClass("active");
        }
        else{
            $(this).parent().removeClass("active");
        }
    });
});

To implement this functionality, save the following code as an HTML file named test2.html:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  <script type='text/javascript' src='https://code.jquery.com/jquery-1.9.1.js'></script>
  <style type='text/css'>
    .flexy-menu li:hover > a, .flexy-menu li.active a {
         background: #c68f50;
         color: #fff;
    }
  </style>

<script type='text/javascript'>
$(document).ready(function () {
    var pagename = location.pathname.split('/').slice(-1)[0];
    $(".flexy-menu li a").each(function (index) {
        if($(this).attr("href").indexOf(pagename)==0){
            $(this).parent().addClass("active");
        }
        else{
            $(this).parent().removeClass("active");
        }
    });
});
</script>

</head>
<body>
  <nav class="flexy-menu">
    <li class="active"><a href="index.php">home</a>

        <div class="menu-space"></div>
    </li>
    <li><a href="test2.html">about</a>

        <div class="menu-space"></div>
    </li>
    <li><a href="service-style2.php">service</a>

        <div class="menu-space"></div>
    </li>
</nav>
</body>
</html>

In the provided HTML, the first li element has the active class set by default. However, in the browser, the second link will be highlighted when the file is saved as test2.html.

Answer №5

Greetings once again! I have carefully reviewed all of your comments and responses. I must say, everything you suggest seems to be working perfectly. However, since I am not very familiar with JS/Jquery and CSS3 selectors, I opted for the PHP route :)

Here's what I did: I added a variable on each page such as $about_page=1; for instance, when someone visits the index page. Next, in the navigation.php file, I implemented some if statements to echo the "active" class.

<li <?php if($about_page==1){echo 'class="active"';}?>><a href="about-us-style1.php">about</a><div class="menu-space"></div>
            </li>

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

Can a shake event be utilized to indicate necessary form fields?

Hey, so I'm working with this form and implementing validation using the onclick event and submitting on change. <form action="reservation.php" method="post"> <input class="date" id="from" name="from" type="text" ...

Updating an added row with jeditable and the on() method in jQuery version 1.7 triggered by a button click

I am facing an issue with my data table. I have the ability to add rows from a button at the top of the table and select rows as well. However, I want to be able to edit those selected rows, even if they are newly added. Currently, I am able to use a code ...

Enhance the performance of jQuery and CSS on your WordPress site

I'm currently working on a WordPress 4.3 website that utilizes over 20 plugins, each loading CSS and jQuery on every page. My main concern is how to optimize the styles and jQuery so that only the necessary ones are loaded on each page. I've at ...

Display an image when the cursor hovers over a text

I'm attempting to display an image when hovering over specific text. The image should not replace the text, but appear in a different location. The concept is as follows: When hovering over the word "Google", the Google logo should appear in the red ...

After the initial rendering, JQuery can dynamically search through the DOM elements and seamlessly replace keys with their respective values

I am in the process of implementing my personal localization method on my web application that is currently under development. With the use of JQuery 2.2.0 and no other frameworks or third-party tools, I need to embed certain expressions directly into my H ...

Matching the heights of div-containers within cards

Is there a way to ensure that the containers within my cards are all the same height? I'm not referring to the actual cards themselves, but rather the elements inside them. This is what my code currently looks like: .card-text { border: 1px solid ...

Web page saving fails to preserve images!

Currently working on a PHP-based website that is utilizing the Zend framework and hosted on an Apache server. The folder structure within my www directory looks like this: +www | |_+css | | | |_images | |_js | |_images The issue I'm ...

What is the best way to remove bootstrap when transitioning to a new microfrontend?

Our team is facing an issue with styling when using a combination of React, Bootstrap, and Tailwind. The problem arises when linking our micro frontend to modules that use Tailwind, as the Bootstrap styles persist despite the change. Since both Tailwind an ...

Is jQuery's click-to-remove-row functionality not functioning properly?

Watch for the next question to be posted tomorrow function n() { $('.m').on('click',function() { var id = $(this).closest("tr").find(".t").text(); var p= $(this).closest("tr").find(".t1").text(); $('#c').append( ...

When trying to make a selection from a dropdown menu on my mobile device, no action is taken

Why is it that when I select an option from a dropdown menu on mobile, it doesn't trigger any validation or send data to the server until I select the same option again? This issue only seems to occur on mobile devices. $("#major").click(function() ...

Create a stylish Bootstrap 4 layout with a scrollable row that elegantly fills the remaining height

In Bootstrap 4, I want to create a row that fills up the remaining height of the page without extending past its designated space. The content should be scrollable using buttons, preferably with no visible scrollbar. I have attempted to break down my layo ...

Translate a portion of a painting by utilizing context.putImageData()

I am attempting to gradually fill a canvas with pieces of the original image. To achieve this, I need each square of the image to be filled in iteratively on the canvas. To optimize performance, my approach involves rendering the original image onto an of ...

Incorporate AJAX into your Javascript code for ordering

My issue arises when pointOnMap() is executed before xmlPreparer(), even though they are called in the correct order. I suspect this has something to do with the use of AJAX, as parseXML creates the object that pointOnMap() requires to be initialized befor ...

In Bootstrap 5, the anchor tag is causing a shift in the background color of surrounding tags upon being clicked

Why does clicking on an anchor tag temporarily change the background of other tags that weren't clicked? What am I doing wrong? https://i.stack.imgur.com/ZKlUT.png Check out the code below: <nav class="navbar navbar-expand-lg navbar-light bg- ...

Bootstrap 4 radio buttons are not aligning properly with the padding

There seems to be an issue with the alignment of Bootstrap 4 custom radio buttons and my left padding. Here is a snippet: https://i.sstatic.net/vWTNo.png This is part of the code for displaying an item <div class="p-4"> <ul class="d-flex ...

Conceal all alphabetical characters exclusively within paragraph content

I have a lengthy, dynamically generated paragraph containing both alphabetic and numeric characters. Query: How can I filter out all alphabetic characters from the paragraph and only display the numeric ones? For instance: <div class="mytexts"> So ...

No wrapping of columns in Bootstrap 4

I am struggling with preventing the B4 columns from wrapping when resizing the Browser. Check out my code below: <div class="card card-outline-primary"> <div class="card-block"> <form class="row"> <div class="col-xs-4" sty ...

Display visuals from Contentful in Angular

I'm encountering an issue with displaying images uploaded to Contentful on my Angular website. The browser console shows that the image is loaded correctly, but on the screen, I only see a blank image. Below is the code snippet: contentful.service ...

To add a code snippet to the right side of a paragraph using CSS, place it at the end of the

Is there a way to insert code at the end of each paragraph and have it aligned to the right on the same line as the last sentence? Update: I initially tried using float:right, but encountered an issue with vertically aligning the code with the last line ...

Center the content within the div

Is there a way to center the content of the second column within this div? I've tried various methods without success so far. I'm currently using Bootstrap 4. Can anyone provide guidance on how to achieve this? <div class="card"> < ...