Generate Chuck Norris jokes asynchronously from external API of Internet Chuck Norris Database.
https://api.icndb.com/jokes/random/
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" /> <link rel="icon" href="#"> <title>Chuck Norris API</title> <style> .imgBx img{ border-radius: 50%; display: block; margin: auto; max-width: 200px; } button{ display: block; margin: 30px auto; } .text-center{ text-align: center; margin-top: 20px; } form input{ display: block; margin: auto; } form label{ text-align: center; } </style> </head> <body> <div class="container"> <div class="imgBx"> <img src="norris.jpg" alt="Chuck Norris"> </div> <div class="txtBx"> <h1 class="text-center">Chuck Norris API</h1> </div> <form> <div> <label for="number">Number of jokes</label> <input type="number" id="number"> </div> </form> <button id="button">Get Jokes</button> <ul class="jokes"></ul> </div> <script src="app.js"></script> </body> </html>
JavaScript
document.getElementById('button').addEventListener('click', getJokes); function getJokes(e) { const number = document.querySelector('input[type="number"]').value; const xhr = new XMLHttpRequest(); xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true); xhr.onload = function(){ if(this.status === 200){ const response = JSON.parse(this.responseText); let output = ''; if(response.type === 'success'){ response.value.forEach(function(joke){ output += ` <li>${joke.joke}</li> `; }); } else{ output += '<li>Something went wrong</li>'; } document.querySelector('ul.jokes').innerHTML = output; } } xhr.send(); e.preventDefault(); }
Leave a Reply