Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Generate a Random Password using JavaScript?
Next article icon

Show And Hide Password Using JavaScript

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When creating login or registration forms, a common feature is the ability to show and hide passwords. This improves user experience by allowing users to verify their input before submitting the form.

What We're Going to Create

We will create a "Password Hide and Show" feature that will allow users to toggle the visibility of their password. It will include an input field for the password and a button or icon (like an eye) to show or hide the text. Using HTML for structure, CSS for styling, and JavaScript for functionality, clicking the button will toggle the input field’s type between "password" (hidden) and "text" (visible), enhancing user experience and security.

Project Preview

Recording2024-12-31130827-ezgifcom-video-to-gif-converter
Show and hide password using JavaScript

Show and Hide Password - HTML code

The "Show and Hide Password" feature allows users to toggle the visibility of their password input field with a button, enhancing usability and security in web forms.

HTML
<html>
<head></head>
<body>
    <div class="container">
        <label for="passes">Enter Password</label>
        <div class="input-container">
            <input id="passes" placeholder="Your password" type="password" />
            <span class="eye-icon" id="eye-icon"> 👁️ </span>
        </div>
    </div>
</body>
</html>

In this example

  • The div with class container organizes the label and input field for the password.
  • The label is linked to the password input field using the for attribute and prompts the user to enter a password.
  • The input field with type="password" accepts the user's password and shows placeholder text when empty.
  • The span with class eye-icon and an eye emoji (👁️) is intended to toggle the visibility of the password.

Show and Hide Password - CSS Styling

The CSS styling for the "Show and Hide Password" feature ensures a clean, user-friendly interface by styling the input field, button, and positioning the eye icon. It uses flexbox for alignment and adds padding, borders, and rounded corners for a polished look.

CSS
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f4f4f4;
}

.container {
    background-color: white;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    width: 300px;
    text-align: center;
}

.input-container {
    display: flex;
    align-items: center;
    position: relative;
}

input {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
    border: 2px solid #ccc;
    border-radius: 5px;
    font-size: 16px;
}

.eye-icon {
    position: absolute;
    right: 10px;
    cursor: pointer;
    font-size: 20px;
    color: #333;
}

label {
    font-size: 18px;
    margin-bottom: 10px;
    display: block;
}

In this example:

  • Container Styling: Adds a white background, rounded corners, padding, and shadow for modern look.
  • Input Field: Stretches to fit the container width, includes padding, a light gray border, and rounded corners for usability and style.
  • Eye Icon: Positioned on the right of the input field, with a pointer cursor and dark gray color for clear interactivity.
  • Label Styling: Features larger text, proper spacing, and a block layout for alignment and readability.
  • Input-Icon Layout: Uses flexbox for horizontal alignment and relative positioning for precise placement.

Show and Hide Password - JavaScript

The JavaScript functionality for the "Show and Hide Password" feature toggles the input field's type between "password" and "text" when the button is clicked, updating the button text accordingly. It ensures that the password visibility can be switched with each click, providing interactive user experience.

JavaScript
let input = document.getElementById("passes");
let btn = document.getElementById("btnss");
btn.addEventListener("click", function() {
    if (input.type === "password") {
        input.type = "text";
        btn.textContent = "Hide";
    }
    else {
        input.type = "password";
        btn.textContent = "Show";
    }
})

In this example

  • Variable Declarations: Selects the password input field (passes) and the button element (btnss) for manipulation and interactivity.
  • Event Listener: Adds a click event to the button that toggles password visibility.
  • Toggle Functionality: Checks the input field's type and toggles between "password" and "text", updating the button text to "Show" or "Hide" accordingly.
  • Button Text Change: Updates the button text to "Hide" when password is visible and "Show" when hidden.
  • Password Security: Keeps the password hidden by default and only reveals it when the button is clicked.

Complete code

HTML
<html>
<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 300px;
            text-align: center;
        }
        .input-container {
            display: flex;
            align-items: center;
            position: relative;
        }
        input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 2px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
        .eye-icon {
            position: absolute;
            right: 10px;
            cursor: pointer;
            font-size: 20px;
            color: #333;
        }
        label {
            font-size: 18px;
            margin-bottom: 10px;
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <label for="passes">
            Enter Password
        </label>
        <div class="input-container">
            <input id="passes" placeholder="Your password" type="password" />
            <span class="eye-icon" id="eye-icon"> 👁️ </span>
        </div>
    </div>
    <script>
        let input = document.getElementById('passes');
        let eyeIcon = document.getElementById('eye-icon');
        eyeIcon.addEventListener('click', function () {
            if (input.type === 'password') {
                input.type = 'text';
                eyeIcon.textContent = '🙉';
            } else {
                input.type = 'password';
                eyeIcon.textContent = '👁️';
            }
        })
    </script>
</body>
</html>

Next Article
How to Generate a Random Password using JavaScript?

G

Gaurang Bansal 2
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Projects

Similar Reads

    Validate a password using HTML and JavaScript
    Validating a password using HTML and JavaScript involves ensuring that user-entered passwords meet certain criteria, such as length, complexity, or character types (e.g., uppercase, lowercase, numbers, and symbols). This process enhances security by enforcing strong password requirements before form
    2 min read
    Show And Hide Password Using TypeScript
    Managing password visibility in web applications enhances user experience by allowing users to toggle between hidden and visible passwords. TypeScript provides strong type safety and better maintainability for implementing this feature.What We Are Going to CreateWe’ll build an application that allow
    4 min read
    How to Generate a Random Password using JavaScript?
    Creating a random password generator is an excellent beginner-friendly project that can be useful in real-world applications. Passwords are vital for securing accounts, and strong, randomized passwords enhance security significantly. How to Generate a Random Password using JavaScriptWhat We're Going
    5 min read
    How to Generate a Random Password using JavaScript?
    Creating a random password generator is an excellent beginner-friendly project that can be useful in real-world applications. Passwords are vital for securing accounts, and strong, randomized passwords enhance security significantly. How to Generate a Random Password using JavaScriptWhat We're Going
    5 min read
    How to Generate a Random Password using JavaScript?
    Creating a random password generator is an excellent beginner-friendly project that can be useful in real-world applications. Passwords are vital for securing accounts, and strong, randomized passwords enhance security significantly. How to Generate a Random Password using JavaScriptWhat We're Going
    5 min read
    How to validate confirm password using JavaScript ?
    In almost every modern website we have seen a login and signup feature, which is surely an important service for both the client and the service provider. When a user signs up for a certain website they have to put in a username a password, to enter the password websites ask them to enter a password
    3 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences