An effective method for modifying the active class on an li element in jQuery and ensuring that the user is directed to the desired page upon clicking the li element

I am facing an issue with my script tag. When I click on the links test.php or test2.php, the active class changes from index.php to the respective file but I am not redirected to the clicked page. I have tried solutions from various sources but none of them give me the desired result. I want to be directed to the clicked page and update the active class accordingly in the li element.

How to change active class while click to another link in bootstrap use jquery?

Active link after click

When I uncomment e.preventDefault(), I can navigate to the clicked link but the active class is not updated in the li element. When this line is commented, I cannot navigate to the clicked page, instead, the active class updates in the li element.

<div class="menu">
    <ul class="list">
        <li class="header">MAIN NAVIGATION</li>
        <li class="active">
            <a href="index.php">
                <i class="material-icons">home</i>
                <span>Home</span>
            </a>
        </li>
        <li class="">
            <a href="test.php">
                <i class="material-icons">group</i>
                <span>Test</span>
            </a>
        </li>
        <li class="">
            <a href="test2.php">
                <i class="material-icons">people</i>
                <span>Test2</span>
            </a>
        </li>
    </ul>
 </div>

And the script code:

$(document).ready(function () {
    $('.menu .list a').click(function(e) {

        $('.menu li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});

The content of test.php is as follows:

<body class="theme-red">
    <nav class="navbar">
        <?php include_once('navbar.html'); ?>
    </nav>
    <section>
        <aside id="leftsidebar" class="sidebar">
            <?php include_once('left-side-bar.html');?>
        </aside>
    </section>

    <section class="content">
        <div class="container-fluid">
            <div class="row clearfix">
                <table id="tbl-users" class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </tfoot>
                    <tbody>
                    <?php
                        $accounts = get_details();
                        foreach($accounts as $acc){
                    ?>
                        <tr>
                            <td><?php echo $acc['id']; ?></td>
                            <td><?php echo $acc['name']; ?></td>
                        </tr>
                    <?php
                        }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </section>
</body>

Answer №1

The Cause of the Issue

An issue arises when you use e.preventDefault() on clicking an anchor tag, as it disrupts the default behavior of redirecting the page. This results in the page not loading while still adding the active class. On the other hand, if you do not use e.preventDefault(), the page redirects immediately before applying any changes, making it difficult to see the active class.

.

Solution to Resolve the Issue

To address this problem, you can return a value from test.php or test2.php which can be validated with JavaScript using if-else conditions to determine and set the active class accordingly for li elements.

Steps to Implement the Changes:

In each linked page like test.php or test2.php, add a hidden span with text that matches the hyperlink in the anchor tag. For example, for test.php add the following span:

<span id="curpage" style="display:none;">test.php</span>

Then include the following script at the end of the body tag or in a separate file that is included in all PHP files using <?php include(".."); ?>:

$('a[href=\"' + $("#curpage").text() + '\"]').parent().addClass("active");

You can try out the following sample code to implement this solution. Create two files within the same directory named a.html containing the code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <span id="curpage" style="display:none;">a.html</span>
  <div class="menu">
  <li><a href="b.html">1</a></li>
  <li><a href="a.html">2</a></li>
</div>
<script>
  $('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
</script>
</body>
</html>

And b.html containing the code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <span id="curpage" style="display:none;">b.html</span>
  <div class="menu">
  <li><a href="b.html">1</a></li>
  <li><a href="a.html">2</a></li>
</div>
<script>
  $('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
  </script>
  </body>
</html>

Now, by navigating between the pages using the links, you will observe the change in bullet color indicating the active page.

Answer №2

One method to ensure the active menu link remains displayed correctly is by implementing a unique identifier for each page within your HTML templates. By assigning a specific ID and data attribute to a designated div element, you can easily track the current page using JQuery.

<div id="page-name" data-page="home-page">

To dynamically update the active menu link based on the current page, you can retrieve the stored data with the following code:

var current_page = $("#page-name").data("page");

Subsequently, adjust the class of the menu links accordingly using conditional statements like so:

// Remove "active" class from all menu links
$(".menu li a").removeClass("active");

if (current_page === "home-page") {
    // Add "active" class to desired link
    $("#home-page-link").addClass("active")
}

It's advisable to utilize a switch statement for multiple pages and remember to include the corresponding JS file across all pages. Utilizing the Header template simplifies this process, requiring just a single inclusion. Lastly, ensure consistency in naming conventions for the "data-page" attribute in your HTML markup.

Answer №3

If you want to dynamically add a class to the navigation item of the current page when the page loads, here's how you can achieve it:

  1. First, check the URL of the current page:
    $(location).attr('href') OR $(location).attr('pathname')
  2. Next, iterate through anchor elements (a) in the navigation menu to see if any of the href attributes match the current page URL using the .indexOf() method with a conditional statement:
    if(anchorEl.indexOf(currentPageUrl) >= 0)
  3. If there is a match, add the required class using the .addClass() function: $(this).addClass('current');

Check out this code snippet for a visual demonstration:

Please note that this example uses specific URLs to illustrate functionality and is not intended for production environments.

$(document).ready(function () {
    var currentPageUrl = $(location).attr('href'), // store current page url
        anchorEl;
    
    $('.menu a').each(function(){
    
      anchorEl = $(this).attr('href'); // store href attribute of current anchor element
      console.log('anchor link url:',anchorEl);
      console.log('current window url:',currentPageUrl);
    
      if(anchorEl.indexOf(currentPageUrl) >= 0) { 
        $(this).addClass('current');
        console.log('class "current" added.');
      }
    });
});

/* 

Note:
$(location).attr('href') = full absolute path (https://example.com/page)
$(location).attr('pathname') = relative path (/page)

*/
.current {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <ul class="list">
    <li>
      <a href="https://example.com/page1">
          <span>Example Page 1</span>
      </a>
    </li>
    <li>
      <a href="https://example.com/page2">
          <span>Example Page 2</span>
      </a>
    </li>
    <li>
      <a href="https://example.com/current-page">
          <span>This should be the <em>current</em> page</span>
      </a>
    </li>
  </ul>
</div>

Answer №4

Have you considered using e.preventDefault()? This function stops the default behavior of an object, such as a redirect in this case. By doing so, you can prevent your application from automatically redirecting to the specified href.

If you want to implement this feature, you can update your code like this:

$(document).ready(function () {
    $('.menu .list a').click(function(e) {

        $('.menu li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();

        // Make the necessary changes here
        location.href = $(this).attr('href');
    });
});

Edit 1: You can follow these steps:

1) Assign a specific class name to each li tag

2) Send the required class name (which should have the active class) after redirection and page load

3) Retrieve the class name passed through the url and add or remove it from your li tags

Your updated html code will look like this:

<div class="menu">
    <ul class="list">
        <li class="header">MAIN NAVIGATION</li>
        <li class="home active">
            <a href="index.php">
                <i class="material-icons">home</i>
                <span>Home</span>
            </a>
        </li>
        <li class="group">
            <a href="test.php">
                <i class="material-icons">group</i>
                <span>Test</span>
            </a>
        </li>
        <li class="people">
            <a href="test2.php">
                <i class="material-icons">people</i>
                <span>Test2</span>
            </a>
        </li>
    </ul>
 </div>

If you need the corresponding script code for this solution, let me know and I'll update my answer.

Edit 2: To make this work, include the following script codes in your file:

function setActiveClass() {
    //Remove active class from all li tags
    $('.menu li.active').removeClass('active');
    //Get the current url
    var url = $(location).attr('href');

    if (url.contains("activeClass")) {
        //Find the index of active class in the url
        var start = url.indexOf("#activeClass");
        //Adjust the end index based on the longest class name ("people" has 6 characters)
        var end = start + 6;
        //Extract the passed class name from the url
        var className = url.substring(start, end);

        //Add the active class based on the passed class name
        if(className.contains("home"))
            $(".home").addClass('active');
        else if(className.contains("group"))
            $(".group").addClass('active');
        else
            $(".people").addClass('active');
    } else {
        //Add the active class in default mode (when there's no redirect yet)
        $("#defaultLiTag").addClass('active');
    }
}

$(document).ready(function () {
    //Call the function
    setActiveClass();

    $('.menu .list a').click(function(e) {
        e.preventDefault();

        var classNameOfParent = $(this).parent().attr('class');

        var classNameToBePassedByUrl = "home";

        if(classNameOfParent.contains("group"))
            classNameToBePassedByUrl = "group";
        else if(classNameOfParent.contains("people"))
            classNameToBePassedByUrl = "people";

        location.href = $(this).attr('href') + "#activeClass=" + classNameToBePassedByUrl;
    });
});

Answer №5

After encountering the same issue and researching extensively, I stumbled upon a helpful solution in the following link. Hopefully, it can assist you as well. It is recommended to remove the "active" class and add it to the clicked navbar item. Using location.href helps to add the active class when the page reloads.

https://example.com/refresh-active-page-jquery/

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

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Locate specific text within the content and apply an underline to it

Is there a way to locate specific text on my website and apply an underline to it? Suppose I have some text displayed and I wish to identify all instances of the word hello and underline them. Here is my attempt at the code: $( "body:contains('hell ...

Uploading images in React JS by allowing users to paste images

Currently working on a chat application using React JS and I'm looking to enable image uploading when an image is pasted into the chatbox. How can I make this happen? Essentially, I am in need of: An event that will activate upon performing the "Pas ...

What is the best way to redirect a URL to include www using Node.js?

What is the best way to redirect a URL to start with www? For instance: ---> ...

Dealing with nested file includes in PHP and passing values to a JavaScript function

When the button is clicked on login.php, it triggers the execution of redirect.php. This redirect.php file carries out Twitter authentication, which includes invoking another file that eventually calls index.php. index.php provides the result in the form ...

Struggling with eliminating the bottom margin on your website?

I can't figure out where this mysterious margin is coming from in the CSS - there's a consistent 30px of space at the bottom of each web page. Any assistance would be greatly appreciated. I know it's probably something simple, but my brain ...

Discover the absent style attributes within an HTML code in C# and incorporate them

Currently facing a challenging situation where I have a C# string with html tags: string strHTML = "<span style="font-size: 10px;">Hi This is just a section of html text.</span><span style="font-family: 'Verdana'; font-size: 10px; ...

Step-by-step guide on making a post request to the Facebook Graph Api with Httparty in a Rails application

I'm currently working on developing a bot for Facebook Messenger, and I need to make a post request call to the Facebook Graph API. The sample code provided by Facebook is in Node.js, but I am working with Rails as my backend framework. Sample Code ...

Can data be transmitted to two separate scripts simultaneously?

Just a quick HTML inquiry: Can data from HTML forms be sent to two separate scripts using the "action" attribute, or is there an alternative method? I'd like to explore other options aside from utilizing curl. ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Issues encountered with making JSONP requests

Hey there, I'm a bit stuck and need some help figuring out what's going wrong. Sometimes a fresh perspective can make all the difference. So, here's the situation: I'm making a JSONP request using jQuery from one domain () to a PHP scri ...

Tips for customizing column width in v-simple-table with Vuetify.js component

For my most recent projects UI component, I decided to use vuetify.js. I attempted to adjust the width of the th and td elements within a v-simple-table using CSS, but unfortunately, nothing seemed to happen. My goal was to set the width of every th and td ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Reinvent the AJAX functionality

Is there a way to create a custom function that changes the default ajax functionality? I currently have this ajax function implemented: $.ajax({ type: "POST", url: "http://" + document.location.host + '/userajax', data: 'type= ...

Hide popup using HTML when clicking outside of it

Currently, I have implemented Bootstrap Popover with HTML content using the code snippet below. This code is based on the answer provided at . $(".song-status-link").popover({ html: true, placement: 'bottom', ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

Passing Variables from Node JS to Pug Template's HTML and JavaScript Sections

Here is a route that sends various variables to a Pug template: items.js route router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeExp ...

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...

The Gulp task abruptly terminates before the Stream has a chance to trigger the "end" event

const gulpJasmine = require('gulp-jasmine'); const gulpDebug = require('gulp-debug'); function runTest(platform, testType) { const timer = startTimer(); console.log('started!'); return gulp.src('./src/**/_test/**/ ...

Sharing JSON data across different domains to ASP.NET using jQuery

I have encountered a complex issue. Currently, I am involved in a project that requires generating receipt printouts when users check out on our website at a kiosk. Due to driver and formatting challenges, I am utilizing COM automation with Word for handl ...