Create a number facts app using JavaScript
Tags: javascript, webdev, beginners, tutorial
Published: 2021-12-05 13:04:08

Hello everyone, today we are going to create **Number Facts App**. It is a fun API project which gives you random facts about the numbers that a user input. For this project we'll be working with JS and AJAX/Fetch API concept to send and retrieve data from a server asynchronously without interfering with the display and behaviour of existing page. 

I've learnt these concepts by making this fun project.

API url that we are going to use in this project is [http://numbersapi.com/](http://numbersapi.com/) .

Our final project will look like this

{%youtube YvJYUY9qW_0 %}

##HTML

So, basically our interface is going to look like this

![Simple Interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ll1er064813061u2o6fj.png)

Now you are free to use Bootstrap classes to design it or you may start from scratch just like me.

```html
<div class="row">
            <div id="header">
                <h1>Number Facts</h1>
            </div>
            <div id="instruction">
                <p>Enter a number and get random facts</p>
            </div>
            <div id="box">
                <input type="number"  id="numberInput" placeholder="Enter any number....">
            </div>
            <div>
                <br>
            </div>            
            <div id="fact">
                <h4>
                    Number Fact
                </h4>
                <p id="factText"></p>
                <div>
                    <br>
                </div>
            </div>
        </div>
```

##CSS
Now it's time to design our web page. So, I basically do a little CSS that is enough for this project. And as always you're free to do experiments with this.

```css
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    background: #264653;
    display: grid;
    place-items: center;
}

.developer-name{
    margin-top: 30px;
    font-size: 30px;
    opacity: 0.3;
}

#fact{
    display: none;
}
h1{
    color: #5c0bb9;
    z-index: 1;
    font-family: 'Fredoka One', cursive;
    
}

.row{
    margin-top: 15%;
    background: #a8dadc;
    width: 50vw;
    height: max-content;
    border-radius: 5px;
    box-shadow: 0px 0px 10px 0px #a8dadc;
}
#header{
    display: grid;
    place-items: center;
}
#instruction{
    margin-left: 6%;
    font-weight: bolder;
}
#fact{
    margin-left: 3%;
    font-weight: bolder;
}
#box{
    display: grid;
    place-items: center;
    margin-top: 3%;
}
input[type=number]{
    background: transparent;
    width: 70%;
    height: 150%;
}
#fact{
    margin-top: 4%;
}
#factText{
    margin-top: 2%;
}
```
##JavaScript
The most important part of this project. So, first take a look at JS part and I'll be explaining in last.

```javascript
let fact = document.querySelector('#fact');
let factText = document.querySelector('#factText');

 let numberInput = document.querySelector('#numberInput');
```
Firstly we defined variables. Now, we have to add `addEventListener` to `numberInput` to get the `input` and run a `function` whenever user `input` a number

```javascript
numberInput.addEventListener('input',getFactFetch);
```
From this point we have 2 ways either we use Fetch API or use AJAX. I'll be providing code for both ways.

##Fetch API

```javascript
function getFactFetch(){
    let number = numberInput.value;

    fetch('http://numbersapi.com/'+number)
    .then(response => response.text())
    .then(data => {
        if (number !='') {
            fact.style.display = 'block';
            factText.innerHTML = data;
        }else {
            fact.style.display = 'none';
        }
        
    })
    .catch(err => console.log(err));
}
```
We defined the `getFactFetch()`. 
• First we get the value of `numberInput`.
• Then use fetch() and put the API url in parentheses.
• Then we check the condition if there is any number input run 
```javascript
            fact.style.display = 'block';
            factText.innerHTML = data;
```
• And if there is no number input this code will execute
```javascript
            fact.style.display = 'none';
```
• `.catch()` is used to show error if there is any.

##AJAX
First change the function `getFactFetch` to `getFActAjax`

```javascript
function getFactAjax(){
    let number = numberInput.value;
    let xhr = new XMLHttpRequest();
    xhr.open('GET','http://numbersapi.com/'+number);

    xhr.onload = function(){
        if (this.status == 200 && number != '') {
            fact.style.display = 'block';
            factText.innerHTML = this.responseText;
        }if(this.status == 200 && number == '') {
            fact.style.display = 'none';
        }
    }
    xhr.send();
}
```
_If you have any doubt or you don't know the AJAX and Fetch API concept I'll suggest you to check out this [video](https://youtu.be/tUE2Nic21BA) by Traversy Media_

And another important point:-
This will work perfectly on your local host but if you want to it to deploy and use a browser like Chrome or FireFox then this will not work due to [Mixed content](https://www.globalsign.com/en/blog/how-to-fix-mixed-content-warnings-on-your-ssl-site#:~:text=When%20a%20site%20doesn't,over%20SSL%20to%20the%20browser)