Modifying and Show Ques. Randomly in the Quiz with navigation - javascript

I'm working on this quiz.
This is the Demo: https://jsfiddle.net/rpscadda/vwpctcjg/
var quiztitle = "Social Security Quiz";
var quiz = [
{
"question" : "Q1: Who came up with the theory of relativity?",
"image" : "http://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/220px-Albert_Einstein_Head.jpg",
"choices" : [
"Sir Isaac Newton",
"Nicolaus Copernicus",
"Albert Einstein",
"Ralph Waldo Emmerson"
],
"correct" : "Albert Einstein",
"explanation" : "Albert Einstein drafted the special theory of relativity in 1905.",
},
{
"question" : "Q2: Who is on the two dollar bill?",
"image" : "http://upload.wikimedia.org/wikipedia/commons/thumb/9/94/US_%242_obverse-high.jpg/320px-US_%242_obverse-high.jpg",
"choices" : [
"Thomas Jefferson",
"Dwight D. Eisenhower",
"Benjamin Franklin",
"Abraham Lincoln"
],
"correct" : "Thomas Jefferson",
"explanation" : "The two dollar bill is seldom seen in circulation. As a result, some businesses are confused when presented with the note.",
},
{
"question" : "Q3: What event began on April 12, 1861?",
"image" : "",
"choices" : [
"First manned flight",
"California became a state",
"American Civil War began",
"Declaration of Independence"
],
"correct" : "American Civil War began",
"explanation" : "South Carolina came under attack when Confederate soldiers attacked Fort Sumter. The war lasted until April 9th 1865.",
},
];
var currentquestion = 0,
score = 0,
submt = true,
picked;
jQuery(document).ready(function ($) {
function htmlEncode(value) {
return $(document.createElement('div')).text(value).html();
}
function addChoices(choices) {
if (typeof choices !== "undefined" && $.type(choices) == "array") {
$('#choice-block').empty();
for (var i = 0; i < choices.length; i++) {
$(document.createElement('li')).addClass('choice choice-box').attr('data-index', i).text(choices[i]).appendTo('#choice-block');
}
}
}
function nextQuestion() {
submt = true;
$('#explanation').empty();
$('#question').text(quiz[currentquestion]['question']);
$('#pager').text('Question ' + Number(currentquestion + 1) + ' of ' + quiz.length);
if (quiz[currentquestion].hasOwnProperty('image') && quiz[currentquestion]['image'] != "") {
if ($('#question-image').length == 0) {
$(document.createElement('img')).addClass('question-image').attr('id', 'question-image').attr('src', quiz[currentquestion]['image']).attr('alt', htmlEncode(quiz[currentquestion]['question'])).insertAfter('#question');
} else {
$('#question-image').attr('src', quiz[currentquestion]['image']).attr('alt', htmlEncode(quiz[currentquestion]['question']));
}
} else {
$('#question-image').remove();
}
addChoices(quiz[currentquestion]['choices']);
setupButtons();
}
function processQuestion(choice) {
if (quiz[currentquestion]['choices'][choice] == quiz[currentquestion]['correct']) {
$('.choice').eq(choice).css({
'background-color': '#50D943'
});
$('#explanation').html('<strong>Correct!</strong> ' + htmlEncode(quiz[currentquestion]['explanation']));
score++;
} else {
$('.choice').eq(choice).css({
'background-color': '#D92623'
});
$('#explanation').html('<strong>Incorrect.</strong> ' + htmlEncode(quiz[currentquestion]['explanation']));
}
currentquestion++;
$('#submitbutton').html('NEXT QUESTION »').on('click', function () {
if (currentquestion == quiz.length) {
endQuiz();
} else {
$(this).text('Check Answer').css({
'color': '#222'
}).off('click');
nextQuestion();
}
})
}
function setupButtons() {
$('.choice').on('mouseover', function () {
$(this).css({
'background-color': '#e1e1e1'
});
});
$('.choice').on('mouseout', function () {
$(this).css({
'background-color': '#fff'
});
})
$('.choice').on('click', function () {
picked = $(this).attr('data-index');
$('.choice').removeAttr('style').off('mouseout mouseover');
$(this).css({
'border-color': '#222',
'font-weight': 700,
'background-color': '#c1c1c1'
});
if (submt) {
submt = false;
$('#submitbutton').css({
'color': '#000'
}).on('click', function () {
$('.choice').off('click');
$(this).off('click');
processQuestion(picked);
});
}
})
}
function endQuiz() {
$('#explanation').empty();
$('#question').empty();
$('#choice-block').empty();
$('#submitbutton').remove();
$('#question').text("You got " + score + " out of " + quiz.length + " correct.");
$(document.createElement('h2')).css({
'text-align': 'center',
'font-size': '4em'
}).text(Math.round(score / quiz.length * 100) + '%').insertAfter('#question');
}
function init() {
//add title
if (typeof quiztitle !== "undefined" && $.type(quiztitle) === "string") {
$(document.createElement('h1')).text(quiztitle).appendTo('#frame');
} else {
$(document.createElement('h1')).text("Quiz").appendTo('#frame');
}
//add pager and questions
if (typeof quiz !== "undefined" && $.type(quiz) === "array") {
//add pager
$(document.createElement('p')).addClass('pager').attr('id', 'pager').text('Question 1 of ' + quiz.length).appendTo('#frame');
//add first question
$(document.createElement('h2')).addClass('question').attr('id', 'question').text(quiz[0]['question']).appendTo('#frame');
//add image if present
if (quiz[0].hasOwnProperty('image') && quiz[0]['image'] != "") {
$(document.createElement('img')).addClass('question-image').attr('id', 'question-image').attr('src', quiz[0]['image']).attr('alt', htmlEncode(quiz[0]['question'])).appendTo('#frame');
}
$(document.createElement('p')).addClass('explanation').attr('id', 'explanation').html(' ').appendTo('#frame');
//questions holder
$(document.createElement('ul')).attr('id', 'choice-block').appendTo('#frame');
//add choices
addChoices(quiz[0]['choices']);
//add submit button
$(document.createElement('div')).addClass('choice-box').attr('id', 'submitbutton').text('Check Answer').css({
'font-weight': 700,
'color': '#222',
'padding': '30px 0'
}).appendTo('#frame');
setupButtons();
}
}
init();
});
<style type="text/css" media="all">
/*css reset */
html, body, div, span, h1, h2, h3, h4, h5, h6, p, code, small, strike, strong, sub, sup, b, u, i {
border:0;
font-size:100%;
font:inherit;
vertical-align:baseline;
margin:0;
padding:0;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display:block;
}
body {
line-height:1;
font:normal 0.9em/1em"Helvetica Neue", Helvetica, Arial, sans-serif;
}
ol, ul {
list-style:none;
}
strong {
font-weight:700;
}
#frame {
max-width:620px;
width:auto;
border:1px solid #ccc;
background:#fff;
padding:10px;
margin:3px;
}
h1 {
font:normal bold 2em/1.8em"Helvetica Neue", Helvetica, Arial, sans-serif;
text-align:left;
border-bottom:1px solid #999;
padding:0;
width:auto
}
h2 {
font:italic bold 1.3em/1.2em"Helvetica Neue", Helvetica, Arial, sans-serif;
padding:0;
text-align:center;
margin:20px 0;
}
p.pager {
margin:5px 0 5px;
font:bold 1em/1em"Helvetica Neue", Helvetica, Arial, sans-serif;
color:#999;
}
img.question-image {
display:block;
max-width:250px;
margin:10px auto;
border:1px solid #ccc;
width:100%;
height:auto;
}
#choice-block {
display:block;
list-style:none;
margin:0;
padding:0;
}
#submitbutton {
background:#5a6b8c;
}
#submitbutton:hover {
background:#7b8da6;
}
#explanation {
margin:0 auto;
padding:20px;
width:75%;
}
.choice-box {
display:block;
text-align:center;
margin:8px auto;
padding:10px 0;
border:1px solid #666;
cursor:pointer;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id = "frame"
role = "content" >
And This is the Java
I want to make some modification, please help! Here is the list of modification.
when I click on "Check Answer" button then if my answer is wrong
then both correct and incorrect answer will showing and the
explanation should comes with a popup with close button or delay
with 1500ms.
Suppose I have 20 question in the quiz and I want to goto question
No. 10 then I need a navigation menu which help me to go on specific
question like question no.10.
How to show all Question and option Randomly.

Related

Fitting mapbox divs inside div with navbar in django html template

I am following this mapbox example (https://www.mapbox.com/help/building-a-store-locator/) and trying to fit it inside a Django web app. I believe my problem is in base.html because in the Mapbox tutorial they do not have a navbar or use template inheritance. base.html may be causing problems because it uses content from Home.html. In my screen shot you can see that the map and sidebar div do not fill the content-section div height wise. The map also only takes up half of the div it is inside of. I have tried many times to figure out the problem but cannot get it.
base.html
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!-- Bootstrap CSS, and other meta html -->
</head>
<body>
<header class="site-header">
<!-- header for website containing navbar config -->
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md" align="center">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
</div>
</main>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
Home.html
{% extends "geotracker/base.html" %}
{% load static %}
{% block content %}
<body>
<div class="content-section">
<div class='sidebar'>
<div class='heading'>
<h1>Our locations</h1>
</div>
<div id='listings' class='listings'></div>
</div>
<div id='map' class='map'> </div>
</div>
<script>
// This will let you use the .remove() function later on
if (!('remove' in Element.prototype)) {
Element.prototype.remove = function() {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
};
}
mapboxgl.accessToken = 'myTokenHere';
// This adds the map
var map = new mapboxgl.Map({
// container id specified in the HTML
container: 'map',
// style URL
style: 'mapbox://styles/mapbox/light-v9',
// initial position in [long, lat] format
center: [-77.034084142948, 38.909671288923],
// initial zoom
zoom: 13,
scrollZoom: false
});
var stores = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.043959498405,
38.903883387232
]
},
"properties": {
"phoneFormatted": "(202) 331-3355",
"phone": "2023313355",
"address": "1901 L St. NW",
"city": "Washington DC",
"country": "United States",
"crossStreet": "at 19th St",
"postalCode": "20036",
"state": "D.C."
}
}]
};
// This adds the data to the map
map.on('load', function (e) {
// Add the data to your map as a layer
map.addLayer({
"id": "locations",
"type": "symbol",
// Add a GeoJSON source containing place coordinates and information.
"source": {
"type": "geojson",
"data": stores
},
"layout": {
"icon-image": "restaurant-15",
"icon-allow-overlap": true,
}
});
});
// This is where your interactions with the symbol layer used to be
// Now you have interactions with DOM markers instead
stores.features.forEach(function(marker, i) {
// Create an img element for the marker
var el = document.createElement('div');
el.id = "marker-" + i;
el.className = 'marker';
// Add markers to the map at all points
new mapboxgl.Marker(el, {offset: [0, -23]})
.setLngLat(marker.geometry.coordinates)
.addTo(map);
el.addEventListener('click', function(e){
// 1. Fly to the point
flyToStore(marker);
// 2. Close all other popups and display popup for clicked store
createPopUp(marker);
// 3. Highlight listing in sidebar (and remove highlight for all other listings)
var activeItem = document.getElementsByClassName('active');
e.stopPropagation();
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
var listing = document.getElementById('listing-' + i);
listing.classList.add('active');
});
});
function flyToStore(currentFeature) {
map.flyTo({
center: currentFeature.geometry.coordinates,
zoom: 15
});
}
function createPopUp(currentFeature) {
var popUps = document.getElementsByClassName('mapboxgl-popup');
if (popUps[0]) popUps[0].remove();
var popup = new mapboxgl.Popup({closeOnClick: false})
.setLngLat(currentFeature.geometry.coordinates)
.setHTML('<h3>Sweetgreen</h3>' +
'<h4>' + currentFeature.properties.address + '</h4>')
.addTo(map);
}
function buildLocationList(data) {
for (i = 0; i < data.features.length; i++) {
var currentFeature = data.features[i];
var prop = currentFeature.properties;
var listings = document.getElementById('listings');
var listing = listings.appendChild(document.createElement('div'));
listing.className = 'item';
listing.id = "listing-" + i;
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.dataPosition = i;
link.innerHTML = prop.address;
var details = listing.appendChild(document.createElement('div'));
details.innerHTML = prop.city;
if (prop.phone) {
details.innerHTML += ' · ' + prop.phoneFormatted;
}
link.addEventListener('click', function(e){
// Update the currentFeature to the store associated with the clicked link
var clickedListing = data.features[this.dataPosition];
// 1. Fly to the point
flyToStore(clickedListing);
// 2. Close all other popups and display popup for clicked store
createPopUp(clickedListing);
// 3. Highlight listing in sidebar (and remove highlight for all other listings)
var activeItem = document.getElementsByClassName('active');
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
this.parentNode.classList.add('active');
});
}
}
</script>
<style>
body {
color:#404040;
-webkit-font-smoothing:antialiased;
}
* {
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
}
.sidebar {
position:absolute;
width:33.3333%;
height:100%;
top:0;left:0;
overflow:hidden;
border-right:1px solid rgba(0,0,0,0.25);
}
.pad2 {
padding:20px;
}
.map {
position:absolute;
left:33.3333%;
width:66.6666%;
top:0;bottom:0;
}
h1 {
font-size:22px;
margin:0;
font-weight:400;
line-height: 20px;
padding: 20px 2px;
}
a {
color:#404040;
text-decoration:none;
}
a:hover {
color:#101010;
}
.heading {
background:#fff;
border-bottom:1px solid #eee;
min-height:60px;
line-height:60px;
padding:0 10px;
background-color: #00853e;
color: #fff;
}
.listings {
height:100%;
overflow:auto;
padding-bottom:60px;
}
.listings .item {
display:block;
border-bottom:1px solid #eee;
padding:10px;
text-decoration:none;
}
.listings .item:last-child { border-bottom:none; }
.listings .item .title {
display:block;
color:#00853e;
font-weight:700;
}
.listings .item .title small { font-weight:400; }
.listings .item.active .title,
.listings .item .title:hover { color:#8cc63f; }
.listings .item.active {
background-color:#f8f8f8;
}
::-webkit-scrollbar {
width:3px;
height:3px;
border-left:0;
background:rgba(0,0,0,0.1);
}
::-webkit-scrollbar-track {
background:none;
}
::-webkit-scrollbar-thumb {
background:#00853e;
border-radius:0;
}
.marker {
border: none;
cursor: pointer;
height: 56px;
width: 56px;
background-image: url(marker.png);
background-color: rgba(0, 0, 0, 0);
}
.clearfix { display:block; }
.clearfix:after {
content:'.';
display:block;
height:0;
clear:both;
visibility:hidden;
}
/* Marker tweaks */
.mapboxgl-popup {
padding-bottom: 50px;
}
.mapboxgl-popup-close-button {
display:none;
}
.mapboxgl-popup-content {
font:400 15px/22px 'Source Sans Pro', 'Helvetica Neue', Sans-serif;
padding:0;
width:180px;
}
.mapboxgl-popup-content-wrapper {
padding:1%;
}
.mapboxgl-popup-content h3 {
background:#91c949;
color:#fff;
margin:0;
display:block;
padding:10px;
border-radius:3px 3px 0 0;
font-weight:700;
margin-top:-15px;
}
.mapboxgl-popup-content h4 {
margin:0;
display:block;
padding: 10px 10px 10px 10px;
font-weight:400;
}
.mapboxgl-popup-content div {
padding:10px;
}
.mapboxgl-container .leaflet-marker-icon {
cursor:pointer;
}
.mapboxgl-popup-anchor-top > .mapboxgl-popup-content {
margin-top: 15px;
}
.mapboxgl-popup-anchor-top > .mapboxgl-popup-tip {
border-bottom-color: #91c949;
}
</style>
</body>
{% endblock %}
Sidebar and Map div inside content-section div

How to change text of button before progressing to next page?

I am working on a quiz and need some help getting a task to perform correctly. If a user submits a wrong answer they will be shown their result and the correct answer to the question. When that happens, I would like for my 'submit answer' button to say 'next question' and then progress the user onto the next question. How can I write a function that would perform this task?
let score = 0;
let currentQuestion = 0;
let questions = [{
title: "At what age was Harry Potter when he received his Hogwarts letter?",
answers: ['7', '10', '11', '13'],
correct: 1
},
{
title: "Which is not a Hogwarts house?",
answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'],
correct: 0
},
{
title: "Who teaches Transfiguration at Hogwarts?",
answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'],
correct: 3
},
{
title: "Where is Hogwarts School for Witchcraft and Wizardry located?",
answers: ['France', 'USA', 'UK', 'New Zealand'],
correct: 2
},
{
title: "What form does Harry Potter's patronus charm take?",
answers: ['Stag', 'Eagle', 'Bear', 'Dragon'],
correct: 0
},
{
title: "What type of animal is Harry's pet?",
answers: ['Dog', 'Owl', 'Cat', 'Snake'],
correct: 1
},
{
title: "Who is not a member of the Order of the Phoenix?",
answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'],
correct: 2
},
{
title: "What is not a piece of the Deathly Hallows?",
answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'],
correct: 3
},
{
title: "In which house is Harry sorted into after arriving at Hogwarts?",
answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'],
correct: 2
},
{
title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?",
answers: ['Love', 'Anger', 'Friendship', 'Joy'],
correct: 0
},
];
$(document).ready(function() {
$('.start a').click(function(e) {
e.preventDefault();
$('.start').hide();
$('.quiz').show();
showQuestion();
});
$('.quiz ul').on('click', 'li', function() {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
$('.quiz a').click(function(e) {
e.preventDefault();
if ($('li.selected').length) {
let guess = parseInt($('li.selected').attr('id'));
checkAnswer(guess);
} else {
alert('Please select an answer');
}
});
$('.summary a').click(function(e) {
e.preventDefault();
restartQuiz();
});
});
function showQuestion() {
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz ul').html('');
for (var i = 0; i < question.answers.length; i++) {
$('.quiz ul').append(`<li id="${i}">${question.answers[i]}</li>`);
}
showProgress();
}
function showIncorrectQuestion(guess) {
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz ul').html('');
for (var i = 0; i < question.answers.length; i++) {
let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
$('.quiz ul').append(`<li id="${i}" class="${cls}">${question.answers[i]}</li>`);
}
showProgress();
}
function checkAnswer(guess) {
let question = questions[currentQuestion];
if (question.correct === guess) {
if (!question.alreadyAnswered) {
score++;
}
showIsCorrect(true);
currentQuestion++;
if (currentQuestion >= questions.length) {
showSummary();
} else {
showQuestion();
}
} else {
showIsCorrect(false);
showIncorrectQuestion(guess);
}
question.alreadyAnswered = true;
}
function showSummary() {
$('.quiz').hide();
$('.summary').show();
$('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
}
function restartQuiz() {
questions.forEach(q => q.alreadyAnswered = false);
$('.summary').hide();
$('.quiz').show();
score = 0;
currentQuestion = 0;
showQuestion();
}
function showProgress() {
$('#currentQuestion').html(currentQuestion + " out of " + questions.length);
}
function showIsCorrect(isCorrect) {
var result = "Wrong";
if (isCorrect) {
result = "Correct";
}
$('#isCorrect').html(result);
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
text-decoration: none;
text-align: center;
background-color: #837F73;
}
h1 {
font-family: 'Poor Story', cursive;
background-color: #950002;
padding: 60px;
color: #FFAB0D;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
h2 {
font-family: 'Poor Story', cursive;
font-size: 30px;
padding: 60px;
background-color: #950002;
color: #FFAB0D;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
p {
font-family: 'Poor Story', cursive;
background-color: #FFAB0D;
font-size: 20px;
font-weight: bold;
}
a {
border: 1px solid #222F5B;
padding: 10px;
background-color: #222F5B;
color: silver;
border-radius: 5px;
margin-top: 50px;
display: inline-block;
}
a:hover {
border: 1px solid #000000;
background-color: #000000;
color: #FCBF2B;
}
.quiz li {
cursor: pointer;
border: 1px solid;
display: inline-block;
width: 200px;
margin: 10px;
font-family: 'Poor Story', cursive;
font-size: 26px;
}
#currentQuestion {
color: #000000;
font-size: 18px;
font-family: 'Poor Story', cursive;
margin-top: 10px;
}
#isCorrect {
color: white;
font-family: 'Poor Story', cursive;
font-weight: bold;
font-size: 18px;
}
.quiz, .summary {
display: none;
}
.quiz ul {
margin-top: 20px;
list-style: none;
padding: 0;
}
.selected {
background-color: #398C3F;
}
.wrong {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="start">
<h1>How Well Do You Know Harry Potter?</h1>
Start Quiz
</div>
<div class="quiz">
<h2>Question Title</h2>
<ul>
<li>Choice</li>
<li>Choice</li>
<li>Choice</li>
<li>Choice</li>
</ul>
Submit Answer
<div id="currentQuestion"></div>
<div id="isCorrect"></div>
</div>
<div class="summary">
<h2>Results</h2>
<p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p>
Retake Quiz
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
You will need a second button to toggle between them
<a class="submit" href="#">Submit Answer</a>
<a class="navigate" style="display:none;" href="#">Next Question</a>
js
$('.quiz a.submit').click(function(e) {//change the selector to the answer button only
e.preventDefault();
if ($('li.selected').length) {
let guess = parseInt($('li.selected').attr('id'));
checkAnswer(guess);
} else {
alert('Please select an answer');
}
});
function checkAnswer(guess) {
let question = questions[currentQuestion];
if (question.correct === guess) {
if (!question.alreadyAnswered) {
score++;
}
showIsCorrect(true);
//remove the code for go to the next page
} else {
showIsCorrect(false);
showIncorrectQuestion(guess);
}
question.alreadyAnswered = true;
}
function showIsCorrect(isCorrect) {
var result = "Wrong";
if (isCorrect) {
result = "Correct";
}
$('#isCorrect').html(result);
$('.navigate').show();//toggle the buttons
$('.submit').hide();
}
$('.navigate').click(function() {
currentQuestion++;//go to the next question or summary
if (currentQuestion >= questions.length) {
showSummary();
} else {
showQuestion();
}
$('.navigate').hide();//toggle the buttons
$('.submit').show();
$('#isCorrect').html('');
})
demo
JS:
$(document).ready(function() {
$('.start a').click(function(e) {
e.preventDefault();
$('.start').hide();
$('.quiz').show();
showQuestion();
});
$('.quiz ul').on('click', 'li', function() {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
$('.quiz a').click(function(e) {
e.preventDefault();
if ($('li.selected').length) {
let guess = parseInt($('li.selected').attr('id'));
checkAnswer(guess);
$('#submitBtn').text('Next');
} else {
alert('Please select an answer');
}
});
$('.summary a').click(function(e) {
e.preventDefault();
restartQuiz();
});
});
function showQuestion() {
var buttonTxt = $('a#submitBtn').text();
if (buttonTxt == "Next")
$('a#submitBtn').text('Submit Answer');
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz ul').html('');
for (var i = 0; i < question.answers.length; i++) {
$('.quiz ul').append(`<li id="${i}">${question.answers[i]}</li>`);
}
showProgress();
}
function showIncorrectQuestion(guess) {
let question = questions[currentQuestion];
$('.quiz h2').text(question.title);
$('.quiz ul').html('');
for (var i = 0; i < question.answers.length; i++) {
let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
$('.quiz ul').append(`<li id="${i}" class="${cls}">${question.answers[i]}</li>`);
}
showProgress();
}
function checkAnswer(guess) {
let question = questions[currentQuestion];
if (question.correct === guess) {
if (!question.alreadyAnswered) {
score++;
}
showIsCorrect(true);
currentQuestion++;
if (currentQuestion >= questions.length) {
showSummary();
} else {
showQuestion();
}
} else {
showIsCorrect(false);
showIncorrectQuestion(guess);
}
question.alreadyAnswered = true;
}
function showSummary() {
$('.quiz').hide();
$('.summary').show();
$('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
}
function restartQuiz() {
questions.forEach(q => q.alreadyAnswered = false);
$('.summary').hide();
$('.quiz').show();
score = 0;
currentQuestion = 0;
showQuestion();
}
function showProgress() {
$('#currentQuestion').html(currentQuestion + " out of " + questions.length);
}
function showIsCorrect(isCorrect) {
var result = "Wrong";
if (isCorrect) {
result = "Correct";
}
$('#isCorrect').html(result);
}
HTML:
<a id="submitBtn" href="#">Submit Answer</a>

Event Handlers On Newly Created Elements

I have a web app with a number of textareas and the ability to add more if you wish.
When you shift focus from one textarea to another, the one in focus animates to a larger size, and the rest shrink down.
When the page loads it handles the animation perfectly for the initial four boxes in the html file, but when you click on the button to add more textareas the animation fails to accomodate these new elements... that is, unless you place the initial queries in a function, and call that function from the addelement function tied to the button.
But!, when you do this it queries as many times as you add a new element. So, if you quickly add, say 10, new textareas, the next time you lay focus on any textarea the query runs 10 times.
Is the issue in my design, or jQueries implementation? If the former, how better can I design it, if it is the latter, how can I work around it?
I've tried to chop the code down to the relevant bits... I've tried everything from focus and blur, to keypresses, the latest is on click.
html::
<html>
<head>
<link rel="stylesheet" type="text/css" href="./sty/sty.css" />
<script src="./jquery.js"></script>
<script>
$().ready(function() {
var $scrollingDiv = $("#scrollingDiv");
$(window).scroll(function(){
$scrollingDiv
.stop()
//.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "fast" );
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>boxdforstacks</title>
</head>
<body>
<div class="grid">
<div class="col-left" id="left">
<div class="module" id="scrollingDiv">
<input type="button" value="add" onclick="addele()" />
<input type="button" value="rem" onclick="remele()" />
<p class="display">The value of the text input is: </p>
</div>
</div> <!--div class="col-left"-->
<div class="col-midd">
<div class="module" id="top">
<p>boxa</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxa" ></textarea>
<p>boxb</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxb"></textarea>
<p>boxc</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxc"></textarea>
<p>boxd</p>
<textarea class="tecksd" placeholder="begin typing here..." id="boxd"></textarea>
</div>
</div> <!--div class="col-midd"-->
</div> <!--div class="grid"-->
</body>
</html>
<script type="text/javascript" src="boxd.js"></script>
js:
function onit(){
$('textarea').on('keyup change', function() {
$('p.display').text('The value of the text input is: ' + $(this).val());
});
}
$('textarea').on("click",function(){
//alert(this.id.substring(0,3));
if ( this.id.substring(0,3) == 'box' ){
$('textarea').animate({ height: "51" }, 1000);
$(this).animate({ height: "409" }, 1000);
} else {
$('textarea').animate({ height: "51" }, 1000);
}
}
);
var boxfoc="";
var olebox="";
var numb = 0;
onit();
function addele() {
var tops = document.getElementById('top');
var num = numb + 1;
var romu = romanise(num);
var newbox = document.createElement('textarea');
var newboxid = 'box'+num;
newbox.setAttribute('id',newboxid);
newbox.setAttribute('class','tecksd');
newbox.setAttribute('placeholder','('+romu+')');
tops.appendChild(newbox);
numb = num;
onit();
} //addele(), add element
function remele(){
var tops = document.getElementById('top');
var boxdone = document.getElementById(boxfoc);
tops.removeChild(boxdone);
} // remele(), remove element
function romanise (num) {
if (!+num)
return false;
var digits = String(+num).split(""),
key = ["","c","cc","ccc","cd","d","dc","dcc","dccc","cm",
"","x","xx","xxx","xl","l","lx","lxx","lxxx","xc",
"","i","ii","iii","iv","v","vi","vii","viii","ix"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
} // romanise(), turn numbers into roman numerals
css :
.tecksd {
width: 97%;
height: 51;
resize: none;
outline: none;
border: none;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
font-size: 70%;
background: white;
/* box-shadow: 1px 2px 7px 1px #0044FF;*/
}
.tecksded {
width: 97%;
resize: none;
outline: none;
border: none;
overflow: auto;
position: relative;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
font-size: 70%;
background: white;
/* box-shadow: 1px 2px 7px #FFDD00;*/
}
/*#postcomp {
width: 500px;
}*/
* {
#include box-sizing(border-box);
}
$pad: 20px;
.grid {
background: white;
margin: 0 0 $pad 0;
&:after {
/* Or #extend clearfix */
content: "";
display: table;
clear: both;
}
}
[class*='col-'] {
float: left;
padding-right: $pad;
.grid &:last-of-type {
padding-right: 0;
}
}
.col-left {
width: 13%;
}
.col-midd {
width: 43%;
}
.col-rght {
width: 43%;
}
.module {
padding: $pad;
}
/* Opt-in outside padding */
.grid-pad {
padding: $pad 0 $pad $pad;
[class*='col-']:last-of-type {
padding-right: $pad;
}
}
body {
padding: 10px 50px 200px;
background: #FFFFFF;
background-image: url('./backgrid.png');
}
h1 {
color: black;
font-size: 11px;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
}
p {
color: white;
font-size: 11px;
font-family: "Lucida Console", Monaco, monospace;
font-weight: 100;
}
You should use the following:
// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on("click", "textarea", function () {
event.preventDefault();
alert('testlink');
});
Since the textarea is added dynamically, you need to use event delegation to register the event handler.
Try
$(document).on('click', 'textarea', function() {
// do something
});
The issue is you are binding the textareas only on the page load. I made a JSFiddle with working code: http://jsfiddle.net/VpABC/
Here's what I changed:
I wrapped:
$('textarea').on("click", function () {
//alert(this.id.substring(0,3));
if (this.id.substring(0, 3) == 'box') {
$('textarea').animate({
height: "51"
}, 1000);
$(this).animate({
height: "409"
}, 1000);
} else {
$('textarea').animate({
height: "51"
}, 1000);
}
});
in a function so it looked like this:
function bindTextAreas() {
$('textarea').unbind("click");
$('textarea').on("click", function () {
//alert(this.id.substring(0,3));
if (this.id.substring(0, 3) == 'box') {
$('textarea').animate({
height: "51"
}, 1000);
$(this).animate({
height: "409"
}, 1000);
} else {
$('textarea').animate({
height: "51"
}, 1000);
}
});
}
bindTextAreas();
What this does is it allows you to call this function, bindTextAreas, whenever you create a new textarea. This will unbind all the current events than rebind them. This will make it so your new textarea is has the click handler setup.
An place where this function is called is in the addele function like this:
function addele() {
var tops = document.getElementById('top');
var num = numb + 1;
var romu = romanise(num);
var newbox = document.createElement('textarea');
var newboxid = 'box' + num;
newbox.setAttribute('id', newboxid);
newbox.setAttribute('class', 'tecksd');
newbox.setAttribute('placeholder', '(' + romu + ')');
tops.appendChild(newbox);
numb = num;
onit();
bindTextAreas();
} //addele(), add element
Notice the bindTextAreas(); line near the bottom. This reloads all the click handlers.

Background color automatic cycle with Javascript

I have 3 divs set up on my website, and at the moment I am using CSS3 to highlight each div for 5 seconds by changing the background colour. So the first div highlights for 5 seconds, then the 2nd then the 3rd. Can I acheive the same thing with Javascript?
My html is
<a href=""><div class="highlight" id="caption2">
Text1
</div></a>
<a href=""><div class="highlight" id="caption3">
Text2</div></a>
<a href="">
<div class="highlight" id="caption4">
Text3</div></a>
Js
$("div.highlight").each(function (i) {
var $self = $(this);
setTimeout(function () {
$self.removeClass("highlight")
$self.addClass("caption");
setTimeout(function () {
$self.addClass("highlight");
$self.removeClass("caption");
}, 1000);
}, i * 1000);
});
CSS
#caption2 {
position:absolute;
top:10px;
left:-20px;
z-index:50;
padding-left:10px;
padding-right:20px;
padding-top:15px;
padding-bottom:15px;
color:#fff;
font-family: 'Droid Sans', sans-serif;
overflow:hidden;
}
#caption3 {
position:absolute;
top:70px;
left:-20px;
z-index:70;
padding-left:10px;
padding-right:20px;
padding-top:15px;
padding-bottom:15px;
color:#fff;
font-family: 'Droid Sans', sans-serif;
overflow:hidden;
}
#caption4 {
position:absolute;
top:130px;
left:-20px;
z-index:50;
padding-left:10px;
padding-right:20px;
padding-top:15px;
padding-bottom:15px;
color:#fff;
font-family: 'Droid Sans', sans-serif;
overflow:hidden;
}
.highlight {
background-color:#000;
}
.caption {
background-color:#f1583c;
color:yellow;
}
Sure! Nothing simpler than this:
var divs = document.getElementsByTagName("div")
for(var i = 0; i < divs.length; i++) {
setTimeout(function(n){
divs[n].className = "highlight";
}, i * 1000, i);
}
http://fiddle.jshell.net/e4Qv4/
Or if you want it more jQuery'ished, take something like this:
$("div").each(function(i){
var self = this;
setTimeout(function(){
self.className = "highlight";
}, i * 1000);
});
http://fiddle.jshell.net/e4Qv4/1/
Update
Your main problem is the css-selector specificity... An ID gets an higher rate then a class. The other thing is, that you've misunderstood my solution. Read a bit about the Sizzle-Selector engine, which is built in jQuery, that should help you.

Explore generic value like WebKit console

I am developing a customed tool to test a javascript library.
I'm using Chrome.
I need to explore a generic object, programmaticaly, like WebKit console, when I write "window" and press enter.
How can I implement that inspector?
Or, how can I invoce that object inspector and insert generated HtmlElement to DOM?
In waiting I develop the Explore method.
jQuery required.
This is the JavaScript code:
window.Debugger = {};
window.Debugger.Explore = function (value) {
var fReturn = jQuery("<div class=\"DbgExp\" />");
if (value === null) {
fReturn.addClass("aNull").text("null");
} else {
switch (typeof value) {
case "undefined":
fReturn.addClass("aNull").text("undefined");
break;
case "string":
fReturn.addClass("aStr").text("\"" + value + "\"");
break;
case "number":
fReturn.addClass("aVal").text(value);
break;
case "boolean":
fReturn.addClass("aVal").text(value ? "true" : "false");
break;
case "function":
case "object":
var str1 = "" + value;
if (str1.length > 40) str1 = str1.substr(0, 37) + "...";
var objName = jQuery("<div class=\"name\" />").text(str1);
fReturn.addClass("aObj").append(objName);
objName.click(function (ev, data) {
if (fReturn.hasClass("aOn")) return fReturn.removeClass("aOn");
fReturn.addClass("aOn");
if (fReturn.data("isFill")) return;
var ul = jQuery("<ul />").appendTo(fReturn);
var num = 0;
for (var k in value) {
jQuery("<li />")
.appendTo(ul)
.append(
jQuery("<div class=\"lbl\" />").text(k)
, Debugger.Explore(value[k])
);
num++;
}
if (num == 0) {
jQuery("<li><div class=\"lbl\">- no properties -</div></li>").appendTo(ul);
}
fReturn.data("isFill", true);
});
break;
}
}
return fReturn;
};
And this is the CSS:
.DbgExp { display:inline-block; background-color:white; color:black; font-family:monospace; font-size:10pt; }
.DbgExp.aNull { background-color:white; font-size:10pt; color:#a9a9a9; }
.DbgExp.aStr { background-color:white; font-size:10pt; color:#a62222; }
.DbgExp.aVal { background-color:white; font-size:10pt; }
.DbgExp.aObj { background-color:white; font-size:10pt; border:dotted 1px cornflowerblue; margin-left:20px; }
.DbgExp.aObj:before { display:inline-block; content:"+"; background-color:#d8eaff; border:solid 1px #0966b4; width:16px; line-height:16px; font-family:monospace; font-size:14px; font-weight:bold; text-align:center; }
.DbgExp.aObj .name { display:inline; font-family:monospace; min-width:40px; margin-left:5px; color:#0966b4; background-color:#d8eaff; border:solid 1px #0966b4; font-size:9pt; font-family:helvetica; padding:1px 4px; cursor:pointer; }
.DbgExp.aObj.aOn:before { content:"-"; }
.DbgExp.aObj ul { display:none; }
.DbgExp.aObj.aOn > ul { display:block; }
.DbgExp.aObj ul li { }
.DbgExp.aObj ul li .lbl { display:inline-block; font-family:helvetica; min-width:80px; font-size:10pt; color:#777; vertical-align:top; }
.DbgExp.aObj ul li .DbgExp { margin-left:10px; }
A html fragment to show how to use:
...
<div id="DebugOutput">
</div>
<script type="text/javascript">
jQuery(document)
.ready(function () {
jQuery("#DebugOutput")
.append(
Debugger.Explore(new Date())
, Debugger.Explore(window)
);
});
</script>

Categories

Resources