Switch the style of the anchor tag using JavaScript

I need assistance with modifying a list on my webpage. Here is the current structure:

 <ul id="breadcrumbs" class="breadcrumbs-two">
        <li><a href="#" class="current"  id="a1">Step1</a></li>
        <li><a href="#"  id="a2">Step2</a></li>
        <li><a href="#"  id="a3">Step3</a></li>
        <li><a href="#"  id="a4">Step4</a></li>
        <li><a href="#"  id="a5">Complete</a></li>
    </ul>

I want to apply a CSS class to an anchor tag when a specific link button is clicked.

The CSS code to be applied is as follows:

 .breadcrumbs-two .current
    {
        background: #99db76;
    }

    .breadcrumbs-two .current, .breadcrumbs-two .current:after
    {
        border-left-color: #99db76;
    }

    .breadcrumbs-two .current, .breadcrumbs-two .current:before
    {
        border-color: #99db76 #99db76 #99db76 transparent;
    }

How can this be achieved?

I attempted the following approach

function addClass(dis) {
        dis.className += "current";
    }

 <li><a href="javascript:addClass(this)"  id="a1">Step1</a></li>

  <asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="addClass('a1')">Done</asp:LinkButton>

However, it is not functioning as expected.

If anyone could provide guidance, I would greatly appreciate it.

Thank you in advance. Gulrej

Answer №1

For those needing a navigation menu, you may want to consider this approach based on what I'm currently using in my project:

 $('.breadcrumbs-two li a').click(function(){
        $(this).parent().parent().children('li').removeClass('current');
        $(this).addClass('current');
 });

When clicking a link, it will clear the styling from previously selected links and apply the .current class to the newly clicked link.


I initially assumed that the <li> tags were the targets for clicks. You could test out this alternative method:

$.fn.breadcrumb = function( content, title ){
    $(this).parent().parent().children('li').removeClass('current');
    $(this).addClass('current');
};

$('#LinkButton1').click(function(){
    $(this).breadcrumb();
});

Answer №2

You have the flexibility to apply different styles and colors using CSS for active, visited, hover, link states, and more.

a {
    outline: 0;
    text-decoration: underline;
}

a:link {
    color: #0099FF;
}

a:visited {
    color: #0099FF;
}

a:hover {
    color: #FFFF00;
}

a:active {
    color: #33FF66;
}

Answer №3

Give this a shot:

$(document).ready(function(){
    $('.crumbs-2 a').click(function(){

        $('.crumbs-2 a').removeClass('active');
        $(this).addClass('active');

    })
})

Answer №4

Include the following code in your anchor tag's href attribute

javascript:toggleClass(this)

Create this function in JavaScript

function toggleClass(element)
{
   element.className = element.className + ' customclass';
}

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

Having Trouble with the Fancybox Title Attribute Showing Up?

Looking for some help using the title attribute to recognize participants in a fundraising effort. The title tag is placed inside the href, but it's not displaying as expected. Additionally, the title positioning appears differently in Internet Explor ...

What is the best way to specify the JSDoc types for this.field within the Mocha TestContext during the before() hook, in order to provide clarity for other it() tests as well as IntelliJ?

I am looking for IntelliJ, or a similar IDE like WebStorm or VSCode, to provide auto-complete for the fields I define in my Mocha.js before() hook within my test context. Furthermore, I want to have access to the auto-complete documentation of those fields ...

Issue with ExpressJS Regex not correctly matching a path

I'm currently struggling with a simple regex that is supposed to match words consisting of letters (0-5) only, but for some reason it's not working as expected. Can anyone help me figure out the correct expression and how to implement it in Expre ...

What is the best way to retrieve an object from every function?

I'm dealing with a <div> containing radio buttons: <div id='RB-01'> <span>Item_1</span><input type='radio' name='RB01' value='1'><br /> <span>Item_2</span><inp ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

Obtain the length of a sound file in .wav format

Can anyone suggest a way to incorporate a waveform or horizontal bar on a website that displays the duration of a WAV file in seconds using HTML text? For instance, for a 60-second WAV file: I'm open to any ideas. ...

Executing a function on a dropdown menu in AngularJS

Currently facing an intriguing scenario that is causing me some confusion. This question is specifically for those well-versed in Angular UI Grid, but all responses are welcome. The situation revolves around a UI Grid with a dropdown functionality impleme ...

Initiating a file download using HTML

When I try to initiate a download by specifying the filename, instead of downloading, it opens in a new tab. The code snippet below shows what I am currently using. Additionally, I am working on Chrome Browser. <!DOCTYPE html> <html> < ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

unresponsive script caused by videoegg javascript code

Has anyone encountered a message like this before? "A script on this page might be occupied, or it could have stopped responding. You have the option to stop the script now, or you can wait to see if it finishes." No JavaScript errors are visible in the ...

When trying to use selenium.WebDriver, an error pops up: "missing ) after argument list."

Trying to extract content from the ::after element is proving to be a challenge. Despite my attempts, I keep encountering an exception: "OpenQA.Selenium.WebDriverException: "javascript error: missing ) after argument list My setup includes VSC, Selenium ...

upload document to joomla

Hello, I am currently working with Joomla and I am attempting to provide users with the option to download a CSV or Excel file of the table they are currently viewing. I have been using PHPExcel for the file creation process. Here is the content of my exp ...

Adjust the translateX value and element size based on either the parent element's size or the window's dimensions

Is this question specific enough to relate to others' problems? My issue involves two elements, a child and a parent, with the child element rotating around the parent using CSS animations. <div class="planet"> <div class="moon"></di ...

Checking if children have certain text using jQuery

My task involves filtering an HTML table. In order to accomplish this, I have created an 'each' callback for all 'tr' elements and check if any of their children contain a specific pattern. $("#filter").keypress(function() { var fi ...

What is the best way to align a container in the middle of the page without positioning the text in the center

Query 1: What is the best way to horizontally center the container div while keeping Typography aligned to the left? Expected outcome: https://i.stack.imgur.com/yKCZF.jpg Query 2: How can a component be positioned below the AppBar without relying on mar ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

How can I access data from a function that is executed within a method in Vue.js?

When working with vuejs and JS scopes, passing a value to a style property inside data can be tricky. The issue arises when trying to access this.data.property: Vue.component ('loader-component', { template: '#loader-template', mo ...

What could be causing the issue with perspective not functioning properly?

I'm attempting to create a simple 3D square shape. div { width: 300px; height: 300px; background: #333; transform: rotateX(50deg); -webkit-transform: rotateX(50deg); -moz-transform: rotateX(50deg); -ms-transform: rotateX(50deg); perspective: ...

Is there a way to selectively import specific functions from a file in NextJs/React rather than importing the entire file?

Imagine this scenario: we have two files, let's call them File A - export const a = () => {} export const b = () => {} Now, consider importing this into File B - import { a } from 'path' When I tried running npm run analyze, it showe ...