Random password generator with character length using JavaScript


In this tutorial, we are going to learn to create a random password generator tool with an option to change the number of characters. We will be using JavaScript to create a random string to generate the password.

Full Source Code :

<style type="text/css">
    background-color: cadetblue;
    font-family: monospace;
    color: #fff;
    font-weight: normal;
    text-align: center;
    font-size: 30px;
    width: 500px;
    height: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background-color: beige;
    padding: 20px;
    box-shadow: 0 5px 15px rgb(100,100,100 / 100%);
    display: inline-block;
    height: 15px;
    width: fit-content;
    background-color: #0075ff;
    padding: 10px 20px;
    color: #fff;
    user-select: none;
    float: right;
    cursor: pointer;
    background-color: cadetblue;
    padding-bottom: 20px;
    border-bottom: 1px solid #0075ff;
    color: #0075ff;
    font-size: 32px;
    text-align: center;
    height: 35px;
    cursor: pointer;
    text-align: center;
    margin-top: -5px;
    color: #0075ff;
    font-size: 1.1em;
    font-weight: bold;

<div class="container">
  <h1 class="title">Password Generator</h1>
  <div class="box">
    <h1 class="password">thePassword</h1>
    <div class="btn-block char-length">9</div>
    <div class="btn btn-block generate-btn" onclick="generate();">Generate</div>
    <input type="range" value="9" onclick="generate();" id="input" min="5" max="20" style="width:100%;">
    <p class="info">Slide to set number of characters</p>

<script type="text/javascript">
  function generate(){
    char_length = document.getElementById('input').value;
    document.getElementsByClassName('char-length')[0].innerHTML = char_length;
    password = getPassword(char_length);
    document.getElementsByClassName('password')[0].innerHTML = password;

  function getPassword(length){
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';
    var random_string = '';
    if(length > 0){
      for(var i=0; i<length; i++){
        random_string += chars.charAt(Math.floor(Math.random() * chars.length));
    return random_string;


Follow this video for complete guidance :


ALSO READ  Access Camera and Read QR code using JavaScript

Comments are closed.