Changing the font awesome icon dynamically during execution

Changing icons dynamically with Font Awesome - I'm attempting to switch between the Font Awesome sun and moon icons dynamically using the JavaScript code below, but it doesn't seem to be functioning as expected.

I am loading Font Awesome from a local directory instead of a repository. I have verified that the fonts are being successfully loaded.

<head>
    <style>
        body {
            padding:10% 3% 10% 3%;
            text-align:center;
        }
        img {
            height:140px;
            width:140px;
        }
        h1 {
            color: #32a852;
        }
        .mode {
            float:right;
        }
        .change {
            cursor: pointer;
            border: 1px solid #555;
            border-radius: 40%;
            width: 20px;
            text-align: center;
            padding: 5px;
            margin-left: 8px;
        }
        .dark {
            background-color: #222;
            color: #e6e6e6;
        }
    </style>
    
</head>
 
<body>
    <div class="mode">
        Dark mode:            
        <span class="change">OFF</span>
    </div>

     
    <script>
        $( ".change" ).on("click", function() {
            if( $( "body" ).hasClass( "dark", "fa-solid fa-moon")) {
                $( "body" ).removeClass( "dark" );
                $( ".change" ).text( "OFF" );
            } else {
                $( "body" ).addClass( "dark", "fa-solid fa-sun" );
                $( ".change" ).text( "ON" );
            }
        });
    </script>
</body>

Answer №1

If you're looking to achieve this using only Javascript, you can follow the code snippet below:

const toggleBtn = document.querySelector('.toggle-btn');

toggleBtn.addEventListener('click', function() {
  toggleBtn.classList.toggle('dark-mode');
  toggleBtn.classList.toggle('fa-solid-fa-moon');
  toggleBtn.classList.toggle('fa-solid-fa-sun');

  if (toggleBtn.textContent === 'OFF') {
    toggleBtn.textContent = 'ON';
  } else {
    toggleBtn.textContent = 'OFF';
  }
});

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

Organize a method's for-loop using JavaScript modules

I have a function that looks like this: function createModifiedList(people){ const modifiedList = [] for (let i = 0; i < people.length; i++){ modifiedList.push({ name: person.firstName + " " + person.lastName, ...

Ways to protect my login details when making an ajax request?

The scenario I am dealing with is as follows: I have developed a website using Javascript where users are required to input a username and password. Subsequently, the site makes an ajax call to the Webserver. On the other end, I have a PHP-powered Webser ...

Vue.js and Firestore will only update variables that do not have empty string values

Modify the variables that are not empty strings const state = reactive({ birthNumber: '', phoneNumber: '', DoctorName: '', DoctorPhone: '', }) db.collection(state.user.uid).doc( ...

How to Submit a Form in jQuery with both File and Text inputs without Redirecting the Current Window

I am working on creating an application form that allows users to attach images. The form consists of a few input elements placed within a div rather than a traditional form element. I need the form to be submitted via AJAX without causing a page redirect, ...

How to Retrieve the Value of a Radio Button with JavaScript

Issue: Difficulty in retrieving the value of a radio button or text box input. Through trial and error, I managed to access the information within the div gender1. I struggled to extract the values of gender or age. Despite attempting methods like append ...

AngularJS modal directives trigger a reset of $scope variables

I am developing a custom AngularJS application that needs to handle and store all the checkbox selections made by the user in a simple array of IDs. The functionality includes displaying a modal when the open button is clicked, allowing the user to perform ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Struggling to successfully send php information back to a jQuery ajax request

It seems like I've searched for the answer to this particular question multiple times, but I just can't seem to make it work despite spending hours trying different solutions. Below is my ajax code: $.ajax({ type: 'POST', url: 's ...

Use jQuery to add a class when a specific element is clicked and then remove that class when another element

Currently, I am working on creating a photo frame designer. One of the features I am trying to implement is that when a pattern is clicked, it fills the text with that pattern. I have managed to do this using the .addClass function. However, I have run int ...

Wrap the text in Alphine using PHP

Currently, I am dealing with a situation where I have a string that needs to be wrapped using the Yii tag like Yii::t('app' , 'what_string'). The reason for this is because I require it to be translated per string on another page. Howev ...

Is there a way to switch the cursor to a pointer when hovering over a bar on a ChartJS bar graph?

Here's the chart I created: createChart = function (name, contributions, idArray) { globalIdArray = idArray; var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: "bar", data: { lab ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

What steps can I take to personalize Material UI within a React application?

As someone who is new to this UI framework and React, I have been tasked with developing an application that requires more design patterns. I specifically chose a framework that does not depend on jQuery code. However, I am facing challenges when it comes ...

Processing DataTables in an Asp.Net MVC 4 Environment

I'm currently working on a project that involves using DataTables with an ajax request. The code is functioning, but the execution time ranges from 8-12 seconds which is suboptimal. I need to find a way to optimize this code, particularly the String P ...

Tips for retaining spaces in a multiline string when setting a helm value using cdktf

Currently, I am utilizing CDKTF to facilitate the deployment of the datadog helm chart into a kubernetes cluster. My objective is to assign a specific value to confd, however, the issue arises when the spaces in my typescript multiline string do not mainta ...

Angular triggers a function upon completion of several API requests

I am currently working on an Angular service that involves making HTTP calls. Here is an overview of the code structure: this.checkAndSendNotifications = function() { UsersService.getArray(function(array) { var notifications = []; angu ...

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

I am feeling a bit unsure, how can I shield this code from SQL Injection?

After going through various resources, I'm a bit lost on how to actually implement them in my code. Can anyone provide some guidance? Once I get a hang of it in my code, I believe I'll be able to grasp it better! I came across this AJAX autocompl ...

Adding animation to a div that is being appended can be done by using JavaScript functions and

I am looking to incorporate animation into my title div. Below is the HTML code I have so far: <div class="particles" id="tittle"> <!-- Displaying title from Firestore using JavaScript --> </div> Here is the CSS cod ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...