How to toggle classes on anchor tags using jQuery for Twitter Bootstrap buttons?

I built a single-page website. The navigation is made up of buttons styled with bootstrap 3.

Since it's a single page, the buttons are anchor tags. I'm trying to figure out how to apply an .active class to the last clicked anchor tag.

Here is the structure of my HTML:

<a href="#home">
    <button type="button" class="btn btn-default btn-lg active">
    <span class="glyphicon glyphicon-home"></span> Home
    </button>
</a>

<a href="#about">
    <button type="button" class="btn btn-default btn-lg">
    <span class="glyphicon glyphicon-user"></span> About
    </button>
</a>

Additionally, this is the CSS I am using:

.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
border:none;
background-color: #2C3E50;
border-bottom: 1px solid #2C3E50;
}

Answer №1

Check out this solution...

$(function() {
    $("a").on("click", function() {
        $(".btn-default.active").removeClass("active");
        $(this).find(".btn-default").addClass("active");
    });
});

Alternatively, you can try this...

$(function() {
    $("a").on("click", function() {
        $("a.active").removeClass("active");
        $(this).addClass("active");
    });
});

If you're unsure whether to add the active class to the link or the enclosed button, these two solutions provide options for both cases.

Answer №2

If you want to dynamically apply a class using jQuery, you can utilize the jQuery addClass method.

$('a#buttonid').click(function(){
    $(this).addClass('active');
});

It is important to ensure that the class is not already present, and also remove the 'active' class from the other buttons if necessary.

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

Display an alert using JQuery if the page remains inactive for a specific amount of time, ensuring it only triggers once

I've been browsing different solutions on how to display an alert or popup when there is no activity on a webpage. However, none of the examples I found actually match what I want to achieve. Here's what I'm looking for: Load the webpage. ...

Are there any images included in the WebResponse being downloaded?

I need to download HTML efficiently in order to parse it with minimal bandwidth consumption. Here is a snippet of my code: if (!String.IsNullOrEmpty(siteAddress)) webReq = WebRequest.Create(siteAddress) WebResponse webRes ...

Align a block vertically

Is there a way to perfectly center a div vertically? There are plenty of methods for horizontal alignment, but no matter what I attempt, getting vertical centering proves to be a challenge. body { vertical-align: middle;} No effect body {text-align ...

Exploring the world of flexbox and experimenting with implementing flex-wrap at a specific breakpoint

I am working on a layout that includes a module containing various content. My goal is to have the progress bar, along with the labels "parts" and "projects," positioned underneath an image and expand to the full width of the module when the window size go ...

Safari iOS does not properly support responsive images when using srcset and sizes

I am facing an issue with the following code snippet: <img src="/img/footer/logo_white.png?v=2.0" srcset="/img/footer/logo_white.png?v=2.0 1x, /img/footer/logo_white2x.png?v=2.0 2x" > This ...

Enable drawing on a div element and synchronizing it across multiple divs using Javascript and HTML5

I am embarking on a project to create a website that allows users to doodle on an element and share it with others viewing the page using ajax - essentially a small-scale whiteboard feature. While I have a good grasp of HTML, CSS, Javascript (specificall ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Starting a div programmatically and then running into trouble when trying to close it, an error was encountered with an end tag for "div" without a corresponding start tag

I am looking to create the following HTML structure: <div id="my-grid" class="isotope"> <div class="myProject-item">....</div> <div class="myProject-item">....</div> <div class="myProject-item">....</div> ...

Retrieving data-id attribute from selected element using jQuery when the value changes

Can you retrieve the value of a data attribute during an on change event? jQuery(document).ready(function($) { $('.mystatus').on("change", function() { var value = this.value; alert(value); var myid = get the data-myid at ...

Trouble updating Kendo DropDown in Internet Explorer

Having an issue with updating a Kendo DropDownList through a javascript function. It works fine in FireFox and Chrome, but not in Internet Explorer. @(Html.Kendo().DropDownList() .Name("myDDL") .HtmlAttributes(new { style = "width: 320px" }) . ...

The 1st DIV element nudges the content within the 2nd DIV Element, causing it to stretch beyond the screen with 100%

I have gone through several other questions, but I am struggling to integrate the solutions into my problem. My main content DIV is set to 100% height and works perfectly fine until I add another element outside of the DIV towards the top of the browser. ...

Stopping a Bootstrap Modal Closure When Validation Errors are Present

I'm dealing with a bootstrap model within a .NET MVC5 app. Although my client-side validation is functioning properly (using jquery unobtrusive in MVC), I have encountered an issue where the modal keeps closing even when there are errors present. How ...

Having trouble with the vertical-align property in Google Chrome?

<html> <head> <style> table,td {border:1px solid black ;} table {width : 80% ;height:80%;} .top {vertical-align:top}; .center {vertical-align: middle}; .bottom {verti ...

Completely place one element with respect to its sibling element

I am currently facing a situation where I have implemented a Navigation bar wrapper that reveals an overlay across the entire page when clicked. In order for this setup to function correctly, all the elements that the overlay covers must be sibling elemen ...

CSS Trick: How to Clear Content in a 3-Column Div arrangement

I've been struggling to clear the content below my three div columns, each consisting of a span with centered text and a textarea. It seems that the issue arises from the floating div tags without proper clearing. When viewed in Firefox, the next ele ...

The idea of a webpage completely powered by Ajax

I'm currently in the process of creating a compact website that utilizes full ajax requests for features such as login and registration, all done asynchronously. However, I've come across an issue where if a user decides to refresh the site, any ...

What CSS attribute determines the distinction in visual presentation between two elements that share the same CSS configurations?

In the HTML code below, there is a button and a div with the same class and content: <div class="root"><!-- --><button class="outer"><div class="middle"><div class="inner">label</div></div></button><!-- - ...

Perform encryption and decryption of a JSON file on separate webpages

Situation : Is there a way to encode JSON data in the getuser.php page and then decode it in index.php? In my getuser.php file, I use echo (json_encode($data)); which produces the following example output: { "id": 2, "username": "Teeto", "sur ...

Troubleshooting issues when utilizing flexbox in Firefox and Chrome version 48

Chrome 47 Behavior: The .scroll div scrolls correctly in Chrome 47, taking up 100% height using flex. Firefox Behavior: In Firefox, the .scroll div does not scroll properly and instead uses the content height. What is the solution that works across diffe ...

When a specific JavaScript function is triggered, the value of an HTML control will reset to its original default value

I have a form with a specific requirement. I need to allow users to input data in a text field and press enter, which should dynamically create new controls like another text field, a dropdown menu, and another text field using jQuery. While the functional ...