How to keep a button active using CSS in a different area of the webpage

I'm new to coding in javascript and I could use some assistance solving an issue on my test website. The problem involves creating a top menu with an active button that stays highlighted when clicked. In this case, I specifically need the active CSS class for buttons 1 and 2. Button 3 is a link to an email address and button 4 is a logout function.

See example of active button

I found one solution for the active class button, but it resulted in a new issue arising.

HTML:

<menu id="nav">
    <ul>
        <li><a href="index.php" class="btn btn-default"><i class="fa fa-tachometer fa-lg"></i><p class="desc_menu">BTN_1</p></a></li>
        <li><a href="index.php?nav=1" class="btn btn-default"><i class="fa fa-cogs fa-lg"></i><p class="desc_menu">BTN_2</p></a></li>
        <li><a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5bdb5b1aa85bdb5b1aaeba6aaa8">[email protected]</a>" class="btn btn-default"><i class="fa fa-envelope-o fa-lg">EMAIL</i><p class="desc_menu">COMUNICATIONS</p></a></li>
        <li><a href="exit.php" class="btn btn-default"><i class="fa fa-rocket fa-lg"></i><p class="desc_menu">EXIT</p></a></li>
    </ul>
</menu>

JAVASCRIPT:

$(function() {
    var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/")+1);
    $("#nav ul li a").each(function(){
      if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
        $(this).addClass("activ");
      })
  });

Clicking the green section link causes the active CSS styling on the button in the top menu to disappear. How can I keep the button active?

See example of disappearing active button

Any suggestions on resolving this problem would be greatly appreciated!

Thank you

Answer №1

To customize the styling of different sections, you can assign different classes:

$("#nav ul li a.btn-default").each(function(){
     // Skip green buttons
     if($(this).hasClass('green')) 
        return; 

     // Add active class to other buttons
     if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
        $(this).addClass("activ");
})

In order for this code example to function correctly, make sure your green buttons have a 'green' class. The naming is flexible and can be adjusted as needed.

Answer №2

To ensure proper navigation, make use of both location.pathname and location.search:

$(function() {
    var currentPage;
        currentPage = location.search == '' 
                ? window.location.pathname.slice(1) 
                : location.pathname.split('?')[0];

    $('#nav a[href="'+currentPage+'"]').addClass('active');
});

Your navigation consists of blue and green buttons, each requiring a specific method to determine the current page. The blue buttons rely on location.pathname, while the green ones necessitate the use of location.search as shown in the provided code snippet.

Answer №3

Implement this code snippet

 $(document).ready(function() {
    $('#navigation ul').find('a[href="' + window.location.pathname + window.location.search + '"]').addClass('current');
  });

Furthermore, your script appears to be correct, with the exception of a minor typo error.

$(this).addClass("activ"); should actually be $(this).addClass("active");. You mistakenly wrote it as activ.

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

Is animation not functioning for SVG path within a clip path on Firefox?

Creating the HTML for a unique effect: <svg class="svg-defs2" version="1.1" xmlns="http://www.w3.org/2000/svg" height="200" width="640"> <defs> <clipPath id="clipping2"> <!--Adjusting the x-coordinate of start will expand ...

Locating HTML content using a regular expression and saving it in an array with PHP

I am looking to find specific strings in HTML code, such as: <div class="icon_star">&nbsp;</div> and <div class="icon_star"></div> or <div class="icon_star"> </div> The above strings need to be located within H ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...

Trouble aligning image in the middle with bootstrap

After attempting the solutions proposed in previous posts, I find myself sharing my amateur code where the embedded image refuses to center and I am at a loss as to why. The image is meant to be positioned in the middle of a login screen/box; it worked for ...

Encountering an unexpected token error in Vercel during deployment, even though the code runs smoothly in the

I'm facing an issue with a SyntaxError: Unexpected token '??='. I am not sure how to resolve it, so any help would be greatly appreciated. Thank you in advance. SyntaxError: Unexpected token '??=' at wrapSafe (internal/modules ...

Create a div that pops up when clicked, just like the Fancybox jQuery feature

I'm looking to create a popup div with an elastic effect similar to jQuery's fancybox. I've tried using the following code, but it doesn't seem to work... Here is the HTML: <a href="#" id="LoginAnchorLink">ClickME</a> < ...

Picture does not appear on the webpage

Encountering an issue with two identical pages showing the same loading image upon clicking the submit button. Below is a snippet of the code: <div class="content"> <img src="/images/stroomschema.png" style="padding: 10px;"> <form m ...

Utilize Django's collapse feature in a loop to streamline your Bootstrap integration

As I navigate through the event_list, I aim to showcase details for each entry. However, my html only exhibits information for the initial entry regardless of which one I select. For instance, if I click on green event, it triggers the display of the my we ...

Issue with border-radius.htc in IE8 on a specific page (functional in a basic demo page)

I utilize border-radius.htc to create rounded corners on older versions of Internet Explorer that do not support the border-radius CSS property. I follow the instructions provided in the documentation to implement it properly. It works perfectly on a simpl ...

Clicking on a button will allow me to select only a portion of text within a specific cell of

Inside a table, there is a paragraph of text enclosed in a <td></td> element. Take for example the following passage. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Tips for adjusting the border-bottom line in real-time as text is selected from a dropdown menu

$('#select').on('change', function() { name = $('#select :selected').val(); //some code here }); . bdr-txtline { border-bottom: 1px solid black; } <div class="container"> <div class="row"> <div ...

Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below). I am in need of a RegEx that can transform JSON into an array containing all characters such as ...

"Displaying a Variety of STL Files Simultaneously with ThreeJS on a Website

Hello, I am currently working on displaying multiple STL files using threeJS in a web page. I have successfully displayed one file, but I am stuck on how to render more than one STL file on the same page. Below is my existing code: var container, camera ...

Executing a node.js function within an Angular 2 application

Currently, I am running an Angular2 application on http://localhost:4200/. Within this app, I am attempting to call a function located in a separate node.js application that is running on http://localhost:3000/. This is the function call from my Angular2 ...

Utilizing Grunt to streamline a personalized project

I have set up Grunt as my "JS Task Runner". Node.js is installed in the directory "C:/Program Files". NPM has been installed in C:/users/Peterson/appdata/roaming/npm. Inside the npm folder, I have Grunt, Bower, and Grunt-cli. I am working on a pro ...

Ways to determine whether JavaScript is enabled in the browser using .ASPX

One way to potentially reduce form spam on our site is by considering the impact of javascript. Spammers typically do not have javascript enabled when accessing websites, so this could be a quick and effective solution to lower the amount of spam we rece ...

Encountering issues with the phaser framework while setting up a server on xampp, faced with errors in javascript and html

Recently, I've been working on a game using Phaser and encountered some issues while trying to run the code in XAMPP. The game's base is located at htdocs/itw/test.html, with the necessary pngs and json file stored in htdocs/itw/assets/. The pngs ...

Issue with retrieving data from an external provider

I'm attempting to fetch data so I can tokenize my Credit Card, but I am required to use this address: this.state.data.CardRegistrationURL == "https://homologation-webpayment.payline.com/webpayment/getToken" Here is my fetch method: postI ...

Control the contents of the DOM using JavaScript in a single-page application

Is there a way to append a div element with p and h3 tags after the <product-list> component in Angular? When I try putting it inside window.onload(), it only works when the page is reloaded or refreshed. This approach doesn't work well in singl ...

Hi there, I am facing an issue with the modal window. Whenever I click on the image, it always displays the same image instead of the right one. Can you please suggest

The window opens, but instead of showing the image I clicked on, it displays the last image in the table. How can I fix this error? Below are my modal and map templates, which are the parent components of the modal. Thank you. <template> <di ...