Is it possible for two Bootstrap icon class names to be used sequentially with one taking precedence over the other?

I am having an issue with toggling a class name in my code. I have a class named (bi bi-clipboard) and I want to change it to (bi-clipboard-check) when it is clicked. However, the problem is that the new class name gets added next to the existing one like this:

Before clicking:

<i class="bi bi-clipboard" onclick="changeIcon(this)"></i>

After clicking:

<i class="bi bi-clipboard bi-clipboard-check" onclick="changeIcon(this)"></i>

Here is the method I am using:

function changeIcon(icon){
    icon.classList.toggle("bi-clipboard-check");
}

I noticed another example using fontawesome where the class toggles properly using the toggle() JavaScript method. In my case, however, the classes are not toggling correctly as they are just getting added next to each other. Any solutions or suggestions would be greatly appreciated.

Answer №1

Utilizing jQuery allows you to independently toggle the classes - refer to the demonstration below

$(function() {
  $(".bi").on('click', function() {
    $(this).toggleClass("bi-clipboard-check");
    $(this).toggleClass("bi-clipboard");

    console.log($(this).prop('classList').value);
  });
});
.bi {
  height: 100px;
  width: 100px;
  display: inline-block;
  background-color: green;
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<i class="bi bi-clipboard"></i>

Alternatively, you have the option to toggle each class separately.

Refer to the plain JavaScript demo below

function changeIcon(thisEl) {
  thisEl.classList.toggle("bi-clipboard-check");
  thisEl.classList.toggle("bi-clipboard");
  console.log(thisEl.classList.value);
}
.bi {
  height: 100px;
  width: 100px;
  display: inline-block;
  background-color: green;
  border: 1px solid red;
}
<i class="bi bi-clipboard" onclick="changeIcon(this)"></i>

Answer №2

If you prefer not to rely on jQuery,

you can achieve the same functionality by checking if a classlist contains bi-clipboard and then swapping it with bi-clipboard-check, or vice versa.

function toggleIcon(icon) {
    if (icon.classList.contains("bi-clipboard")) {
        icon.classList.replace("bi-clipboard", "bi-clipboard-check");
    }
    else if (icon.classList.contains("bi-clipboard-check")) {
        icon.classList.replace("bi-clipboard-check", "bi-clipboard");
    }
}

Another approach is to use the toggle() method:

function toggleIcon(icon) {
     icon.classList.toggle("bi-clipboard-check");
     icon.classList.toggle("bi-clipboard");
}

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

What are the steps for increasing text input size on an html page?

I was actually using w3schools, so I'm a bit lost now. On this repl called BatCoder, you can write and save Bat files. And currently, I need to expand the text input! Would really appreciate any help as I am still learning how to code. No errors, j ...

Troubleshooting $templateCache not functioning correctly within the Angular.js angular-config

I keep encountering an error message that says "angular.min.js:6Uncaught Error: [$injector:modulerr]" whenever I try to implement $templateCache in my app.config block. Interestingly, when I remove the $templateCache parameter from app.config, the errors d ...

Is it advisable to incorporate Material-UI into a React project?

When it comes to designing a login page in react, I stumbled upon material-ui. The real question is, should we utilize Material-UI for this purpose? Furthermore, how can we manage styles in a separate file in the given examples? It seems logical to place t ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

Fetching the latest phase using BS-stepper

Does anyone know how I can retrieve the current page using bs-stepper? I've been struggling with this issue for quite some time now. This is what my code looks like: <script> var stepper = new Stepper($('.bs-stepper')[0]); </sc ...

Include a custom HTML element on a webpage using Python's Selenium module

I am looking to modify the HTML of a webpage by adding an element. Prior to modification: div p something /p /div Post modification: div form p something /p /form /div Is it feasible to accomplish this task? I would greatly appreciate any guidance. Than ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

javascript highchart image carousel

I am currently working on a visual chart project using the JavaScript library highchart. After setting up my chart with some dummy data, I am looking to incorporate functionality that allows for triggering an image slide based on the chart data. Specific ...

How can I utilize a service for monitoring user data and ensuring that $watch() functions properly?

I'm a beginner when it comes to AngularJS and currently working on building a website that has a navigation bar dependent on the user's login status. My approach involves using a state model design with the Nav controller as the parent state for ...

Is there an easy way to determine if an element inside a Vue component is overflowing?

I created a unique component called ResultPill which includes a tooltip feature (implemented using vuikit). The text displayed in the tooltip is determined by a getter function called tooltip, utilizing vue-property-decorator. Here are the relevant parts o ...

Node.js (npm) is still unable to locate python despite setting %PYTHON% beforehand

Trying to get Node.js to work is proving to be more challenging than expected! Despite having two versions of Python on my computer, it seems that Node.js only works with the older version, 2.7. When I encountered an error, it prompted me to set the path ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

Transforming a collection of items into a JSON format string

UPDATE: There was a mistake in the programming, please refrain from submitting answers. This question will be removed. If you have already submitted an answer, kindly delete it. I am attempting to submit a form using jQuery and ajax. One of the fields con ...

The grouping functionality of the Material UI Buttongroup seems to be failing to properly

Working on a review score list currently, where I've set up a RadioGroup with RadioButtons. However, the issue is that the RadioButtons are not aligning properly with the RadioGroup. The goal is to have the radiobuttons styled similarly to the exampl ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

What is the functionality of client-side applications?

I am new to web development and my programming background is primarily focused on algorithms and creating visualization tools using local Windows forms. I often distribute these tools via email as compiled exe files (C++ or C# win form) to my math students ...

What is the best way to retrieve the parent of the initial jQuery object?

At the bottom of a lengthy table containing multiple button.enter-match elements, I am using the following code: $("button.enter-match") .button() .on('click', function() { $("form.enter-match").dialog({ modal: true, height: ...

The functionality of using variables in conjunction with the .insertAfter method appears to be

As a novice coder with limited English skills, I apologize in advance. Here is the CSS code snippet I am working with: #wrapper{ width: 200px; height: 300px; border: solid 1px #000; overflow: visible; white-space: nowrap; } .page{ ...

How can we enhance our proxyURL in Kendo UI with request parameters?

As outlined in the Kendo UI API documentation, when using pdf.proxyURL with kendo.ui.Grid, a request will be sent containing the following parameters: contentType: Specifies the MIME type of the file base64: Contains the base-64 encoded file content fil ...

Ways to modify the background images in doxygen

Currently, I am facing a challenge while customizing Doxygen's output and my main roadblock is the menu bar. To address this issue, I decided to generate custom CSS and HTML files provided by Doxygen by executing the command: doxygen -w html header. ...