Random password generator with character length using JavaScript

In this article, 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 :

  background-color: cadetblue;
  font-family: monospace;
  font-weight: normal;
  text-align: center;
   width: 500px;
   height: 400px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: -200px;
   margin-top: -200px;
  background-color: beige;
  box-shadow: 0 5px 15px rgb(100 100 100 / 100%);
  display: inline-block;
  background: #0075ff;
  padding: 10px 20px;
    color: #fff;
  user-select: none;
  float: right;
  cursor: pointer;
  cursor: hand;
.generate-btn:hover {
  background-color: cadetblue;
  padding-bottom: 20px;
  border-bottom:1px solid #0075ff;
  font-size: 32px;
  text-align: center;
input[type=range] {
    height: 34px;
    cursor: pointer;
  text-align: center;
    margin-top: -5px;
    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-block generate-btn" onclick="generate();">
    <input onclick="generate();" type="range" value="9" 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 = '[email protected]!#$%^&*()';
      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 :


Recommended For You

About the Author: Ritesh Ghimire

Ritesh is a Computer Engineer, Web Developer and an active cricket follower.