Issue: The icon does not change when toggling between showing and hiding the password input (HTML, CSS, JS)

After following a tutorial on building a basic login form, I decided to enhance it by incorporating a show/hide password feature using JavaScript. Unfortunately, despite the tutorial working flawlessly, I encountered issues when implementing it myself. I attempted solutions from a related article here but none seemed to solve the problem.

HTML:

<!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTG-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Website Login & Registration | Nick</title>
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="https:stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <script src="https://kit.fontawesome.com/0938e96d29.js" crossorigin="anonymous"></script>

            <div class="form-box login">
                <h2>Login</h2>
                <!--Allows the use of a form box-->
                <form action="#">
                    <div class="input-box">
                        <i class="fa-regular fa-envelope"></i>
                        <input type="email" required>
                        <label>Email</label>
                    </div>
                    <div class="input-box">
                            <span class="icon-eye-outline" id="icon-eye-outline"><ion-icon name="eye-outline"></ion-icon></span>
                        <input type="password" required id="password">
                        <label>Password</label>
                        <i class="fa fa-eye" id="show-password"></i>
                    </div>>
                    <div class="remember-forgot">
                        <label><input type="checkbox"> Remember me</label>
                        <a href="#">Forgot Password?</a>
                    </div>>
                    <button type="submit" class="btn">Login</button>
                    <div class="login-register">
                            <p>Don't have an account? 
                                <a href="#" class="register-link">Register</a>
                            </p>
                    </div>

                </form>
            </div>
    

Answer №1

The showPassword element is receiving the fa-eye-slash class in addition to the existing fa-eye class. However, there seems to be no visible change as the fa-eye class appears to have higher precedence over fa-eye-slash in FontAwesome's rendering.

So, what can be done in this situation? We can toggle between both classes using a clever solution found in this answer!

  showPassword.addEventListener("click", function() {
    ["fa-eye", "fa-eye-slash"].map(v=> showPassword.classList.toggle(v) )
    const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
    passwordField.setAttribute("type", type);
  })

This code snippet will iterate through each item in the array and toggle the class accordingly. This approach ensures that when fa-eye is removed, fa-eye-slash will be added instead.

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 is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Halt the execution of code once the user unselects the div

Is there a way to prevent the setInterval function from running when the user unselects the div they originally selected? I've tried using clearInterval but it's not working. Also, utilizing the cvalue from this doesn't seem to update within ...

What are some superior methods for determining the validity of a control in JavaScript?

Is there a way to determine the validity of a control in JavaScript within Asp.Net using a client-side API? Specifically, I am looking for a function that can check if a control is valid based on attached validators. For example, if a textbox has 2 validat ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

Is there a way to substitute the final character in the specific regex I've selected?

I have a specific string that I need to modify from {Rotation:[45f,90f],lvl:10s} to {Rotation:[45,90],lvl:10}. Here is the code I tried: const bar = `{Rotation:[45f,90f],lvl:10s}` const regex = /(\d)\w+/g console.log(bar.replace(regex, '$&a ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

Encountering the message "a critical error occurred: 'vips/vips8' file was not located" while using M2 (Apple Silicon) Macs

Encountered a pesky error that read: fatal error: 'vips/vips8' file not found while setting up a React project on my new M2 (Apple Silicon) device. After sifting through multiple reported issues on StackOverflow and github, I pinpointed the culp ...

Is there a solution for the noticeable delay in loading fonts on a web page?

I've encountered an issue in my React project where a Google font I'm using seems to briefly load as a different font before switching to the correct one. How can I prevent this from happening? This is how I'm loading the font in public/ind ...

How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve. I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it. const products = ["premium t-shirt", "t-shirt", "swea ...

Only output to the console if the data returned from an AJAX request has been

Here is a script that I created: <script type="text/javascript> $('.storage').html(""); setInterval(function(){ $.get('./playcommand.php', function(data) { if($('.storage').html() !== data){ ...

AngularJS control for KendoUI Switch functionality

I have been attempting to integrate Kendo UI's switch control with AngularJS but I am encountering an issue where the value is not properly binding to the model. This is how I am implementing it: <input type="checkbox" id="locked" kendo-mobile-swi ...

When I try to open my modal in Electron by clicking on the button, it doesn't work

I was expecting the modal to open by clicking on the Edit button within #app, but it doesn't open at all! I am unsure if there is an issue with my JavaScript logic or my HTML code! When attempting to use a function for the Modal, it still does not wo ...

The webpack "externals" option is reporting an error due to an unexpected character "@" being used

I've come across several discussions regarding the issue of "Unexpected character '@' in webpack, but none of them address the specific problem I'm facing with the externals option. I've used this feature in the past without any is ...

There should be a delay in the code following the ajax (code) block

Initially, my question was lengthy and accompanied by the complete code. However, it has now been condensed. function displayRecords(table) { myTable.fnDestroy(); $.ajax( { data: "tableName=" + table, url: "showTable.php", ...

The file that was sent via HTTP was not fully completed

Attempting to transfer a binary file over HTTP using NodeJS and Express has presented some challenges with a file size of around 1.8 MB. The approach of reading the file with fs.readFile(..) and sending it using res.sendFile(..) through curl command succe ...

Preventing Canvas Image Disappearance with JavaScript's onload Event

My current issue involves adding an Image to my webpage. However, every time I hit the refresh button, the image disappears. After researching on Stack Overflow, it was suggested to include window.onload=yourDrawFunction() in the code. Despite following th ...

When I imported my CSS file, it led to my jQuery becoming undefined, triggering a ReferenceError

Recently, I decided to delve into the world of webpack and embarked on a small project to better understand its functionality. Following this tutorial has been really helpful. In this project, I successfully bundled a .js file using webpack and incorporat ...

Activate a function when clicking on a Bootstrap toggle switch (checkbox)

Is it possible to have the function updateText() executed when I click on the checkbox with the id text_mode? I attempted using onClick="updateText()", but it didn't yield the desired outcome. While searching for solutions, I noticed that many respons ...

How to extract a substring from a string in Javascript

I am currently facing an issue with extracting a specific part of a string (from the URL pathname) and I need some help to solve it. Here is what I have tried so far: ^(/svc_2/pub/(.*?).php) The string in question is: /svc_2/pub/stats/dashboard.php?aja ...