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 :

<style>
body{
  background-color: cadetblue;
  font-family: monospace;
}
.title{
  color:#fff;
  font-weight: normal;
  text-align: center;
  font-size:30px;
}
.container{
   width: 500px;
   height: 400px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: -200px;
   margin-top: -200px;
}
.box{
  background-color: beige;
  padding:20px;
  box-shadow: 0 5px 15px rgb(100 100 100 / 100%);
}
.btn-block{
  display: inline-block;
  height:15px;
  width:fit-content;
  background: #0075ff;
  padding: 10px 20px;
    color: #fff;
}
.generate-btn{
  user-select: none;
  float: right;
  cursor: pointer;
  cursor: hand;
}
.generate-btn:hover {
  background-color: cadetblue;
}
.password{
  padding-bottom: 20px;
  border-bottom:1px solid #0075ff;
  color:#0075ff;
  font-size: 32px;
  text-align: center;
}
input[type=range] {
    height: 34px;
    cursor: pointer;
}
.info{
  text-align: center;
    margin-top: -5px;
    color:#0075ff;
    font-size:1.1em;
    font-weight: bold;
}

</style>
<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();">
      Regerate
    </div>
    <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>
    </div>
  </div>
</div>
<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;
  }
</script>

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.