Manipulate CSS classes according to the attribute value of a button

Is there a way to change the icons on a navigation button based on an attribute value using jQuery? I have a button that expands and collapses the navigation menu, and I want to toggle between left arrows and right arrows icons. I thought of achieving this by adding or removing CSS classes.

<button class="t-Button t-Button--icon t-Button--header t-Button--headerTree" aria-label="Expand / Collapse Navigation" title="Expand / Collapse Navigation" id="t_Button_navControl" type="button" aria-controls="t_TreeNav" aria-expanded="true">
  <span class="fa-angle-double-left fa-lg" aria-hidden="true"></span>
</button>
$('.t-Header-controls button').on('classChange', function() {

$('.t-Header-controls button[aria-expanded="true"]').find('span').addClass('fa fa-angle-double-left fa-2x fa-lg');
$('.t-Header-controls button[aria-expanded="false"]').find('span').addClass('fa fa-angle-double-right fa-2x fa-lg');

});

I am struggling with adding and removing classes from the span element as described above. The current code is not working. Basically, I need to remove the .fa-angle-double-left class and add the .fa-angle-double-right class when the button is clicked and its attribute aria-expanded is set to "false". And vice versa when aria-expanded is set to "true."

It seems that when the side menu is expanded, the button's aria-expanded property changes to "true," and I need the icon to be left directional arrows (.fa-angle-double-left fa-lg).

When the side menu is collapsed, the aria-expanded property changes to "false," and I need the icon to be right directional arrows (.fa-angle-double-right fa-lg).

Please help me find the correct solution.

Answer №1

When an attribute changes, no event is automatically triggered. One way to work around this is to manually trigger an event when the attribute is changed programmatically:

$('.t-Header-controls button').attr('aria-expanded','false').trigger('classChange');

// in a separate JavaScript file
$('.t-Header-controls button').on('classChange', function() {
    $('.t-Header-controls button[aria-expanded="true"]').find('span').addClass('fa fa-angle-double-left fa-2x fa-lg');
    $('.t-Header-controls button[aria-expanded="false"]').find('span').addClass('fa fa-angle-double-right fa-2x fa-lg');
});

Answer №2

An efficient way to accomplish this is by utilizing the toggleClass method in jQuery. By overriding the image URL or glyph in your CSS and toggling the class on click, you can seamlessly change the displayed image.

For instance:

<style>
.element {
 background-image: url(your icon);
}
.element.active {
 background-image: url(your other icon);
}
</style>
<script>
$(.element).click(function(){
 $(this).toggleClass('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

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

CSS: Navigation links at the bottom of the page

I am looking to design a menu where all the menu items are aligned at the bottom, even if they span across multiple lines. ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: ...

JavaScript function encountered an error due to an expected object

Currently, I am in the process of developing an application using VS2015, JavaScript, Angular, and MVC 5. Here is an excerpt of my JavaScript code: var myApp = angular.module('QuizApp', []); myApp.controller('QuizController', [&apos ...

Firefox displays CSS inaccurately due to inconsistent spacing

I am currently utilizing Concrete5 for the construction of a website, which can be found at this link: On specific pages like the Gallery, Firefox is causing the header (including navigation and h1 tag) to shift down inexplicably. This issue does not occu ...

Tips on preventing conflicts between jQuery FancyBox and mouse scrolling

<script src="js/jquery-1.9.1.js"></script> <?php include("fancybox/fb.php"); ?> <script type="text/javascript" src="js/jquery.slimscroll.js"></script> <script type="text/javascript"> ...

Using jQuery to remove the 'active class' when the mouse is not hovering

I recently came across this amazing jQuery plugin for creating slide-out and drawer effects: However, I encountered a problem. I want to automatically close the active 'drawer' when the mouse is not hovering over any element. The jQuery plugin c ...

Create a CSS border that resembles the one used in Google's signup form

lies a curious inquiry: what unique border style is in play here? It rests slightly raised against the backdrop, creating an intriguing visual effect. After combing through various sources online, the answer still eludes me. Perhaps turning to Google' ...

Showing an image on a blurred background-image at the top of the webpage

Is it possible to overlay an image on top of another image, with the top image appearing blurred in the background? .background-image { background-image: url('https://images.pexels.com/photos/366968/pexels-photo-366968.jpeg?w=1153&h=750&a ...

Utilizing a dropdown feature in Bootstrap for creating X columns of lists instead of a traditional single list

Check out my Fiddle. Beneath Dropdown1 lies a single-column list of actions. I'm looking to expand this list across multiple columns, like 5 or the width of the page. I'm hoping there's a Bootstrap CSS class I can use for this, but I migh ...

Calculating the Mean of an Array in JavaScript

Greetings! I am working with an array that has the following structure: [ { group: "23", delays: [ { Station: "a", Arrival: "3", Departure: 0 }, { Station: "b", Arrival: -179, Departure: 0 }, ...

Choose the initial element that has a unique label

Looking to create a custom CSS class that will apply a background color only to the first element with a specific tag... This is what I have so far: .blue p:first-of-type { background-color:#2E9AFE; } It works in this scenario: <div class="blue" ...

Eliminate the header top margin in Bootstrap

HTML <div class="container-fluid"> <div class="row"> <div class="page-header header_site"> <h1><font>ABC Company</font></h1> </div> </div> </div> CSS Code: .header_site { b ...

creating links for navigating to previous pages is crucial for enhancing

Take a look at the code snippet provided. The objective here is to display the previous pagination numbers if the "pagestart" input is 5 or greater. Otherwise, only 5 page numbers will be shown. Refer to the attached HTML for a clearer understanding. Thank ...

Troubleshooting HTML/CSS and JavaScript Issues with Dropdown Menus

I'm having trouble getting my dropdown menu to work properly and I can't figure out why. The JavaScript code should toggle a class that hides the language options and slides up the other tabs like "Contact". However, when I click the button, noth ...

Error encountered while trying to embed SVG file

My method involves utilizing an ajax call to fetch an htm file that constructs an SVG. Although the call retrieves the file successfully, the designated area where it should display only shows: https://i.sstatic.net/8G9IU.jpg Could this issue be related ...

How can I determine the length of the returned array after a successful jQuery Ajax

I am struggling with looping through the Array returned from PHP. However, when I use jQuery .length, it returns 'undefined'. 'undefined' PHP: $items = array(); $items["country"] = "North Korea", $items["fruits"] = array( ...

Identifying and categorizing flip switches with jQuery without relying on div elements

Is it possible to have two jQuery flip switches side by side, but only one visible if the screen is too narrow? I've tried assigning different classes to each switch for styling purposes, but it doesn't seem to work correctly. When I assign a cl ...

jQuery reports that the array has a length of zero

I'm encountering an issue where the loop is not executing after submitting. The strange thing is that although I can see values present, the array length is showing as '0' (please refer to the picture). Why isn't it entering the loop an ...

Galleria: Execute a JavaScript function whenever a new image is displayed

Looking for guidance in the Galleria JavaScript file on how to trigger a JavaScript function whenever the current picture is changed (previous, next, or by clicking on a thumbnail). Seeking insights from those familiar with Galleria. Any thoughts? ...

Images in jQuery rotate depending on the movement of the cursor

My oven has knobs that rotate when you hover over them, but they only turn clockwise. Is there a way to track which direction the cursor enters the image from - left or right - and rotate it accordingly? For example, clockwise if from the left, countercl ...