Tips for adding a CSS class to an HTML element on-the-fly

As a newcomer to JavaScript and AngularJS, my question may be considered naive by some.

I am currently working on a tutorial project involving AngularJS.

Here is the HTML code snippet I am dealing with:

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://acornejo.github.io/bootstrap-nav-wizard/bootstrap-nav-wizard.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<div class="container">
  <ul class="nav nav-wizard">
    <li class="active"><a href="#">Step1</a></li>
    <li><a href="#">Step2</a></li>
    <li><a href="#">Step3</a></li>
  </ul>
  <hr>
</div>
</body>

My goal is to make the <a> tag active when clicked (i.e., set the attribute class of the corresponding <li> element to active like in step1).

How can I achieve this programmatically on the client side?

Answer №1

Greetings Michael,

If you are utilizing Angular, it is recommended to employ the following syntax

<li ng-class="'yourclass': expression">

For further details, refer to the ngClass documentation

Feel free to explore this Codepen example

Answer №2

To implement dynamic styling in AngularJS, you should utilize the ng-class directive along with data bindings.

For a code example, check out this JSFiddle: https://jsfiddle.net/bdLwrs1p/

<li ng-class="{active: active == 1}" ><a href="#" ng-click="active = 1" ng-init="active = 1">Step1</a></li>
<li ng-class="{active: active == 2}" ><a href="#" ng-click="active = 2" >Step2</a></li>
<li ng-class="{active: active == 3}" ><a href="#" ng-click="active = 3">Step3</a></li>

Answer №3

To change the class of an element based on a controller variable, you can utilize the ngClass directive in AngularJS. For a practical example, take a look at this codepen demo.

Here's how you can apply this concept to your list item:

ng-class="{active: isClicked}" 

and then in your anchor tag:

ng-click="isClicked = true"

Once clicked, the list item will dynamically change its class to "active" as defined by the CSS properties.

Answer №4

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link href="http://custom.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="http://jdoe.github.io/custom-theme/custom-style.css" rel="stylesheet"/>
    <link href="http://custom.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <body>
    <div class="container">
      <ul class="nav nav-wizard">
        <li class="active"><a href="#">Step1</a></li>
        <li><a href="#">Step2</a></li>
        <li><a href="#">Step3</a></li>
      </ul>
      <hr>
    </div>
    </body>
<script type="text/javascript">
$('a').click(function(){
    $('li').each(function(){
       $(this).removeClass('active'); 
    });
$(this).closest('li').addClass('active');
});
</script>

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

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

The accordion won't function properly if it is added using append() after the document is ready

I have implemented a button to add an accordion, but unfortunately it doesn't seem to be working properly. I am unsure of how to troubleshoot and resolve this issue. If the accordion HTML is appended after the document.ready() function, then the accor ...

Injecting CSS styles into dynamically inserted DOM elements

Utilizing Javascript, I am injecting several DOM elements into the page. Currently, I can successfully inject a single DOM element and apply CSS styling to it: var $e = $('<div id="header"></div>'); $('body').append($e); $ ...

"Emulate the social sharing capabilities of CNET with interactive share

I remember a while ago, CNET had these amazing Social Share buttons that, when clicked, would reveal a "dropdown box" with the social network share dialog. Does anyone know how they achieved that? I've searched but couldn't find any information ...

Trouble filling a List<WebElement> from a Table using Selenium Java

I am experiencing difficulty filling a List from a table: <div class="es"> <button class="btn btn-primary" [routerLink]="['add']">New User</button> </div> <div class="User_table" id="t02" > <div class="table ...

Using AngularJS ng-repeat to pass href links

I am facing an issue with displaying hyperlinks in a list of messages obtained from server response using AngularJS. $scope.messages = [] When a button is clicked, the content of a text area is added to the array using ng-click method. This message is th ...

What is the significance of the dollar sign prefix ($) in Vue.js?

Can you explain the significance of the dollar symbol prefix used before property names in Vue.js? For instance, consider this code snippet: this.$emit('clicked', 'demo') ...

Issues with the animation of letters bouncing in css3

I wanted to implement an animated effect in CSS, specifically the "jumping letters" effect. However, it seems that the current implementation is not working as intended. The entire word moves upward instead of each letter bouncing individually. Can you h ...

Steer clear of downloading images while on your smartphone

As I develop a responsive website, I encounter the challenge of optimizing image loading based on viewport size. While using CSS to hide images not needed for certain viewports can reduce display clutter, it does not prevent those images from being downloa ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Converting dates in Javascript

I have retrieved a date/time value of "20131218" from an API response. My goal is to transform this date into the format "2013-12-18". In PHP, this can be easily achieved with the following code: echo date("Y-m-d", strtotime('20131218')); The ...

The XML response from Ajax is returning as empty

My goal is to retrieve XML data from an ajax request and extract information using the DOM. The ajax request itself seems to be working fine as I can access AjaxRequest.responseText without any issues. However, I am encountering an error message stating: ...

How to choose an item from a dropdown list using its item number with jQuery

Is there a way to select an item in a dropdown menu by its item number using jQuery? <select id="selectbox" style="width: 220px;"> <option value="Option 1">Option 1</option> <option value="Option 2">Option 2</option> < ...

Incorporating JavaScript/jQuery values into C# backend with ASP.NET

Despite attempting all possible methods, I am unable to pass the screen.width value from a JS script on an aspx page to C# in the code behind. Even though the screen.width is correctly assigned, it never gets passed to my hidden field value. <asp:Conte ...

Modify the behavior of the tab key using JavaScript

I'm currently working on a text editor embedded within a contenteditable div. My goal is to modify the [TAB] functionality so that instead of shifting focus to the next element (as is done by default in browsers), it will either insert spaces or a &b ...

What is the best way to display data retrieved from a GET request in Angular?

Spending too much time on a development issue is causing me frustration. After extensive research, I find myself stuck at this point. The problem lies in making a GET request from a service which is called by a controller. Below is the code for the servi ...

The jspdf tool tries to cram my extensive data into a single page, resulting in an overcrowded and barely visible PDF document

My PDF generated using Jspdf is being forced to fit in one page, making it difficult to see all the data because there is a huge amount of information present. To view the issue, please visit this link: https://jsfiddle.net/frost000/04qt7gsm/21/ var pdf ...

Deactivate the dependent picklist functionality on a Visualforce page

After successfully disabling all input and select elements on my page using the following code: $('input').prop('disabled',true); $('select').prop('disabled',true); I encountered an issue with two picklist fields i ...

Uniting the client-side jQuery and server-side Express for enhanced functionality

Currently, I am deepening my understanding of Express/Node. My goal is to construct a basic HTML form that undergoes client-side validation (using jQuery/AJAX) while also being processed server-side (via Express.js). The application's complexity remai ...

Click action: two functions, but only the first one seems to be functioning. Feeling frustrated

Here is the HTML code I am using: <td width="15%" align="center"><input name="submit" type="submit" class="button" value="Basic" tabindex="13" onclick="return submit_Click('bxbas','bxsht');" /></td> And b ...