Ascii Art Animation in Browser - javascript

I want to animate Ascii Art in the Browser.
The Ascii Art should be loaded via a text file. There are many libraries which convert but I have found none, which actually animates it.
By animation I mean a typewriter animation that speeds up over time and changes the 'zoom factor' so that the whole image is visible in the viewport at the end.
Hopefully anyone knows a libary for my problem.

I have a feeling SO doesn't like library recommendations, and actually I haven't found one, so here's some basic code to get you started.
It sets the typing speed to the old Teletype 10 chars per second and of course that can be changed, and an acceleration function can be added when you know what you want for that. Note: the txt file needs to be on the same domain to prevent CORS problems.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Typewriter print</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Courier, monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div id="container">
<input id="file" type="text" value="" placeholder="Filename" />
<button onclick="loadFile()">Click to draw the file</button>
<div id="picture"></div>
</div>
<script>
let file = '';
let reader = new XMLHttpRequest();
function loadFile() {
file = document.getElementById('file').value;
reader.open('get', file, true);
reader.onreadystatechange = draw;
reader.send(null);
}
function draw() {
if (reader.readyState == 4) {
const picture = document.getElementById('picture');
picture.innerHTML = '';
let str = reader.responseText;
let chs = str.split('');
//set as the typing speed in characters
//per second 10 is the old teletype speed
let chsPerSec = 10;
let i = 0;
function reveal() {
if (i < chs.length) {
let nextch = chs[i];
if (nextch.charCodeAt(0) == 10) {
nextch = '<br>';
} else if (nextch.charCodeAt(0) == 32) {
nextch = '<span style="color:transparent;">.</span>';
}
picture.innerHTML = picture.innerHTML + nextch;
setTimeout(reveal, Math.floor(1000 / chsPerSec));
i++;
}
}
reveal();
}
}
</script>
</body>
</html>

Related

how to change a text and image every 5 seconds in javascript and html

hey I wrote a JavaScript code and I managed to make the image change every few seconds but the text is changing alongside with the image but not the correct text is shown here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
<script>
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
setTimeout("changeImage()", 6000);
}
function changeText() {
var txt= document.getElementById("message");
txt.textContent = text[y];
y++;
if(y>= text.length){
y = 0;
}
setTimeout("changeText()", 6000);
}
var text = [], y=0;
text[0] = "MSG1";
text[1] = "MSG2";
text[1] = "MSG3";
setTimeout("changeText()", 6000);
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hello
</h1>
<img id="img"
src="image1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
is there any efficient way to do it my goal is to make 3-5 images on an html webpage that change between each other every few seconds and each image has a different text above it
Combine your two functions into one, so both things happen at the same time:
<script>
function changeImageAndText() {
var img = document.getElementById("img");
img.src = images[x];
var txt = document.getElementById("message");
txt.textContent = text[x];
x++;
if (x >= images.length) {
x = 0;
}
setTimeout("changeImageAndText()", 6000);
}
var text = [],
images = [],
x = 0;
text[0] = "MSG1";
text[1] = "MSG2";
text[2] = "MSG3";
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImageAndText()", 6000);
</script>
Instead of maintaining two arrays have one array of objects each of which contains image and text information. You can then create markup containing both sets of information at once rather than relying on two functions.
This working example uses images from dummyimage.com.
const data = [
{ image: 'https://dummyimage.com/100x100/666/ff0', text: 'Image 1' },
{ image: 'https://dummyimage.com/100x100/222/ff0', text: 'Image 2' },
{ image: 'https://dummyimage.com/100x100/fff/000', text: 'Image 3' },
{ image: 'https://dummyimage.com/100x100/a45/000', text: 'Image 4' },
];
// Cache the element
const div = document.querySelector('div');
// `carousel` is the main function into which we
// pass the data
function carousel(data) {
// `loop` is what `setTimeout` calls every second
// We initialise `count` to 0
function loop(count = 0) {
// Create the HTML using a template string
const html = `
<figure>
<img src="${data[count].image}" />
<figcaption>${data[count].text}</figcaption>
</figure>`;
// Add the markup to the div
div.innerHTML = html;
// Reset the count if we've reached the
// end of the array, otherwise increment it
if (count === data.length - 1) {
count = 0;
} else {
++count;
}
// Call `loop` every second with the
// updated `count` variable
setTimeout(loop, 1000, count);
}
loop();
}
carousel(data);
<div></div>
Additional information
Template/string literals
querySelectorAll
figure
Your code is basically fine as far as timing goes - with intervals as long as 6 seconds you aren't going to notice if one timeout happens a microsecond after the other.
Your problem is a straightforward bug. There is a repetition of text[1] so the MSG2 never gets shown.
This is your snippet with just that change made and it works perfectly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
img {
height: 500px;
width: 450px;
}
h1 {
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button {
margin-left: 45%;
}
</style>
<script>
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if (x >= images.length) {
x = 0;
}
setTimeout("changeImage()", 6000);
}
function changeText() {
var txt = document.getElementById("message");
txt.textContent = text[y];
y++;
if (y >= text.length) {
y = 0;
}
setTimeout("changeText()", 6000);
}
var text = [],
y = 0;
text[0] = "MSG1";
text[1] = "MSG2";
text[2] = "MSG3";
setTimeout("changeText()", 6000);
var images = [],
x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hello
</h1>
<img id="img" src="image1.jpg">
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
However, you mention efficiency, and again at such long time intervals it probably isn't going to make a great deal of difference as the JS is only called every 6 seconds but if you want to make more efficient code then consider ditching JS and using CSS animations instead - the browser will have a chance of using the GPU then.
The way I would do it is this:
const text = ["MSG1", "MSG2", "MSG3"];
const image = ["image1.jpg", "image2.jpg", "image3.jpg"];
const imageObj = document.GetElementById("img");
const textObj = document.GetElementById("message");
let counter = 0;
function ChangeImage() {
if (counter == text.length) {
counter = 0;
}
textObj.innerText = text[counter];
imageObj.src = image[counter];
counter++;
}
setInterval(ChangeImage, 3000); // 3000 = 3 Seconds, 5000 = 5 seconds.
The main thing to remember is to reduce the amount of times you repeat yourself, when looping through an array (when the pointer will be the same always) use the same variable (in this case counter)

How to increase size of emoji using 'ArrowUp' in Javascript

I'm trying to continually increase the size of the balloon emoji 10px when a user pushes the up arrow as well as decrease size by 10px with down arrow on keypad.
I've been trying to set:
let size = para.style.fontSize;
in order to get a variable for the size and then adjust that value by adding +/- 10px in my function. However, I've tried this method and it seems as if you can not set:
para.style.fontSize = size +10;
Does anybody have any suggestions to get this to work?
Note: I have not included the size variable in the code below as I found it does not work.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
window.addEventListener("keydown", e => {
if (e.key == "ArrowUp") {
para.style.fontSize = '60px';
} else {
para.style.fontSize = '40px';
}
});
</script>
</body>
</html>
To achieve growing/shrinking behavior over multiple keydown events, you'll need to increment/decrement para.style.fontSize per event. Once way this could be done is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
window.addEventListener("keydown", e => {
let currentSize = parseInt(para.style.fontSize);
// If unable to determine current fontSize, default to 50
if (isNaN(currentSize)) {
currentSize = 50;
}
// Define the rate of change
let changeAmount = 5;
if (e.key == "ArrowUp") {
para.style.fontSize = (currentSize + changeAmount) + 'px';
} else {
// Protect againt zero or negative font sizes via Math.max()
para.style.fontSize = Math.max(changeAmount, currentSize - changeAmount) + 'px';
}
});
</script>
</body>
</html>
The issue is that the current fontSize property was null so you can't add to a null value. The second issue is that the fontSize property is actually a string with "px". So if you want to increase or decrease the value, you need to parse out the integer value. Then, when you assign it back to para.style.fontSize, you need to append "px" back.
Here is your code with the changes described above.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
// Set to default size
para.style.fontSize = '24px';
window.addEventListener("keydown", e => {
var sizeAsInteger = parseInt(para.style.fontSize, 10);
if (e.key == "ArrowUp") {
sizeAsInteger += 10;
} else {
sizeAsInteger -= 10;
}
para.style.fontSize = sizeAsInteger + 'px';
});
</script>
</body>
</html>
Note that if you grab the size and then do console.log(size), you will get a blank result for the first round (because it's initially not set) and all subsequent rounds you get the size with px appended to the end. Thus, size + 10 with an initial size of 40px will give you 40px10. This results in undesired behavior.
To fix this, you need to remove the px, convert to a number, then append the px again:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
window.addEventListener("keydown", e => {
let size = para.style.fontSize.replace('px', '');
size = size == '' ? '50' : size; // size may not be initialized, so default to our intended starting value!
size = parseInt(size);
if (e.key == "ArrowUp") {
para.style.fontSize = (size + 10) + 'px';
} else {
para.style.fontSize = (size - 10) + 'px';
}
});
</script>
</body>
</html>

Passing variables from JavaScript to HTML and HTML button inputs to JavaScript

I am trying to make a simple game using JavaScript and HTML.
The game consists of having two buttons on the screen with random numbers and clicking the one that is smaller.
At the end, you will get your results.
What I am having trouble with is getting the random number generated in JavaScript to print on the button and getting the data back to JavaScript from the button.
var number = prompt('Choose Your Difficulty, Easy, Normal, Or Hard?');
var number = number.toUpperCase(); //Chooses difficulty
if (number === 'EASY')//easy difficulty
{
var difficulty = 20;
}else if (number === 'NORMAL')//normal difficulty
{
var difficulty = 100;
}else if(number === 'HARD')//hard difficulty
{
var difficulty = 1000;
}else
{
alert('Please Enter A Valid Answer')//if value is not valid
}
var number1 = Math.floor((Math.random()* difficulty) + 1);//random number 1
var number2 = Math.floor((Math.random()* difficulty) + 1);//random number 2
//----------------------Code i found but im not sure now to use it--------------
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "Do Something";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener("click", function() {
alert("did something");
});
//-----------------------------------------------------------------------------
button {
margin-top: 20px;
line-height: 60px;
font-weight: bold;
padding: 0 40px;
background: salmon;
border: none;
}
button:hover {
background: lightsalmon;
}
<!DOCTYPE html>
<html>
<head>
<title>
Speed Game
</title>
<link href="css/styles.css" rel="stylesheet"
type="text/css">
<script src="../script/script.js"></script>
</head>
<body>
<button id= "button">
Do Something!
</button>
</body>
</html>
How can I solve this problem?
First of all, welcome to the world of programming!
Second, here's the game you wanted. I've done everything using functions, so understanding it should be easy.
Try to play a few games first!
The concept is pretty simple, really, so after playing a bit, look at the code and try to figure it out on your own!
var number;
var difficulty = 0;
var randomNumOne;
var randomNumTwo;
var buttonOne = document.getElementById("buttonOne");
var buttonTwo = document.getElementById("buttonTwo");
var tempButton;
function requestDifficulty(){
number = prompt('Choose Your Difficulty, Easy, Normal, Or Hard?');
number = number.toUpperCase();
setDifficulty();
}
function setDifficulty(){
if (number === 'EASY'){
difficulty = 20;
startGame();
}else if (number === 'NORMAL'){
difficulty = 100;
startGame();
}else if(number === 'HARD'){
difficulty = 1000;
startGame();
}else{
alert('Please Enter A Valid Answer');
requestDifficulty()
}
}
function startGame(){
randomNumOne = Math.floor((Math.random()* difficulty) + 1);
randomNumTwo = Math.floor((Math.random()* difficulty) + 1);
buttonOne.innerHTML = randomNumOne;
buttonTwo.innerHTML = randomNumTwo;
}
function getResults(pressedButton){
tempButton = pressedButton;
if(tempButton == "buttonOne"){
if(randomNumOne < randomNumTwo){
alert("Correct!")
}else{
alert("False!")
}
}else if(tempButton == "buttonTwo"){
if(randomNumTwo < randomNumOne){
alert("Correct!")
}else{
alert("False!")
}
}
}
requestDifficulty();
button {
margin-top: 20px;
line-height: 60px;
font-weight: bold;
padding: 0 40px;
background: salmon;
border: none;
}
button:hover {
background: lightsalmon;
}
<!DOCTYPE html>
<html>
<head>
<title>
Speed Game
</title>
</head>
<body>
<button id="buttonOne" onclick="getResults('buttonOne');">
random number 1
</button>
<button id="buttonTwo" onclick="getResults('buttonTwo')">
random number 2
</button>
</body>
</html>

jQuery Maximum characters in a div

I'm looking for a way to fill a div with single characters.
The div should be the width of the viewport. I get the width with:
$(window).width();
JS should build a HTML-code like this:
<div id="text">ccccccccccccccccccccccccccccccccccccccccc</div>
Thanks for your inputs.
Here's a way to do it:
var char = 'i';
$('#text').html($('#text').html() + char)
var initialheight = $('#text').height();
while ($('#text').height() === initialheight) $('#text').html($('#text').html() + char)
$('#text').html($('#text').html().slice(0,-1))
#text {
word-break: break-all;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text"></div>
The way this works is that the script inserts a character int the div and gets the height. Then in repeatedly adds characters until the height changes, which indicates that more than one line has occurred. Then it trims the last character that caused it to overflow onto two lines. It's independent of any font characteristics.
Because a character size can be fixed or not accordig to the font I suggest to use a function to approximate the numbers of characters to print:
function writeMaxNumCharsInOneLine(textObj, charToWrite) {
var innWidth = textObj.innerWidth();
textObj.append('<span id="charSize" style="visibility: visible; white-space: nowrap;">' + charToWrite + '</span>');
var charSize = $('#charSize').width();
var numCharsToWrite = (innWidth / charSize).toFixed(0);
var strToWrite = charToWrite.repeat(numCharsToWrite);
$('#charSize').text(strToWrite);
charSize = $('#charSize').width();
while (charSize < innWidth) {
strToWrite = strToWrite + charToWrite;
$('#charSize').text(strToWrite);
charSize = $('#charSize').width();
}
if (charSize > innWidth) {
strToWrite = strToWrite.slice(0,-1);
}
$('#charSize').remove();
textObj.text(textObj.text() + '\n' + strToWrite);
}
$(function () {
writeMaxNumCharsInOneLine($('#text'), 'Y')
writeMaxNumCharsInOneLine($('#text'), 'a')
writeMaxNumCharsInOneLine($('#text'), 'b')
writeMaxNumCharsInOneLine($('#text'), 'c')
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<div id="text" style="border: double;width: 50%;height: 100px;"></div>
Next time you may want to add more information as well as what you have tried, your question doesn't show much troubleshooting on your side; however I think the code below should work or help you figure out something for what you are trying to do.
var w = $(document).width();
var d = $("#text").width();
var s = "";
do{
s+= "X";
$("#text").text(s)
d = $("#text").width();
}
while(d < w)
<div>
<span id="text"></span>
</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function() {
var b=$( "<span padding=0 margin=0></span>").appendTo( $("#text") );
do {
$(b).append("M");
} while ($(b).width() < $(b).parent().width() )
});
});
</script>
</head>
<body>
<div id="text"></div>
<button>Click me</button>
</body>
</html>
You mean this?
$(function() {
var windowWidth = $(window).width();
var oneCharacterWidth = $("#text").width();
var total = windowWidth / oneCharacterWidth;
$("#text").html("");
for (i = 0; i < total; i++) {
$("#text").append("c");
}
})
#text {
display:inline;
font-size:12px;
}
body {
margin:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">c</div>

Javascript a game of q and a

Using JavaScript only.
I have an array of four questions and an array of four answers and an array of four wrong answers.
I use an array due to order.
When the first question appears, the computer will generate a random number and based on this number put the correct answer in the left or right and put the wrong answer in the other spot.
I register two event handlers on the left and right div's containing those answers.
The individual will select the left or right div based on the question and after the four questions, I will tell you how well you did.
My issue is how to determine which side they chose and if it is right or wrong. I can use event.target.id to determine what the person selected, but how to compare that to the right answer knowing it is random??
I am so new... did I say new.. here is my code to show I tried.. I think its simple, but mind block
I did not finish the rightwrong eventlistener. AND I know the camelCasing, but I wanted to get a rough cut first
window.onload = function () {
var questions = new Array();
questions[0] = "This is the first question";
questions[1] = "This is the second question";
questions[2] = "This is the third question";
questions[3] = "This is the fourth question";
var answers = new Array();
answers[0] = "first answer";
answers[1] = "second answer";
answers[2] = "third answer";
answers[3] = "fourth answer";
var garbage = new Array();
garbage[0] = "first garbage";
garbage[1] = "second garbage";
garbage[2] = "third garbage";
garbage[3] = "fourth garbage";
var k = 0;
var q = document.getElementById("questionId");
var a = document.getElementById("left");
var g = document.getElementById("right");
var nxtquestion = document.getElementById('nextquestion');
nxtquestion.addEventListener('mousedown', nextquestion, false);
a.addEventListener('mousedown', rightwrong, false);
g.addEventListener('mousedown', rightwrong, false);
function nextquestion() {
for (var i = 0; i < questions.length; i++) {
q.innerHTML = questions[k];
}
randomize(k);
k++;
if (k > questions.length) {
q.innerHTML = "Great, you have finished. Please reload the page to play again!";
a.innerHTML = "";
g.innerHTML = "";
nxtquestion.style.display = "none";
}
return;
}
function randomize(k) {
var randomizer = Math.floor((Math.random() * 10) + 1);
if (randomizer <= 5) {
a.innerHTML = answers[k];
g.innerHTML = garbage[k];
} else {
g.innerHTML = answers[k];
a.innerHTML = garbage[k];
}
}
}
Here is the HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>chapter 1</title>
<link rel="stylesheet" type="text/css" href="regart.css">
<script src="regart.js">
</script>
</head>
<body>
<header>
<img class="center" src="regart.jpg" width="278" height="113" alt="regart" />
</header>
<div class="middlesection">
<p id="questionId" class="question">Let's Play RegArt!<br /> Choose either left or right for the correct answer.<br /> To begin, click on the 'Next Question' button. </p><input type="button" id="nextquestion" value="Next Question" />
<p id="howmany"></p>
</div>
<div>
<div class="answerleft" id="left"><p>Left</p></div> <div class="answerright" id="right"><p>Right</p></div>
</div>
<footer>
</footer>
</body>
</html
Here is the CSS... the image will be missing but not important
header, footer, nav
{ display:block; }
html,ul, li, div, h1, h2, h3, p, img
{margin:0; padding:0;}
body
{ width:80%; margin:auto; max-width:960px; font-size:100%; background-color:#401d36;}
header { height:120px; background-color:#0f9fbf; }
img.center {display:block;margin:0 auto;}
.middlesection { background-color:#f2e085; padding:20px 20px 0 20px; height:200px;border-style:dashed; color:#401d36; border-width:thin;}
p {font-family:Baskerville, "Palatino Linotype", Palatino, "Century Schoolbook L", "Times New Roman", serif; font-size:1.2em; padding-left:10px; padding-bottom:30px;}
.answerleft {border-style:dashed; color:#0f9fbf; float:left; width:35%; padding:5%; height:200px; font-size:3em; }
.answerright {border-style:dashed; color:#0f9fbf; float:right; width:35%; padding:5%; height:200px; font-size:3em; }
the code you provided misses one vital function. however I have created a fiddle you can check. This I think will solve your problem and you can carry on from there.
function randomize(k) {
var randomizer = Math.floor((Math.random() * 10) + 1);
if (randomizer <= 5) {
a.innerHTML = answers[k];
g.innerHTML = garbage[k];
a.addEventListener('mousedown', rightAnswer, false);
g.addEventListener('mousedown', wrongAnswer, false);
} else {
g.innerHTML = answers[k];
a.innerHTML = garbage[k];
g.addEventListener('mousedown', rightAnswer, false);
a.addEventListener('mousedown', wrongAnswer, false);
}
}
function rightAnswer(){
alert('You are right');
}
function wrongAnswer(){
alert('You are wrong');
}
http://jsfiddle.net/Pallab/ACXPN/embedded/result/
One way to do it would be to set something on the element itself and then check for that. Or use a different event handler for each element (you'd have to remove and then re-add them every time the right answer swapped sides).
But an easier way would be to just store the id of the correct element in a global variable then check that, something like this:
var rightAnswerId;
function rightwrong(e) {
if (e.target.id == rightAnswerId) {
alert("CORRECT");
} else {
alert("WRONG");
}
}
function randomize(k) {
var randomizer = Math.floor((Math.random() * 10) + 1);
if (randomizer <= 5) {
a.innerHTML = answers[k];
g.innerHTML = garbage[k];
rightAnswerId = 'left';
} else {
g.innerHTML = answers[k];
a.innerHTML = garbage[k];
rightAnswerId = 'right';
}
}
There are various other solutions, including storing the current question and comparing the clicked elements contents to the correct answer for that question.
I put my solution into a Fiddle, that might make it easier for someone to come up with something better.
(I changed the event from mousedown to click, which made more sense for the demo but it depends on exactly what you want to happen).
You also might want to call nextquestion on page load to go immediately to the first question. Again, depends on what you want to happen.
i'm quite shure you wanna use k instead of i as index in your for() statement...
anyway:
but how to compare that to the right answer knowing it is random??
use another variable to store the right answer's position
...
var right_side;
...
function randomize(k) {
var randomizer = Math.floor((Math.random() * 10) + 1);
if (randomizer <= 5) {
a.innerHTML = answers[k];
g.innerHTML = garbage[k];
right_side = "left";
} else {
g.innerHTML = answers[k];
a.innerHTML = garbage[k];
right_side = "right";
}
}
then in your rightwrong eventlistener check the right_side value

Categories

Resources