Simple random question Quiz app by jquery and ajax

avi gehlot
Nov 8 · 4 min read

Whats I used technology in quiz app that's javascript, ajax first I talk about why I choose because it's cool interactive web-application,

three-part here 1.HTML 2.CSS 3.Jquery

let’s start with HTML

HTML

  1. only some pieces of code I write in HTML
  2. first, I used jquery in my project so lets first I write cdn in HTML code here
<script src=”https://code.jquery.com/jquery-3.4.1.min.js" integrity=”sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=”crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script>

This is minified link you can find more details here

and you can put CDN file in the body tag like

<!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”><title>Document</title></head><body>
here cdn file put
</body></html>

and we create in HTML button, input because “when user input answer then submit and checked by server user answer right and wrong then if the wrong message generates the wrong answer and if the right then message generates right answer “

It's my front end view

Its my Front end view
Its my Front end view

snippets here for input and submit button

<div class=”container quiz”> // first div <h2 id=”randomquestion”></h2> // here is random question generate by api<input class=”form-control” type=”text” placeholder=”Answer”>
<div class=”buttonContainer”><button class=”submit btn btn-success”>Submit</button><button id=”skip” class=”submit btn btn-danger”>Skip</button></div><div class=”buttonContainer”></div><span></span><h3></h3><h4></h4></div>

all small parts are together and full HTML code is below

<!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”><title>Document</title><link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”><link rel=”stylesheet” href=”index.css”></head><body><div class=”container quiz”><h2 id=”randomquestion”></h2><input class=”form-control” type=”text” placeholder=”Answer”><div class=”buttonContainer”><button class=”submit btn btn-success”>Submit</button><button id=”skip” class=”submit btn btn-danger”>Skip</button></div><div class=”buttonContainer”></div><span></span><h3></h3><h4></h4></div><scriptsrc=”https://code.jquery.com/jquery-3.4.1.min.js"integrity=”sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=”crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script><script src=”./index.js”></script></body></html>

here is a first part is complete and I start the second part of this blog CSS

2.CSS code below

body {max-width: 1080px;margin: auto;}.quiz {border: 1px solid black;}h1, h2, h3, input, button {margin-top: 30px;font-family: Arial, Helvetica, sans-serif;;}@import “http://fonts.googleapis.com/css?family=Droid+Serif";/* Above line is used for online google font */h2 {text-align:center;font-size:24px}#skip{margin-left: 10px;}

CSS code to my web-app more beautiful

3. Jquery -In this part, I divided two separate part a)Ajax b)Jquery

a)ajax -lets first know about what is ajax? the main concern is Update a web page without reloading the page, only done by ajax

second is why I used ajax?

because when I talk about I generate questions from API then simple Ajax call to show questions on my page

let us start with jquery code

jQuery(document).ready(function(){}); //this is ready document 

how to generate a random number I used this and when quiz finished then points earn(score) by user

let randomnumber=Math.floor( Math.random() * 10 )
let points = 0; //scope var

b) ajax — let's start with ajax code below ajax syntax

$.ajax({method : ‘GET’,url:'some urls from another website'success:function{
}
error: function(error) {
console.log(error);
}

lets I start with success: function here I created newQuestion

success:function newQuestion(data){}

terminology explains data-

if you write console.log(data) check console https://api.jsonbin.io/b/5dc2a6f7ce068a7724676fa9

this URL put in ajax URL

let us fetch question from API —
put this line
$('#randomquestion').text(data[randomnumber].question);

make an event handler

$(‘.submit’).on(‘click’, function(){})

two var initialize userAns and correctAns

let userAns=$(“input”).val();let correctAns = data[randomnumber].answer

let us compare if userAns right than message show right and if wrong then message show wrong

if (userAns.toLowerCase() === correctAns.toLowerCase()){ //compare$(‘h3’).text(“Right answer”) // text right show$(‘input’).val(‘’) //after right answer then empty inputrandomnumber += 1 //random number +1$(‘#randomquestion’).text(data[randomnumber].question);}else{$(‘h3’).text(“Wrong Answer”); // else if wrong }

Most important thing timer logic here

var count = 30;var timer = setInterval(function() {$(‘h3’).text(count+ “ “+”seconds(S) left”)count — ;if(count == 0) {stopInterval()}}, 1000);var stopInterval = function() {$(‘h3’).text(“Time out”)// $(‘h3’).text(“Your Final Score is “ + points + “ points!”) // if you see final score then open this comment$(‘span’).hide()$(“.submit”).hide();clearInterval(timer);}

I explain you all code line

  1. Step — i used count = 30 and setInterval function create
  2. then count — to 30,29,28 this way show on my page
  3. how to show this way $(‘h3’).text(count+ “ “+”seconds(S) left”)
  4. if coun==0 then call function stopInterval and stopInterval say Time out
  5. and I used hide() to all components hide because after time out user not able to submit the answer

complete code

jQuery(document).ready(function(){let randomnumber=Math.floor( Math.random() * 10 )console.log(randomnumber)let points=0;$.ajax({method : ‘GET’,url:’ https://api.jsonbin.io/b/5dc2a6f7ce068a7724676fa9',success:function newQuestion(data){$(‘#randomquestion’).text(data[randomnumber].question);$(‘.submit’).on(‘click’, function(){console.log(data)let userAns=$(“input”).val();let correctAns = data[randomnumber].answerconsole.log(correctAns)if (userAns.toLowerCase() === correctAns.toLowerCase()){$(‘h3’).text(“Right answer”)$(‘input’).val(‘’)points += 1randomnumber += 1console.log(randomnumber)console.log(data[randomnumber].question)$(‘#randomquestion’).text(data[randomnumber].question);}else{$(‘h3’).text(“Wrong Answer”);}})}})var count = 30;var timer = setInterval(function() {$(‘h3’).text(count+ “ “+”seconds(S) left”)count — ;if(count == 0) {stopInterval()}}, 1000);var stopInterval = function() {$(‘h3’).text(“Time out”)// $(‘h3’).text(“Your Final Score is “ + points + “ points!”) // if you see final score then open this comment$(‘span’).hide()$(“.submit”).hide();clearInterval(timer);}})

so Hope you this article help you, I write first article on medium.com, next time I will better write to you

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade