Create your own decision maker in JavaScript

we will create our own random decision maker using vanilla JavaScript. We use pure JavaScript without external libraries. With complete source code.
Decision maker, code armor, html source code, javascript source code

How to create a Decision maker using vanilla JavaScript

We saw different types of decision maker on the internet. Most websites provide this tool for free. But they also include a lot of ads on the page. But in this article, we will create our own random decision maker using vanilla JavaScript. To improve user experience, its usage is also provided. We use pure javascript for our project without using external libraries. I also provide the complete source code of this project for you.

You will learn some core topics by making this project such as forEach function, setInterval, setTimeout, clearInterval, function callback, etc

First of all, we have to understand it.


What is a decision maker?

The decision maker tool helps you to pick a choice from the selection list of items you provided. Sometimes we have multiple things with the same value. To chose one out of them becomes a difficult task. In this situation decision maker helps us to pick a choice. For fun, we can also use this tool to play games.

Now let’s set up our project.

Set up project

To get systematic results we should set up our project. Follow the given instructions to set up the project:-
  • Create a folder named “Decision maker”.
  • Create an HTML file and a CSS file and a JavaScript file.
  • Connect both CSS and JavaScript files to HTML files.
We successfully set up our project its time to create our project.
So, let’s start.

Adding HTML to the project

Now let’s create an HTML file for our project. Just copy the source code given below and paste it into your “index.html” file.

HTML Source Code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Decision Maker</title>
  <!-- HTML -->
  <!-- Custom Styles -->
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <h2>Random Decision Maker</h2>
    <div class="tabContainer">
      <textarea id=textarea placeholder="i.e, red,blue,green,yellow..."></textarea>
      <div id="btn">Generate</div>
    </div>
    <div id="choiceContainer">
      <!-- <div class="tags">One</div> -->
    </div>
    <div class="description">
      <h3>What is Random Choice Generator ?</h3>
      <p>Random Choice GeneratorGe is use to make a quick decision for you by picking a choice from the selection list of item you provide. It's a quick and easy decision maker.</p>
      <h3>How to use it?</h3>
      <p>Enter the list of choices that you to prefer and separate every choice with commas ","and click the button below to display a random picked selection.</p>
    </div>
  </div>
  
  <!-- Project -->
  <script src="main.js"></script>
</body>

</html>

Understanding HTML Source code

Here a container is created which contains a heading, a tab container, a choice container, and a description. The tab container contains a text area to enter choices. The choice container will show all the choices you entered. And the description container contains all the information about the random decision maker.

Hurray! We completed our HTML section successfully. Now let’s move on style section.

Adding styles to the project


A good-looking project attracts an audience. So it is important to style the project. Here we give some basic style properties to our project.

Copy the CSS source code given below and paste it into your CSS file.

CSS Source Code

:root {
  --themeColor: #6c5ce7;
  --txtColor: #251E44;
  --bg: #fff;
  --fontsize: 13px;
}

body {
  margin: 0 auto;
  padding: 0;
  box-sizing: border-box;
  width: 100vw;
  max-width: 1028px;
  height: 100vh;
  font-family: sans-serif;
  background: var(--themeColor);
  display: flex;
  justify-content: center;
  overflow-x: hidden;
}

.container {
  box-sizing: border-box;
  width: 100%;
  height: auto;
  color: var(--txtColor);
  font-size: 1rem;
}

h2 {
  box-sizing: border-box;
  margin: 0;
  padding: 1em;
  text-align: center;
  color: ghostwhite;
  font-size: 1.5em;
}

.tabContainer {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: auto;
}

#textarea {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  min-width: 90%;
  min-height: 15rem;
  box-sizing: border-box;
  padding: 2%;
  background: ghostwhite;
  border: 0;
  color: var(--txtColor);
  border-radius: 5px;
  box-shadow: 0px 10px 20px #2959FF29;
  overflow: hidden;
  outline: none;
  resize: none;
}

#choiceContainer {
  width: 90%;
  min-height: 10em;
  box-sizing: border-box;
  padding: 2%;
  margin: 0 auto;
  background: transparent;
  border-radius: 5px;
  outline: none;
  display: flex;
  align-content: center;
  justify-content: center;
  flex-wrap: wrap;
}

#btn {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  display: grid;
  place-items: center;
  width: 10em;
  height: 2.5em;
  margin: 5% 0;
  border-radius: 5px;
  background: linear-gradient(135deg, #5c7cfa, #91a7ff);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  color: #fff;
  font-weight: bold;
  text-transform: uppercase;
  letter-spacing: 2px;
}

.tags {
  display: grid;
  place-items: center;
  color: #fff;
  font-weight: bold;
  font-size: var(--fontsize);
  letter-spacing: 2px;
  border-radius: 50px;
  background: #ff7675;
  width: auto;
  height: 2em;
  margin: 1%;
  padding: 0.5em 1em;
}

.select {
  background: #d63031;
}

.description {
  width: 80%;
  color: ghostwhite;
  padding-bottom: 2em;
  margin:0 auto ;
 
}
.description h3{
  font-size: 1.1rem;
}


@media (min-width:600px){
  .description h3{
    font-size: 1.5rem;
  }
}

@media (min-width:768px){
#textarea{
  font-size: 1.05rem;
}
.description h3{
  font-size: 2rem;
}

}

Understanding CSS Source Code

It is not hard to understand the CSS properties. Here we call HTML elements by their names and classes and give some basic style properties. Media query makes it responsive. “:root” pseudo-class matches the root element of the document.

Our project gains a good look but it is static. To make it dynamic we have to add logic to it.

Adding logic to the project

It is important to add JavaScript to our project. We will add pure javascript to it. Just copy the given code and paste it into your javascript file.

JavaScript source code

let textarea = document.getElementById('textarea')
let choiceContainer = document.getElementById('choiceContainer')
let tagElement = document.querySelectorAll('.tags')
let btn = document.getElementById('btn')
let int = 100

textarea.addEventListener('keyup', (e) => {
  // console.log(e.target.value);
  createTags(e.target.value)
})


btn.addEventListener('click', () => {
  tagElement.forEach((tag) => {
    tag.classList.remove('select')
  })
  pickRandom()
})

function pickRandom() {

  //Create Animation
  if (choiceContainer.childElementCount > 1) {
    let animateTags = setInterval(selectTag, int)
    setTimeout(() => {
      clearInterval(animateTags)
      let random = Math.floor(Math.random() * choiceContainer.childElementCount)
      choiceContainer.children[random].classList.add('select')

    }, 3000)
  } else {
    alert('Please Enter Your Choices!')
  }

}

function selectTag(arg) {
  //console.log('it works');


  let random = Math.floor(Math.random() * choiceContainer.childElementCount)
  choiceContainer.children[random].classList.add('select')

  setTimeout(() => {
    choiceContainer.children[random].classList.remove('select')

  }, int)


  // alert(random)
}

function createTags(input) {
  let tags = input.split(",").filter((tag) => { return tag.trim() !== "" }).map((tag) => { return tag.trim() })
  // console.log(tags);

  choiceContainer.innerHTML = ''

  tags.forEach((tag) => {
    let div = document.createElement('DIV')
    div.setAttribute('class', 'tags')
    div.innerText = tag
    choiceContainer.appendChild(div)
  })

}

Understanding JavaScript Source code

Here we call some elements and store them in the variables. First, we add a “keyup” event listener to the text area, which calls the ”createTag” function when the user presses any key. createTag function accepts the key value as an argument. And separates them into white space. It also trims extra white space of strings. It converts every word into tags.

An event listener was also added to the “generate” button. This event listener calls the “pickRandom” function. This function matches a condition if tags are more than one then it will continue to the next step. After satisfying the condition, a “setIntervel” calls a function named “selectTag”. This function is coded to add animation to tags. After 100 milliseconds, it stops the animation and chose a random tag with the help of a “random” method.


This is how our code works.


Finally, we completed our project.

Conclusion

This is a good project for beginners. If you want to improve your javascript skills, definitely it helps you a lot. You can also add this project to your portfolio. Try to code it yourself to improve your skills. You can also modify this decision maker according to your needs. I am sure you learned something new from the article. If I done any mistake please tell me in the comment. Your comment helps us to improve our content.

Also, share this with your friends. 


Thank you!

About the Author

Code Armor makes Full Stack Development easy. We provide code projects with live examples and source code. We help you to increase your coding skills and problem-solving skills. We provide you with code projects in technologies like HTML, CSS, JavaS…

إرسال تعليق

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.