Performing simultaneous text changes and toggleClass with JQuery

When a user clicks on a button, I want to change the displayed text and toggle between two different classes simultaneously. However, my current code only does one of these actions and not both.

$(document).ready(function() {

  $('.more-benefits-btn').click(function() {
  
    $(this).text($(this).text() == 'Show Less' ? 'Show More Benefits' : 'Show Less');
    $("i", this).toggleClass('fal fa-chevron-down fal fa-chevron-up');

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span class="more-benefits-btn">Show More Benefits&nbsp;<i class="fal fa-chevron-down"></i></span>

Answer №1

The issue with the <i>class not toggling is due to the removal of the <i> element when using the text method.

To resolve this problem, you can implement the following code:

  $('.more-benefits-btn').click(function() {
  var icon = $("i", this);
  $(this).text($(this).text() == 'Show Less' ? 'Show More Benefits' : 'Show Less');
  icon.toggleClass('fa-chevron-down fa-chevron-up');
  $(this).append(icon);
  });

Answer №2

Maybe it's due to the fact that it completely alters the content within the button

$(document).ready(function () {

$('.more-benefits-btn').click(function () {
  var $this = $(this).find('span'); 
    $this.text($this.text() == 'Show Less' ? 'Show More Benefits' : 'Show Less');
    $(this).find('i').toggleClass('rotate');
});
});
i{
display: inline-block;
transition:all ease .5s;
}
i.rotate{
transform:rotate(180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="more-benefits-btn"> <span> Show More Benefits </span><i>V</i></button>

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

I have noticed that the display:none property for <span> elements does not seem to work in IE8 on some computers, although it does

<span id='x' style='display:none;'> <input type=button value='x'> </span> <span id='y' style='display:none;'> <input type=button value='y'> </span> Although th ...

How can we display a local image as a backup in case the external image fails to load?

My webpage includes anchor tags with images like this: <a href=\"http://www.duckbill.com" target=\"_blank\"><img height=\"160\" width=\"160\" src=\"http://images.duckbill.com/PlatypiOnVacation.jpg\" al ...

Parsing JSON using jquery.TokenInput (structure)

I am encountering an issue with jquery.tokenInput. Below is my tokenInput code: $(".search-betrocket").tokenInput("http://www.websitehere.com/web/search", { searchDelay: 2000, minChars: 3, tokenLimit: 5, hintText: "Smart Search...", ...

Card design in Bootstrap 4 showcasing a dropdown menu located on the right side

I am currently working with Bootstrap 4 and created a card: <div class="card text-center"> <div class="card-header"> Featured </div> <div class="card-block"> <h4 class="card-title">Special title treatment</h4 ...

Assigning properties in html

When the status is equal to "complete", I need to disable an input tag based on a certain condition. One way to achieve this using javascript is by utilizing the setAttribute method. var element = document.querySelector("input"); element.setAttribute("d ...

Issue with implementing autocomplete using AJAX and PHP for multiple input fields

HTML code: <table> <tr> <td align="center"> <label for="InputBox1"><b>~</b><font color="red">*</font>: &nbsp;</label> </td> </tr> <tr> <td align="center"> <div id="1"> ...

Can different table headers be inserted under a Colspan?

I have been attempting to insert text above each column in Colspan without success. https://i.sstatic.net/MxQPj.png shows the image of how I want the columns in colspan to be displayed as 1 2 3 4 5 O, but I am unsure of how to achieve this. Here is an exam ...

The puzzling Webkit shadow inset glitch

This particular issue differs from the Google Chrome inset box-shadow bug on Windows, not on Mac: Better workaround? However, it appears to be connected to the problem discussed in: Weird box-shadow artifacts in webkit. When applying an inset box-shadow ...

Establish a connection that mirrors the previously clicked hyperlink

I am attempting to create a functionality where a link can return to a specific link that matches the one clicked on a main page. For example: <a href="link.html" onclick="store this link in memory" target=home></a> <a href="the stored lin ...

Struggling to create a dynamic design for a nested column using bootstrap

After creating a layout in Figma, I have set up a grid structure as follows: <div class="container-fluid"> <div class="row" id="sobre-nos-wrapper"> <div class="col"> <div class="row"> <div class="col ...

What is the method for retrieving the data shown in a KendoGrid in JSON format?

I am working with a kendoGrid and my goal is to extract the filtered and sorted data in JSON format. How can I accomplish this? For example, something along these lines, var grid = $("#grid").data("kendoGrid"); alert(grid.dataSource.data.json); // I hav ...

My code seems to be experiencing issues with the carousel functionality despite incorporating Bootstrap

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <% campground.images.forEach((img,i)=> { %> ...

Display an alert message using alert() if duplicate data is submitted through ajax

I'm using a form and jQuery to submit the form via AJAX. $("form#form").submit(function (event) { //submitting vendor name event.preventDefault(); var formData = new FormData($(this)[0]); //validation for duplicates goes here ...

Discovering a failure in executing the $.post() method

Upon the page loading, I have implemented a jQuery $.post() function. $.post("area.php", {'user': $('#state').val()}, function(info){ //do something }); Is there a way to determine if no info is returned if there is a connection ...

"Error encountered while trying to perform a JavaScript _doPostBack

In my asp.net application, I have an HTML table where each td element has a unique id. When a td element is clicked, I use JavaScript to store the id in a hidden field. After that, I attempt to trigger _doPostBack from JavaScript to utilize the hidden fiel ...

Enhance your application with a redo-undo feature using AngularJS to handle extensive amounts of

At this moment, I am dynamically creating a table where multiple rows are added on the fly, just like in Excel. This table could potentially have millions of rows. To implement redo/undo functionality, I've integrated Angular-Chronicle. Everything wo ...

`Use Swing to showcase the power of HTML5`

Many inquiries have been made on how to showcase HTML content in a swing application, yet there seems to be no library that fully supports html5 (especially for those who cannot afford JxBrowser). I possess locally stored html5 webpages and would like to ...

JavaScript can be utilized to monitor outbound clicks effectively

I am currently working on implementing the code found at this link: Make a ping to a url without redirecting. The original poster is looking to ping a URL without opening multiple windows. My goal is to achieve the same functionality, but I also want to vi ...

Using jQuery to make a call to a VB.NET function and then using the response to fill in the content

I have implemented the following code: $("#dropdownPaper").change(function () { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "NomexLine500A.aspx/Ca ...

What is the best way to adjust the translateX value upon clicking a button?

I'm exploring react for the first time. I want to create a button that will change the translateX value by 1170px when clicked, but I am confused about how the onClick attribute works in reactjs. Below is the code snippet: function Slideshow() { co ...