Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Random Password Generator
Abhi Develops - SunTech
Abhi Develops - SunTech

Posted on

     

Random Password Generator

Hi Everyone!
In this post I will be showing you how to make a Random Password Generator with HTML, CSS, and Javascript. Follow me if you want more projects. Enjoy!

Let's start with the user interface made in HTML:

<!DOCTYPE html><html><head><linkrel="stylesheet"href="style.css"><title>Random Password Generator</title></head><body><divclass="container"><h2class="title">Password Generator</h2><divclass="result"><divclass="result__title field-title">Generated Password</div><divclass="result__info right">click to copy</div><divclass="result__info left">copied</div><divclass="result__viewbox"id="result">CLICK GENERATE</div><buttonid="copy-btn"style="--x: 0; --y: 0"><iclass="far fa-copy"></i></button></div><divclass="length range__slider"data-min="4"data-max="32"><divclass="length__title field-title"data-length='0'>length:</div><inputid="slider"type="range"min="4"max="32"value="16"/></div><divclass="settings"><spanclass="settings__title field-title">settings</span><divclass="setting"><inputtype="checkbox"id="uppercase"checked/><labelfor="uppercase">Include Uppercase</label></div><divclass="setting"><inputtype="checkbox"id="lowercase"checked/><labelfor="lowercase">Include Lowercase</label></div><divclass="setting"><inputtype="checkbox"id="number"checked/><labelfor="number">Include Numbers</label></div><divclass="setting"><inputtype="checkbox"id="symbol"/><labelfor="symbol">Include Symbols</label></div></div><buttonclass="btn generate"id="generate">Generate Password</button></div><!-- linking javascript file --><scripthref="script.js"></script></body>
Enter fullscreen modeExit fullscreen mode

Next let's make it look better with CSS:

*{margin:0;padding:0;box-sizing:border-box;}body{width:100%;height:100vh;background-image:linear-gradient(totop,#209cff100%,#80ffdb200%);display:flex;justify-content:center;align-items:center;}button{border:0;outline:0;}.container{margin:40px0;width:400px;height:600px;padding:10px25px;background:#0a0e31;border-radius:10px;box-shadow:005pxrgba(0,0,0,0.45),04px8pxrgba(0,0,0,0.35),08px12pxrgba(0,0,0,0.15);font-family:"Montserrat";}.containerh2.title{font-size:1.75rem;margin:10px-5px;margin-bottom:30px;color:#fff;}.result{position:relative;width:100%;height:65px;overflow:hidden;}.result__info{position:absolute;bottom:4px;color:#fff;font-size:0.8rem;transition:all150msease-in-out;transform:translateY(200%);opacity:0;}.result__info.right{right:8px;}.result__info.left{left:8px;}.result__viewbox{width:100%;height:100%;background:rgba(255,255,255,0.08);border-radius:8px;color:#fff;text-align:center;line-height:65px;}.result#copy-btn{position:absolute;top:var(--y);left:var(--x);width:38px;height:38px;background:#fff;border-radius:50%;opacity:0;transform:translate(-50%,-50%)scale(0);transition:all350mscubic-bezier(0.175,0.885,0.32,1.275);cursor:pointer;z-index:2;}.result#copy-btn:active{box-shadow:000200pxrgba(255,255,255,0.08);}.result:hover#copy-btn{opacity:1;transform:translate(-50%,-50%)scale(1.35);}.field-title{position:absolute;top:-10px;left:8px;transform:translateY(-50%);font-weight:800;color:rgba(255,255,255,0.5);text-transform:uppercase;font-size:0.65rem;pointer-events:none;user-select:none;}.options{width:100%;height:auto;margin:50px0;}.range__slider{position:relative;width:100%;height:calc(65px-10px);display:flex;justify-content:center;align-items:center;background:rgba(255,255,255,0.08);border-radius:8px;margin:30px0;}.range__slider::before,.range__slider::after{position:absolute;color:#fff;font-size:0.9rem;font-weight:bold;}.range__slider::before{content:attr(data-min);left:10px;}.range__slider::after{content:attr(data-max);right:10px;}.range__slider.length__title::after{content:attr(data-length);position:absolute;right:-16px;font-variant-numeric:tabular-nums;color:#fff;}#slider{-webkit-appearance:none;width:calc(100%-(70px));height:2px;border-radius:5px;background:rgba(255,255,255,0.314);outline:none;padding:0;margin:0;cursor:pointer;}#slider::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border-radius:50%;background:white;cursor:pointer;transition:all0.15sease-in-out;}#slider::-webkit-slider-thumb:hover{background:#d4d4d4;transform:scale(1.2);}#slider::-moz-range-thumb{width:20px;height:20px;border:0;border-radius:50%;background:white;cursor:pointer;transition:background0.15sease-in-out;}#slider::-moz-range-thumb:hover{background:#d4d4d4;}.settings{position:relative;height:auto;widows:100%;display:flex;flex-direction:column;}.settings.setting{position:relative;width:100%;height:calc(65px-10px);background:rgba(255,255,255,0.08);border-radius:8px;display:flex;align-items:center;padding:10px25px;color:#fff;margin-bottom:8px;}.settings.settinginput{opacity:0;position:absolute;}.settings.settinginput+label{user-select:none;}.settings.settinginput+label::before,.settings.settinginput+label::after{content:"";position:absolute;transition:150mscubic-bezier(0.24,0,0.5,1);transform:translateY(-50%);top:50%;right:10px;cursor:pointer;}.settings.settinginput+label::before{height:30px;width:50px;border-radius:30px;background:rgba(214,214,214,0.434);}.settings.settinginput+label::after{height:24px;width:24px;border-radius:60px;right:32px;background:#fff;}.settings.settinginput:checked+label:before{background:#5d68e2;transition:all150mscubic-bezier(0,0,0,0.1);}.settings.settinginput:checked+label:after{right:14px;}.settings.settinginput:focus+label:before{box-shadow:0002pxrgba(255,255,255,0.75);}.settings.settinginput:disabled+label:before,.settings.settinginput:disabled+label:after{cursor:not-allowed;}.settings.settinginput:disabled+label:before{background:#4f4f6a;}.settings.settinginput:disabled+label:after{background:#909090;}.btn.generate{user-select:none;position:relative;width:100%;height:50px;margin:10px0;border-radius:8px;color:#fff;border:none;background-image:linear-gradient(135deg,#667eea0%,#764ba2100%);letter-spacing:1px;font-weight:bold;text-transform:uppercase;cursor:pointer;transition:all150msease;}.btn.generate:active{transform:translateY(-3%);box-shadow:04px8pxrgba(255,255,255,0.08);}@keyframesoctocat-wave{0%,100%{transform:rotate(0);}20%,60%{transform:rotate(-20deg);}40%,80%{transform:rotate(10deg);}}
Enter fullscreen modeExit fullscreen mode

Now let's make it functional using #"#0B1EDF",background:"rgba(255, 255, 255, 0.214)",};// Selecting the Range Slider container which will effect the LENGTH property of the password.constslider=document.querySelector(".range__slider");// Text which will show the value of the range slider.constsliderValue=document.querySelector(".length__title");// Using Event Listener to apply the fill and also change the value of the text.slider.querySelector("input").addEventListener("input",event=>{sliderValue.setAttribute("data-length",event.target.value);applyFill(event.target);});// Selecting the range input and passing it in the applyFill func.applyFill(slider.querySelector("input"));// This function is responsible to create the trailing color and setting the fill.functionapplyFill(slider){constpercentage=(100*(slider.value-slider.min))/(slider.max-slider.min);constbg=`linear-gradient(90deg,${sliderProps.fill}${percentage}%,${sliderProps.background}${percentage+0.1}%)`;slider.style.background=bg;sliderValue.setAttribute("data-length",slider.value);}// Object of all the function names that we will use to create random letters of passwordconstrandomFunc={lower:getRandomLower,upper:getRandomUpper,number:getRandomNumber,symbol:getRandomSymbol,};// Random more secure valuefunctionsecureMathRandom(){returnwindow.crypto.getRandomValues(newUint32Array(1))[0]/(Math.pow(2,32)-1);}// Generator Functions// All the functions that are responsible to return a random value taht we will use to create password.functiongetRandomLower(){returnString.fromCharCode(Math.floor(Math.random()*26)+97);}functiongetRandomUpper(){returnString.fromCharCode(Math.floor(Math.random()*26)+65);}functiongetRandomNumber(){returnString.fromCharCode(Math.floor(secureMathRandom()*10)+48);}functiongetRandomSymbol(){constsymbols='~!@#$%^&*()_+{}":?><;.,';returnsymbols[Math.floor(Math.random()*symbols.length)];}// Selecting all the DOM Elements that are necessary -->// The Viewbox where the result will be shownconstresultEl=document.getElementById("result");// The input slider, will use to change the length of the passwordconstlengthEl=document.getElementById("slider");// Checkboxes representing the options that is responsible to create differnt type of password based on userconstuppercaseEl=document.getElementById("uppercase");constlowercaseEl=document.getElementById("lowercase");constnumberEl=document.getElementById("number");constsymbolEl=document.getElementById("symbol");// Button to generate the passwordconstgenerateBtn=document.getElementById("generate");// Button to copy the textconstcopyBtn=document.getElementById("copy-btn");// Result viewbox containerconstresultContainer=document.querySelector(".result");// Text info showed after generate button is clickedconstcopyInfo=document.querySelector(".result__info.right");// Text appear after copy button is clickedconstcopiedInfo=document.querySelector(".result__info.left");// if this variable is trye only then the copyBtn will appear, i.e. when the user first click generate the copyBth will interact.letgeneratedPassword=false;// Update Css Props of the COPY button// Getting the bounds of the result viewbox containerletresultContainerBound={left:resultContainer.getBoundingClientRect().left,top:resultContainer.getBoundingClientRect().top,};// This will update the position of the copy button based on mouse PositionresultContainer.addEventListener("mousemove",e=>{resultContainerBound={left:resultContainer.getBoundingClientRect().left,top:resultContainer.getBoundingClientRect().top,};if(generatedPassword){copyBtn.style.opacity='1';copyBtn.style.pointerEvents='all';copyBtn.style.setProperty("--x",`${e.x-resultContainerBound.left}px`);copyBtn.style.setProperty("--y",`${e.y-resultContainerBound.top}px`);}else{copyBtn.style.opacity='0';copyBtn.style.pointerEvents='none';}});window.addEventListener("resize",e=>{resultContainerBound={left:resultContainer.getBoundingClientRect().left,top:resultContainer.getBoundingClientRect().top,};});// Copy Password in clipboardcopyBtn.addEventListener("click",()=>{consttextarea=document.createElement("textarea");constpassword=resultEl.innerText;if(!password||password=="CLICK GENERATE"){return;}textarea.value=password;document.body.appendChild(textarea);textarea.select();document.execCommand("copy");textarea.remove();copyInfo.style.transform="translateY(200%)";copyInfo.style.opacity="0";copiedInfo.style.transform="translateY(0%)";copiedInfo.style.opacity="0.75";});// When Generate is clicked Password id generated.generateBtn.addEventListener("click",()=>{constlength=+lengthEl.value;consthasLower=lowercaseEl.checked;consthasUpper=uppercaseEl.checked;consthasNumber=numberEl.checked;consthasSymbol=symbolEl.checked;generatedPassword=true;resultEl.innerText=generatePassword(length,hasLower,hasUpper,hasNumber,hasSymbol);copyInfo.style.transform="translateY(0%)";copyInfo.style.opacity="0.75";copiedInfo.style.transform="translateY(200%)";copiedInfo.style.opacity="0";});// Function responsible to generate password and then returning it.functiongeneratePassword(length,lower,upper,number,symbol){letgeneratedPassword="";consttypesCount=lower+upper+number+symbol;consttypesArr=[{lower},{upper},{number},{symbol}].filter(item=>Object.values(item)[0]);if(typesCount===0){return"";}for(leti=0;i<length;i++){typesArr.forEach(type=>{constfuncName=Object.keys(type)[0];generatedPassword+=randomFunc[funcName]();});}returngeneratedPassword.slice(0,length).split('').sort(()=>Math.random()-0.5).join('');}// function that handles the checkboxes state, so at least one needs to be selected. The last checkbox will be disabled.functiondisableOnlyCheckbox(){lettotalChecked=[uppercaseEl,lowercaseEl,numberEl,symbolEl].filter(el=>el.checked)totalChecked.forEach(el=>{if(totalChecked.length==1){el.disabled=true;}else{el.disabled=false;}})}[uppercaseEl,lowercaseEl,numberEl,symbolEl].forEach(el=>{el.addEventListener('click',()=>{disableOnlyCheckbox()})})

Enter fullscreen modeExit fullscreen mode

That's It! You have now successfully created a Random Password Generator.

Live Demo

Full Code

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
fjones profile image
FJones
  • Location
    Munich, Germany
  • Work
    Software Development Team Lead
  • Joined

While the shuffle at least prevents the password from following a clear order of character types, by iterating over the types you still enforce a balance of character types, which in turn reduces randomness. Other than that, this is really neat - especially explicitly using window.crypto!

CollapseExpand
 
rafavls profile image
Rafael
Full Stack Web Developer and Renewable Energies Engineer
  • Location
    San Diego, CA
  • Education
    Renewable Energies Engineer
  • Joined

Nice!
I like the UI a lot 👌🏽

CollapseExpand
 
abhidevelopssuntech profile image
Abhi Develops - SunTech
Hi, I am Abhinav Gupta. I am a self-taught web developer and I know mainly HTML, CSS, some Javascript and Python.
  • Email
  • Education
    Riverbank Public School Australia
  • Work
    I am the Founder of SunTech where people can hire me to create an awesome looking website for them.
  • Joined

Thank You!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Abhi Develops - SunTech
Hi, I am Abhinav Gupta. I am a self-taught web developer and I know mainly HTML, CSS, some Javascript and Python.
  • Education
    Riverbank Public School Australia
  • Work
    I am the Founder of SunTech where people can hire me to create an awesome looking website for them.
  • Joined

More fromAbhi Develops - SunTech

Infinite Loops in Javascript
#loops#infiniteloops#javascript#abhidevelopssuntech
How to make a Memory Matching Card Game with Javascript
#html#css#javascript#memorymatchgame
How to make a movie app in Vanilla Javascript
#html#css#vanillajs#movieapp
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp