JavaScript/HTML Word Guessing Game: difficulty levels w/drop-down - javascript
I am working on a project to have a random word guessing game. So far most of the code is working but I am trying to implement some rules on the length of words displayed to the user as a measure of game difficulty (shorter words = easier, etc). I am using a drop-down menu to get the user's setting selection, and then have rules in the JS tags that are supposed to be handling this.
After toying around with this for several days, I was hoping that a fresh pair of eyes might have a suggestion about where I am going wrong to be able to enforce the rules I am trying to enforce?
The specific functions that should be handling this are setDifficulty(), getSelection(), and randomWord()
<html lang="en">
<head>
<style>
body {
background-color: rgb(231, 223, 223);
align-content: center;
margin: 2px;
padding: auto;
}
h1 {
text-align: center;
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: rgb(187, 212, 235);
margin: auto;
}
h4 {
text-align: center;
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
margin: auto;
}
div {
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: rgb(231, 223, 223);
}
button {
background-color: rgba(65, 127, 207, 0.781);
color: rgb(255, 255, 255);
padding: 1%;
margin-bottom: 2%;
flex-wrap: wrap;
font-size: xx-large;
border: 3px;
border-radius: 5px;
}
button:disabled {
background-color: rgba(65, 127, 207, 0.363);
}
label {
text-align: center;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
border: 3px;
border-radius: 5px;
}
</style>
<meta charset="UTF-8">
<title>Word Guessing Game</title>
</head>
<body>
<label for="difficulty">Choose difficulty level:</label>
<select name="difficulty" id="difficulty_setting">
<option value="Easy" onclick="setDifficulty()">Easy</option>
<option value="Medium" onclick="setDifficulty()">Medium</option>
<option value="Hard" onclick="setDifficulty()">Hard</option>
</select>
<div class="container">
<h1 class="text-center">Random Word Guessing Game</h1>
<div class="float-right" style="position: absolute; text-align: left;">Wrong Guesses: <span id='mistakes'>0</span> of <span id='maxWrong'></span></div>
<div class="text-center">
<h3>Guess the word:</h3>
<p style="font-size: 56px;" id="wordSpotlight">The word to be guessed goes here</p>
</div>
<div id="keyboard"></div>
<button class="btn btn-info" onClick="restart()">Restart</button>
</div>
<script type="text/javascript">
let random_words = [
"plankton",
"pitman",
"dexamethasone",
"marabout",
"wintertime",
"trencherman",
"subtilize",
"cursorial",
"asterism",
"jam",
"bacteriostat",
"unworn",
"nonuniformity",
"subpart",
"groats",
"quintette",
"blowtube",
"ethnographical",
"bulbous",
"cataphoretic",
"difficult",
"opacify",
"credence",
"sextette",
"mot",
"prosthodontics",
"whippletree",
"life",
"cook",
"toxic",
"quadrature",
"tawdrily",
"escalader",
"clincher",
"ataxia",
"chiton",
"pains",
"straining",
"tenderize",
"circadian",
"wreak",
"foam",
"artemisia",
"pietistic",
"commemoration",
"excise",
"phalanger",
"decidua",
"cinematography",
"supportable",
"unspoilt",
"hermeneutics",
"whipsaw",
"quartan",
"transportable",
"imbrue",
"oxtongue",
"flogging",
"intramolecular",
"mechanism",
"busted",
"talker",
"sedum",
"glial",
"youthful",
"deviationist",
"headpin",
"realise",
"hygiene",
"worst",
"isosmotic",
"narcoleptic",
"confidently",
"boneset",
"tugboat",
"bimanual",
"daredeviltry",
"bris",
"trip",
"notably",
"repartee",
"suckling",
"hymnody",
"pleating",
"graffiti",
"assuredly",
"moment",
"isotropic",
"absconder",
"microspore",
"adobe",
"photoconductivity",
"stray",
"stalk",
"squelch",
"animistic",
"pretentiousness",
"unsmoothed",
"goalmouth",
"exclusiveness",
"bullpen",
"unasked",
"dilettantish",
"dedication",
"happily",
"squealer",
"perineurium",
"whatchamacallit",
"appreciativeness",
"topographically",
"conjuncture",
"resurvey",
"vaned",
"homo",
"upcurved",
"houseful",
"microdot",
"hated",
"literature",
"hydrophilic",
"collie",
"phycoerythrin",
"canine",
"unmanful",
"scrim",
"wanted",
"enantiomorphism",
"theologian",
"gastronomical",
"bura",
"malocclusion",
"superincumbent",
"circumferential",
"interrelated",
"calamine",
"subsidizer",
"sarcoplasm",
"eagerly",
"incautiously",
"priorship",
"gooseneck",
"wearisome",
"preciously",
"lust",
"liger",
"ovary",
"garganey",
"slather",
"hisser",
"counterfoil",
"divisible",
"hypochondria",
"statute",
"education",
"byword",
"damp",
"hornbeam",
"levity",
"nucha",
"fauteuil",
"rho",
"soothsaying",
"decreased",
"faze",
"lamia",
"above",
"artful",
"schmuck",
"stocked",
"carabiner",
"incomparably",
"unfaithfully",
"parturient",
"erotism",
"menu",
"pall",
"technical",
"stile",
"expulsion",
"spitball",
"doubting",
"wheelchair",
"aptly",
"aedes",
"successfulness",
"abductor",
"offerer",
"bloody",
"tenderheartedness",
"amusive",
"streptococci",
"gnaw",
"curiousness",
"hemorrhage",
"theologise",
"uninhabited",
"strep",
"unadoptable",
"prophetic",
"somite",
"pythoness",
"governable",
"churlish",
"craniate",
"confusion",
"smilingly",
"accruement",
"oftener",
"coho",
"scripture",
"unprovoked",
"adenohypophysis",
"fitter",
"pronouncement",
"replacing",
"custodial",
"dynamiter",
"vespers",
"hostility",
"knoll",
"vendor",
"sprig",
"stave",
"raphia",
"canfield",
"paint",
"data",
"teleconference",
"tractability",
"knit",
"amazement",
"airfield",
"cesium",
"galactic",
"axial",
"buffalo",
"unsaddled",
"pygmy",
"brewer",
"hazel",
"inauthentic",
"herrenvolk",
"uncommercialized",
"exasperatingly",
"irony",
"solan",
"subsequence",
"outclass",
"etch",
"regalia",
"unanswered",
"prospective",
"rumormonger",
"forecastle",
"mineralogy",
"adorability",
"photogravure",
"pronucleus",
"underpopulated",
"disgrace",
"smutch",
"ohmage",
"cabomba",
"emptying",
"wordsmith",
"charitable",
"sadomasochism",
"web",
"railroader",
"allow",
"pennon",
"preservation",
"mollah",
"prematurity",
"puzzlement",
"megaloblast",
"adulterating",
"dowager",
"shirtfront",
"exchequer",
"transplanter",
"turntable",
"heedlessness",
"escapist",
"calf",
"aortic",
"rumored",
"sagamore",
"form",
"settle",
"persuasiveness",
"ineptitude",
"trembles",
"navigator",
"gabbro",
"disappear",
"thermocouple",
"spay",
"frisking",
"haft"
]
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
function handleGuess(chosenLetter) {
guessed.indexOf(chosenLetter) === -1 ? guessed.push(chosenLetter) : null;
document.getElementById(chosenLetter).setAttribute('disabled', true);
if (answer.indexOf(chosenLetter) >= 0) {
guessedWord();
checkIfGameWon();
} else if (answer.indexOf(chosenLetter) === -1) {
mistakes++;
updateMistakes();
checkIfGameLost();
updateHangmanPicture();
}
}
function checkIfGameWon() {
if (wordStatus === answer) {
document.getElementById('keyboard').innerHTML = 'You Won!!!';
}
}
function checkIfGameLost() {
if (mistakes === maxWrong) {
document.getElementById('wordSpotlight').innerHTML = 'The answer was: ' + answer;
document.getElementById('keyboard').innerHTML = 'You Lost!!!';
}
}
function guessedWord() {
wordStatus = answer.split('').map(letter => (guessed.indexOf(letter) >= 0 ? letter : " _ ")).join('');
document.getElementById('wordSpotlight').innerHTML = wordStatus;
}
function updateMistakes() {
document.getElementById('mistakes').innerHTML = mistakes;
}
function generateButtons() {
let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
`
<button
class="btn btn-lg btn-primary m-2"
id='` + letter + `'
onClick="handleGuess('` + letter + `')"
>
` + letter + `
</button>
`).join('');
document.getElementById('keyboard').innerHTML = buttonsHTML;
}
function restart() {
mistakes = 0;
guessed = [];
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
function setDifficulty() {
mistakes = 0;
guessed = [];
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
document.getElementById('maxWrong').innerHTML = maxWrong;
var diff_setting = document.getElementById('difficulty_setting');
randomWord();
generateButtons();
guessedWord();
function getSelection(){
// select difficulty
//var selection = diff_setting;
let easy_game = random_words.filter((easy_words) => {
if(easy_words.length < 6){
return easy_words;}});
let medium_game = random_words.filter((med_words) => {
if(med_words.length <= 9){
return med_words;}});
let hard_game = random_words.filter((hard_words) => {
if(hard_words.length > 9){
return hard_words;}});
alert(diff_setting.value);
if(diff_setting.value == 'Easy'){
return easy_game;
} else if (diff_setting.value == 'Medium'){
return medium_game;
} else {
return hard_game;}
}
function randomWord() {
var arr = getSelection();
answer = random_words[Math.floor(Math.random() * arr.length - 1)];
}
</script>
</body>
</html>'''
Let's start by saving the difficulty setting in a variable along these :
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
let diff_setting = 'Easy';
then edit the setdifficulty function to change that variable
function setDifficulty(difficulty) {
diff_setting = difficulty;
mistakes = 0;
guessed = [];
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
then call the function each time the setting is changed
<label for="difficulty">Choose difficulty level:</label>
<select name="difficulty" id="difficulty_setting" onchange=" setDifficulty(this.value)">
<option value="Easy" >Easy</option>
<option value="Medium">Medium</option>
<option value="Hard">Hard</option>
</select>
comment this as its not needed anymore
// var diff_setting = document.getElementById('difficulty_setting');
and correct this :
let medium_game = random_words.filter((med_words) => {
if(med_words.length <= 9 && med_words.length>=6){
return med_words;}});
as it was also selecting words that are both medium and easy
also the randomWord function used to select a word from the unfiltered array not the new one you created so it would look like this :
function randomWord() {
var arr = getSelection();
answer = arr[Math.floor(Math.random() * arr.length - 1)];
}
and finally getSelection() should look like this :
function getSelection(){
// select difficulty
//var selection = diff_setting;
let easy_game = random_words.filter((easy_words) => {
if(easy_words.length < 6){
return easy_words;}});
let medium_game = random_words.filter((med_words) => {
if(med_words.length <= 9 && med_words.length>6){
return med_words;}});
let hard_game = random_words.filter((hard_words) => {
if(hard_words.length > 9){
return hard_words;}});
alert(diff_setting);
if(diff_setting == 'Easy'){
return easy_game;
} else if (diff_setting == 'Medium'){
return medium_game;
} else if(diff_setting == 'Hard'){
return hard_game;}
}
now it should work fine :)
Related
Javascript click and open new div
what I'm trying to do for a long time is that; how can I open or create a new window using js button click. Example, I'm going to provide my simple quiz app code. I want to add a new button named "Start". If anyone click the button "Start", the quiz will be start. And the "Start" button will remove. I've added a simple button for this purpose, but not removing the button after click "Start" button. How can I do it ? My code example: $("#start-quiz").click(function(){ const rand = n => Math.floor(Math.random() * n), swap = (t, i, j) => { let q = t[i]; t[i] = t[j]; t[j] = q; return t; }, shuffle = (arr = []) => { let copy = arr.slice(0, 2), last = copy.length, n; while (last > 0) { n = rand(last); swap(copy, n, --last); } return copy; }; var total_seconds = 1220 * 1; var c_minutes = parseInt(total_seconds / 60); var c_seconds = parseInt(total_seconds % 60); var timer; function CheckTime() { document.getElementById("quiz-time-left1").innerHTML = '<i class="fa fa-clock-o"></i> ' + c_minutes + 'm' + ':' + c_seconds + 's'; if (total_seconds <= 0) { score(); } else { total_seconds = total_seconds - 1; c_minutes = parseInt(total_seconds / 60); c_seconds = parseInt(total_seconds % 60); timer = setTimeout(CheckTime, 1000); } } timer = setTimeout(CheckTime, 1000); const quizData = [{ question: "Which language runs in a web browser?", a: "Java", b: "C", c: "Python", d: "JavaScript", correct: "d", }, { question: "What does CSS stand for?", a: "Central Style Sheets", b: "Cascading Style Sheets", c: "Cascading Simple Sheets", d: "Cars SUVs Sailboats", correct: "b", }, { question: "What does HTML stand for?", a: "Hypertext Markup Language", b: "Hypertext Markdown Language", c: "Hyperloop Machine Language", d: "Helicopters Terminals Motorboats Lamborginis", correct: "a", }, { question: "What year was JavaScript launched?", a: "1996", b: "1995", c: "1994", d: "none of the above", correct: "b", }, ]; const quiz = document.getElementById("quiz"); const answerElements = document.querySelectorAll(".answer"); const questionElement = document.getElementById("question"); const a_text = document.getElementById("a_text"); const b_text = document.getElementById("b_text"); const c_text = document.getElementById("c_text"); const d_text = document.getElementById("d_text"); const submitButton = document.getElementById("submit"); const randomizedQuestions = shuffle(quizData).slice(0, 10); let currentQuestion = 0; let score = 0; const deselectAnswers = () => { answerElements.forEach((answer) => (answer.checked = false)); }; const getSelected = () => { let answer; answerElements.forEach((answerElement) => { if (answerElement.checked) answer = answerElement.id; }); return answer; }; const loadQuestion = () => { deselectAnswers(); const currentQuestionData = randomizedQuestions[currentQuestion]; questionElement.innerText = currentQuestionData.question; a_text.innerText = currentQuestionData.a; b_text.innerText = currentQuestionData.b; c_text.innerText = currentQuestionData.c; d_text.innerText = currentQuestionData.d; }; loadQuestion(); submitButton.addEventListener("click", () => { const answer = getSelected(); if (answer) { if (answer === randomizedQuestions[currentQuestion].correct) score++; currentQuestion++; let asd = randomizedQuestions.length - score; let ssrate = (1220 - Math.floor(total_seconds)); let ggg = ""; if (ssrate < 12) ggg = "good morning"; else if (ssrate < 16) ggg = "ghfgdfgh ning"; else if (ssrate < 24) ggg = "asaasasasa ng"; let avg = Math.round(score * 100 / randomizedQuestions.length); document.getElementById("myProgress").value = avg; if (currentQuestion < randomizedQuestions.length) loadQuestion(); else { // stop timer clearInterval(timer); quiz.innerHTML = "<h2>Total Question : " + quizData.length + "<br>" + "Correct Ans : " + score + " <br> Wrong Ans : " + asd + " <br> Average : " + avg + " % <br> Time Usage : " + ssrate + " Seconds <br> Average : " + ggg + " % <br><br> <br><br> <button class='mi-ripple mi-ripple-light' onclick='location.reload()'>Play Again</button></h2>" } } }); }); * { box-sizing: border-box; } body { background-color: #b8c6db; background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 100%); font-family: "Poppins", sans-serif; margin: 0; } .quiz-container { background-color: #fff; border-radius: 10px; box-shadow: 0 0 10px 2px rgba(100, 100, 100, 0.1); width: 600px; max-width: 95vw; overflow: hidden; } .quiz-header { padding: 4rem; } h2 { padding: 1rem; text-align: center; margin: 0; } ul { list-style-type: none; padding: 0; } ul li { font-size: 1.2rem; margin: 1rem 0; } ul li label { cursor: pointer; } button { background-color: #8e44ad; color: #fff; border: none; display: block; width: 100%; font-size: 1.1rem; font-family: inherit; padding: 1.3rem; } button:hover { background-color: #732d91; } button:focus { outline: none; background-color: #5e3370; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <button id="start-quiz"> Start </button> <div class="quiz-container" id="quiz"> <div class="quiz-header"> <h2 id="question">Question is loading...</h2> <div class="mi-center" id="quiz-time-left1" ></div> <ul> <li> <input type="radio" name="answer" id="a" class="answer" /> <label for="a" id="a_text">Answer...</label> </li> <li> <input type="radio" name="answer" id="b" class="answer" /> <label for="b" id="b_text">Answer...</label> </li> <li> <input type="radio" name="answer" id="c" class="answer" /> <label for="c" id="c_text">Answer...</label> </li> <li> <input type="radio" name="answer" id="d" class="answer" /> <label for="d" id="d_text">Answer...</label> </li> </ul> </div> <button id="submit" class="mi-ripple mi-ripple-light" >Submit</button> </div> <progress id='myProgress' value='' max='100'> To sum up, I want like that image: . When anyone will click on start button, the quiz will start. Like that:
$("#start-quiz").click(function(){ // add class to quiz-container to show quiz container $("#quiz").addClass("active"); // add class to start-quiz to hide start button $("#start-quiz").addClass("active"); const rand = n => Math.floor(Math.random() * n), swap = (t, i, j) => { let q = t[i]; t[i] = t[j]; t[j] = q; return t; }, shuffle = (arr = []) => { let copy = arr.slice(0, 2), last = copy.length, n; while (last > 0) { n = rand(last); swap(copy, n, --last); } return copy; }; var total_seconds = 1220 * 1; var c_minutes = parseInt(total_seconds / 60); var c_seconds = parseInt(total_seconds % 60); var timer; function CheckTime() { document.getElementById("quiz-time-left1").innerHTML = '<i class="fa fa-clock-o"></i> ' + c_minutes + 'm' + ':' + c_seconds + 's'; if (total_seconds <= 0) { score(); } else { total_seconds = total_seconds - 1; c_minutes = parseInt(total_seconds / 60); c_seconds = parseInt(total_seconds % 60); timer = setTimeout(CheckTime, 1000); } } timer = setTimeout(CheckTime, 1000); const quizData = [{ question: "Which language runs in a web browser?", a: "Java", b: "C", c: "Python", d: "JavaScript", correct: "d", }, { question: "What does CSS stand for?", a: "Central Style Sheets", b: "Cascading Style Sheets", c: "Cascading Simple Sheets", d: "Cars SUVs Sailboats", correct: "b", }, { question: "What does HTML stand for?", a: "Hypertext Markup Language", b: "Hypertext Markdown Language", c: "Hyperloop Machine Language", d: "Helicopters Terminals Motorboats Lamborginis", correct: "a", }, { question: "What year was JavaScript launched?", a: "1996", b: "1995", c: "1994", d: "none of the above", correct: "b", }, ]; const quiz = document.getElementById("quiz"); const answerElements = document.querySelectorAll(".answer"); const questionElement = document.getElementById("question"); const a_text = document.getElementById("a_text"); const b_text = document.getElementById("b_text"); const c_text = document.getElementById("c_text"); const d_text = document.getElementById("d_text"); const submitButton = document.getElementById("submit"); const randomizedQuestions = shuffle(quizData).slice(0, 10); let currentQuestion = 0; let score = 0; const deselectAnswers = () => { answerElements.forEach((answer) => (answer.checked = false)); }; const getSelected = () => { let answer; answerElements.forEach((answerElement) => { if (answerElement.checked) answer = answerElement.id; }); return answer; }; const loadQuestion = () => { deselectAnswers(); const currentQuestionData = randomizedQuestions[currentQuestion]; questionElement.innerText = currentQuestionData.question; a_text.innerText = currentQuestionData.a; b_text.innerText = currentQuestionData.b; c_text.innerText = currentQuestionData.c; d_text.innerText = currentQuestionData.d; }; loadQuestion(); submitButton.addEventListener("click", () => { $("#myProgress").addClass("active"); const answer = getSelected(); if (answer) { if (answer === randomizedQuestions[currentQuestion].correct) score++; currentQuestion++; let asd = randomizedQuestions.length - score; let ssrate = (1220 - Math.floor(total_seconds)); let ggg = ""; if (ssrate < 12) ggg = "good morning"; else if (ssrate < 16) ggg = "ghfgdfgh ning"; else if (ssrate < 24) ggg = "asaasasasa ng"; let avg = Math.round(score * 100 / randomizedQuestions.length); if (currentQuestion < randomizedQuestions.length) loadQuestion(); else { // stop timer clearInterval(timer); quiz.innerHTML = "<h2>Total Question : " + quizData.length + "<br>" + "Correct Ans : " + score + " <br> Wrong Ans : " + asd + " <br> Average : " + avg + " % <br> Time Usage : " + ssrate + " Seconds <br> Average : " + ggg + " % <br><br> <br><br> <button class='mi-ripple mi-ripple-light' onclick='location.reload()'>Play Again</button></h2><progress id='myProgress' value='"+avg+"' max='100'>" } } }); }); * { box-sizing: border-box; } body { background-color: #b8c6db; background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 100%); font-family: "Poppins", sans-serif; margin: 0; } .quiz-container { background-color: #fff; border-radius: 10px; box-shadow: 0 0 10px 2px rgba(100, 100, 100, 0.1); width: 600px; max-width: 95vw; overflow: hidden; display:none; } .quiz-container.active{ display:block; } .quiz-header { padding: 4rem; } h2 { padding: 1rem; text-align: center; margin: 0; } ul { list-style-type: none; padding: 0; } ul li { font-size: 1.2rem; margin: 1rem 0; } ul li label { cursor: pointer; } button { background-color: #8e44ad; color: #fff; border: none; display: block; width: 100%; font-size: 1.1rem; font-family: inherit; padding: 1.3rem; } button:hover { background-color: #732d91; } button:focus { outline: none; background-color: #5e3370; } #start-quiz.active{ display:none; } #myProgress{ width:100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <button id="start-quiz"> Start </button> <div class="quiz-container" id="quiz"> <div class="quiz-header"> <h2 id="question">Question is loading...</h2> <div class="mi-center" id="quiz-time-left1" ></div> <ul> <li> <input type="radio" name="answer" id="a" class="answer" /> <label for="a" id="a_text">Answer...</label> </li> <li> <input type="radio" name="answer" id="b" class="answer" /> <label for="b" id="b_text">Answer...</label> </li> <li> <input type="radio" name="answer" id="c" class="answer" /> <label for="c" id="c_text">Answer...</label> </li> <li> <input type="radio" name="answer" id="d" class="answer" /> <label for="d" id="d_text">Answer...</label> </li> </ul> </div> <button id="submit" class="mi-ripple mi-ripple-light" >Submit</button> </div>
$("#start-quiz").click(function(){ const thisElement = document.getElementById("start-quiz") thisElement.remove() ....... }
How to achieve camera switch function, and use it in later recognition?
I am doing a project to use the webcam at phone or laptop to do the object recognition. Right now I can get the camera id and object recognition, but I can't switch the video source to the camera that I want. Could someone please help me or give me some hints that how I can select the camera I want, and then use it to do the object recognition? Thanks a lot! var classifier; var resultsP; var msg1; var prevmsg; var video const button = document.getElementById('button'); const select = document.getElementById('select'); let currentStream; function voice_testing(){ var voice_message = "Voice triggered"; var message = new SpeechSynthesisUtterance(voice_message); window.speechSynthesis.speak(message); } function setup() { noCanvas(); video = createCapture(VIDEO); classifier = ml5.imageClassifier('MobileNet', video, modelReady); resultsP = createP('Loading model and video...'); } function modelReady() { console.log('Model Ready'); classifyVideo(); } function classifyVideo() { classifier.classify(gotResult); } async function gotResult(err, results) { resultsP.html(results[0].label + ' ' + nf(results[0].confidence, 0, 2)); if(nf(results[0].confidence, 0, 2) > 0.2){ if(results[0].label != prevmsg){ msg1 = new SpeechSynthesisUtterance(results[0].label); msg2 = results[0].label.split(','); window.speechSynthesis.speak(msg1); Text = msg2[0]; letters = Text.split(''); letters1 = new SpeechSynthesisUtterance(letters); window.speechSynthesis.speak(letters1); prevmsg = results[0].label; } } setTimeout(classifyVideo, 8000); } function stopMediaTracks(stream) { stream.getTracks().forEach(track => { track.stop(); }); } function gotDevices(mediaDevices) { select.innerHTML = ''; select.appendChild(document.createElement('option')); let count = 1; mediaDevices.forEach(mediaDevice => { if (mediaDevice.kind === 'videoinput') { const option = document.createElement('option'); option.value = mediaDevice.deviceId; const label = mediaDevice.label || `Camera ${count++}`; const textNode = document.createTextNode(label); option.appendChild(textNode); select.appendChild(option); } }); } button.addEventListener('click', event => { if (typeof currentStream !== 'undefined') { stopMediaTracks(currentStream); } const videoConstraints = {}; if (select.value === '') { videoConstraints.facingMode = 'environment'; } else { videoConstraints.deviceId = { exact: select.value }; } const constraints = { video: videoConstraints, audio: false }; navigator.mediaDevices .getUserMedia(constraints) .then(stream => { currentStream = stream; video.srcObject = stream; return navigator.mediaDevices.enumerateDevices(); }) .then(gotDevices) .catch(error => { console.error(error); }); }); navigator.mediaDevices.enumerateDevices().then(gotDevices); body{ text-align: center; } h1 { font-size: 40px; font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; } p { font-size: 20px; font-family: Arial, Helvetica, sans-serif; } .startButton { font-size: 12px; text-align: center; margin: 1%; } <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>Camera selection</title> <link rel="stylesheet" href="./app.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script> <script src="https://unpkg.com/ml5#0.4.3/dist/ml5.min.js" type="text/javascript"></script> </head> <body> <header> <h1>Webcam Object Recognition</h1> </header> <main> <button id="button">Get camera</button> <select id="select"> <option></option> </select> <button id="startButtonID" onclick="voice_testing();">Voice Testing</button> </br> <p>If no voice, click the button</p> <p>You can select the camera you want from the box above, and click get camera button</p> </main> <script src="./app.js"></script> </body> </html> ks a lot!
HTML Input doesn't allow double digits to be typed in from keyboard
I'm making a basic calculator and so far it "works". Users can only enter in a single digit from their keyboard. If they want to use double digits they're going to have to use the arrows in the text box. How can I make it so that users can enter in double digit numbers? If the user tries to type in double digit numbers the second number only get stored (so typing in 25 will only store 5) // Base Variables let result = 0; let numb1 = 0; let numb2 = 0; let firstNumberEntered = false; //This will be rewritten let calculationDescription = `${numb1} + ${numb2}`; document.querySelector('#input-number').addEventListener('keypress', numbersInput); function numbersInput(e) { if (!firstNumberEntered && e.key === 'Enter') { numb1 = document.getElementById("input-number").value; firstNumberEntered = true; document.getElementById("input-number").innerHTML = ""; } else if (firstNumberEntered && e.key === 'Enter') { numb2 = document.getElementById("input-number").value; firstNumberEntered = false; console.log(`${numb1} and ${numb2}`); } document.getElementById("input-number").value = ""; } document.querySelector("#btn-add").addEventListener('click', sumNumbs); document.querySelector("#btn-subtract").addEventListener('click', subtractNumbs); document.querySelector("#btn-multiply").addEventListener('click', multiplyNumbs); document.querySelector("#btn-divide").addEventListener('click', divideNumbs); function sumNumbs() { let numb1Final = parseInt(numb1); let numb2Final = parseInt(numb2); result = numb1Final + numb2Final; calculationDescription = `${numb1} + ${numb2}`; outputResult(result, calculationDescription); } function subtractNumbs() { let numb1Final = parseInt(numb1); let numb2Final = parseInt(numb2); result = numb1Final - numb2Final; calculationDescription = `${numb1} - ${numb2}`; outputResult(result, calculationDescription); } function multiplyNumbs() { let numb1Final = parseInt(numb1); let numb2Final = parseInt(numb2); result = numb1Final * numb2Final; calculationDescription = `${numb1} x ${numb2}`; outputResult(result, calculationDescription); } function divideNumbs() { let numb1Final = parseInt(numb1); let numb2Final = parseInt(numb2); result = numb1Final / numb2Final; calculationDescription = `${numb1} / ${numb2}`; outputResult(result, calculationDescription); } <section id="calculator"> <input type="number" id="input-number" /> <div id="calc-actions"> <button type="button" id="btn-add">+</button> <button type="button" id="btn-subtract">-</button> <button type="button" id="btn-multiply">*</button> <button type="button" id="btn-divide">/</button> </div> </section> All this does is grab the elements on the HTML page and put them into variables and send info back to be displayed const userInput = document.getElementById('input-number'); const addBtn = document.getElementById('btn-add'); const subtractBtn = document.getElementById('btn-subtract'); const multiplyBtn = document.getElementById('btn-multiply'); const divideBtn = document.getElementById('btn-divide'); const currentResultOutput = document.getElementById('current-result'); const currentCalculationOutput = document.getElementById('current-calculation'); function outputResult(result, text) { currentResultOutput.textContent = result; currentCalculationOutput.textContent = text; } Not sure if providing my CSS is necessary, but let me know and I'll make a change. I just started learning JavaScript recently. I watched a few videos on a Udemy tutorial on doing this project, but I stopped watching and tried to figure the rest out myself. What I did try doing was adding maxlength="6" to my HTML input element, but that didn't work.
function numbersInput(e) { if(!firstNumberEntered && e.key === 'Enter') { numb1 = document.getElementById("input-number").value; firstNumberEntered = true; document.getElementById("input-number").innerHTML = ""; document.getElementById("input-number").value = ""; } else if(firstNumberEntered && e.key === 'Enter') { numb2 = document.getElementById("input-number").value; firstNumberEntered = false; console.log(`${numb1} and ${numb2}`); document.getElementById("input-number").value = ""; } } Add document.getElementById("input-number").value = ""; to the end of both if statements and remove from the end of the function
Here's my own basic calculator using HTML, CSS, and javascript only. To be able to input one or more digit numbers, use arrays to function as storage of those numbers chosen and for your chosen arithmetic operation as well. please see my source code for a clearer grasp of my idea. //index.html <!DOCTYPE html> <html> <head> <title>My HTML/CSS/JS Calculator</title> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body> <div class="outer-container"> <div class="items" id="items"></div> <div class="calc-screen"> <div id="screen"></div> </div> <div class="keys-container"> <button type="button" class="keys" id="opm" onclick="opm()">*</button> <button type="button" class="keys" id="opd" onclick="opd()">/</button> <button type="button" class="keys" id="opa" onclick="opa()">+</button> <button type="button" class="keys" id="ops" onclick="ops()">-</button> <button type="button" class="keys" id="num9" onclick="num9()">9</button> <button type="button" class="keys" id="num8" onclick="num8()">8</button> <button type="button" class="keys" id="num7" onclick="num7()">7</button> <button type="button" class="keys" id="num6" onclick="num6()">6</button> <button type="button" class="keys" id="num5" onclick="num5()">5</button> <button type="button" class="keys" id="num4" onclick="num4()">4</button> <button type="button" class="keys" id="num3" onclick="num3()">3</button> <button type="button" class="keys" id="num2" onclick="num2()">2</button> <button type="button" class="keys" id="num1" onclick="num1()">1</button> <button type="button" class="keys" id="num0" onclick="num0()">0</button> <button type="button" class="keys" id="del" onclick="del()">Del</button> <button type="button" class="keys" id="clr" onclick="clr()">Clr</button> <button type="submit" class="keys" id="equals" onclick='equals()'>=</button> </div> </div> <script type="text/javascript" src="js/js.js"></script> </body> </html> //js.js var item1, op, item2, arr1, arr2, text, x, prod, qout, sum, diff, a, b, c; item1, item2, op = ''; arr1 = []; arr2 = []; function num9() { if (op=='') { arr1.push(document.getElementById("num9").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num9").innerHTML); arr2Function(); } } function num8() { if (op=='') { arr1.push(document.getElementById("num8").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num8").innerHTML); arr2Function(); } } function num7() { if (op=='') { arr1.push(document.getElementById("num7").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num7").innerHTML); arr2Function(); } } function num6() { if (op=='') { arr1.push(document.getElementById("num6").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num6").innerHTML); arr2Function(); } } function num5() { if (op=='') { arr1.push(document.getElementById("num5").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num5").innerHTML); arr2Function(); } } function num4() { if (op=='') { arr1.push(document.getElementById("num4").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num4").innerHTML); arr2Function(); } } function num3() { if (op=='') { arr1.push(document.getElementById("num3").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num3").innerHTML); arr2Function(); } } function num2() { if (op=='') { arr1.push(document.getElementById("num2").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num2").innerHTML); arr2Function(); } } function num1() { if (op=='') { arr1.push(document.getElementById("num1").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num1").innerHTML); arr2Function(); } } function num0() { if (op=='') { arr1.push(document.getElementById("num0").innerHTML); arr1Function(); } else { arr2.push(document.getElementById("num0").innerHTML); arr2Function(); } } function opm() { if (arr1=='') { document.getElementById("screen").innerHTML = "Please press a number first!"; } else if (op!='' && arr2!='') { console.log("press equal sign"); } else { document.getElementById("screen").innerHTML = document.getElementById("opm").innerHTML; op = '*'; console.log(op); } } function opd() { if (arr1=='') { document.getElementById("screen").innerHTML = "Please press a number first!"; } else if (op!='' && arr2!='') { console.log("press equal sign"); } else { document.getElementById("screen").innerHTML = document.getElementById("opd").innerHTML; op = '/'; console.log(op); } } function opa() { if (arr1=='') { document.getElementById("screen").innerHTML = "Please press a number first!"; } else if (op!='' && arr2!='') { console.log("press equal sign"); } else { document.getElementById("screen").innerHTML = document.getElementById("opa").innerHTML; op = '+'; console.log(op); } } function ops() { if (arr1=='') { document.getElementById("screen").innerHTML = "Please press a number first!"; } else if (op!='' && arr2!='') { console.log("press equal sign"); } else { document.getElementById("screen").innerHTML = document.getElementById("ops").innerHTML; op = '-'; console.log(op); } } function equals() { a = parseInt(item1); b = parseInt(item2); if (op == '*') { prod = a * b; document.getElementById("items").innerHTML = a+' '+op+' '+b+' ='; c = prod; document.getElementById("screen").innerHTML = c; console.log('product: '+c); result(c); } else if (op == '/') { qout = a / b; document.getElementById("items").innerHTML = a+' '+op+' '+b+' ='; c = qout; document.getElementById("screen").innerHTML = c; console.log('qoutient: '+c); result(c); } else if (op == '+') { sum = a + b; document.getElementById("items").innerHTML = a+' '+op+' '+b+' ='; c = sum; document.getElementById("screen").innerHTML = c; console.log('sum: '+c); result(c); } else if (op == '-') { diff = a - b; document.getElementById("items").innerHTML = a+' '+op+' '+b+ ' ='; c = diff; document.getElementById("screen").innerHTML = c; console.log('difference: '+c); result(c); } else { document.getElementById("screen").innerHTML = "Please press a number first!"; } } function result() { console.log('function result: '+c); arr1=[]; arr2=[]; item1, item2, op = ''; item1 = c; console.log('function result new item1: '+item1); arr1.push(item1); arr1Function(); } function del() { if (arr1!='' && op=='' && arr2=='') { arr1.pop(); console.log(arr1); arr1Function(); } else if (arr1!='' && op!='' && arr2=='') { op = ''; document.getElementById("screen").innerHTML = op; } else if (arr1!='' && op!='' && arr2!='') { arr2.pop(); console.log(arr2); arr2Function(); } } function clr() { arr1=[]; arr2=[]; item1,item2,op=''; console.log(arr1+', '+op+', '+arr2+', '+item1+', '+item2); document.getElementById("screen").innerHTML = ''; document.getElementById("items").innerHTML = ''; } function arr1Function() { document.getElementById("screen").innerHTML = arr1; text = ""; arr1.forEach(myFunction); text += ""; function myFunction(value) { text += value; x = parseInt(text); document.getElementById("screen").innerHTML = x; item1 = x; console.log("Arr 1 Parse: "+x); console.log("Arr 1: "+arr1); console.log("Item 1: "+item1); } } function arr2Function() { document.getElementById("screen").innerHTML = arr2; text = ""; arr2.forEach(myFunction); text += ""; function myFunction(value) { text += value; x = parseInt(text); document.getElementById("screen").innerHTML = x; item2 = x; console.log("Arr 2 Parse: "+x); console.log("Arr 2: "+arr2); console.log("Item 2: "+item2); } } //css body { background-color: orange; } .outer-container { position: static; background-color: black; margin: auto; border: solid black 2px; width: 350px; padding: 20px; box-sizing: border-box; border-radius: 20px; } .items { background-color: silver; border: solid white 1px; display: inline-block; color: black; max-width: 100%; font-size: 16px; height: 20px; box-sizing: border-box; } .calc-screen { padding: 10px; border: solid white 1px; max-width: 100%; width: 100%; height: 50px; background-color: silver; color: white; font-size: 25px; box-sizing: border-box; overflow-x: auto; } .keys-container { margin-top: 20px; width: 100%; border: solid white 1px; max-width: 100%; display: inline-block; } #equals { width: 100%; } .keys { float: left; border: solid black 1px; box-sizing: border-box; width: 25%; height: 40px; box-sizing: border-box; text-align: center; margin: auto; font-size: 25px; padding: 5px; } .keys:hover { background-color: blue; color: white; }
Sort following information by Id or by Name and display it
I have following code : <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <style> .content{ border: 1px solid gray; width: 250px; padding: 5px; margin : 10px; } .name{ font-size: 18px; font-weight: 600; color: #efa520; padding: 2px; } .ids{ padding: 2px; color: #1b8ac1; } </style> </head> <body> <span>Sort By :</span> <span> <select id="sortBy" style="width:80px;" onchange="sortEmp();"> <option value="id">Id <option value="name">Name </select> </span> <div class="container"> </div> <script> var data = {"employees": [ {"208880097" :{"name":"John Doe"}}, {"219087644" : {"name":"Anna Smith"}}, {"980017672" : {"name":"Peter Jones"}}, {"203459867" : {"name":"Christopher Brown"}} ]}; var empData = data.employees; for(var empId in empData){ var empInfo = empData[empId]; for(var id in empInfo){ var info = empInfo[id]; var name = info.name; $(".container").append('<div class="content"><span class="name">'+name+'</span><br><span class="ids">'+id+'</span><br></div>') } } function sortEmp(){ var sort = $("#sortBy").val(); if(sort == "name"){ sortByName(); }else{ sortById(); } } </script> </body> </html> So I want to sort this information by id or by name on changing select option and according to that dispaly sorted data on view. There is one option 'Sort By' at the top, so after changing select option 'sortEmp()' function get called, and sorting will be done. So please help me for the same.
I wrote this method which will sort your data function sortEmployees(asc, resolver) { empData = empData.sort(function(a, b) { a = resolver(a), b = resolver(b) if (asc) return (a > b) ? 1 : ((a < b) ? -1 : 0) else return (b > a) ? 1 : ((b< a) ? -1 : 0) }) } the first parameter true or false sets ascending or descending order. The second parameter is a function (in my example, for ease of use, a lamda), this function has to return the property by which the list should be sorted. // sort by id - `Object.keys(o)[0]` returns the id sortEmployees(true, o => Object.keys(o)[0] ) // sort by name- `o[Object.keys(o)[0]].name` returns the name sortEmployees(true, o => o[Object.keys(o)[0]].name ) Example var data = { "employees": [{ "208880097": { "name": "John Doe" } }, { "219087644": { "name": "Anna Smith" } }, { "980017672": { "name": "Peter Jones" } }, { "203459867": { "name": "Christopher Brown" } }] } var empData = data.employees; function displayEmployees() { $(".container").html('') for (var empId in empData) { var empInfo = empData[empId]; for (var id in empInfo) { var info = empInfo[id]; var name = info.name; $(".container").append('<div class="content"><span class="name">' + name + '</span><br><span class="ids">' + id + '</span><br></div>') } } } function sortEmp() { var sort = $("#sortBy").val() if (sort == "name") { sortEmployees(true, o => o[Object.keys(o)[0]].name ) displayEmployees() } else { sortEmployees(true, o => Object.keys(o)[0] ) displayEmployees() } } function sortEmployees(asc, resolver) { empData = empData.sort(function(a, b) { a = resolver(a), b = resolver(b) if (asc) return (a > b) ? 1 : ((a < b) ? -1 : 0) else return (b > a) ? 1 : ((b< a) ? -1 : 0) }) } sortEmp() .content { border: 1px solid gray; width: 250px; padding: 5px; margin: 10px; } .name { font-size: 18px; font-weight: 600; color: #efa520; padding: 2px; } .ids { padding: 2px; color: #1b8ac1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <span>Sort By :</span> <span> <select id="sortBy" style="width:80px;" onchange="sortEmp();"> <option value="id">Id <option value="name">Name </select> </span> <div class="container"> </div>
Error during checkout with VISA card
I'm completely new nopCommerce. One of my client is getting error during check out with VISA card. He is getting the following screen. I'm not sure where do I start to troubleshoot. Can you please help me? Some how I'm not able to post exact HTML document. But please consider below code as properly formatted HTML. <script type="text/javascript"> (function (f, b) { if (!b.__SV) { var a, e, i, g; window.mixpanel = b; b._i = []; b.init = function (a, e, d) { function f(b, h) { var a = h.split("."); 2 == a.length && (b = b[a[0]], h = a[1]); b[h] = function () { b.push([h].concat(Array.prototype.slice.call(arguments, 0))) } } var c = b; "undefined" !== typeof d ? c = b[d] = [] : d = "mixpanel"; c.people = c.people || []; c.toString = function (b) { var a = "mixpanel"; "mixpanel" !== d && (a += "." + d); b || (a += " (stub)"); return a }; c.people.toString = function () { return c.toString(1) + ".people (stub)" }; i = "disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" "); for (g = 0; g < i.length; g++) f(c, i[g]); b._i.push([a, e, d]) }; b.__SV = 1.2; a = f.createElement("script"); a.type = "text/javascript"; a.async = !0; a.src = "//cdn.mxpnl.com/libs/mixpanel-2.2.min.js"; e = f.getElementsByTagName("script")[0]; e.parentNode.insertBefore(a, e) } })(document, window.mixpanel || []); var mode = 'prd'.toLowerCase(); var token = ''; if (mode == 'demo') { token = 'xxxxxxxxxxxxxxxxxxxxxx'; } else if (mode == 'prd' || mode == 'prda' || mode == 'prdk') { token = 'xxxxxxxxxxxxxxxxxxxxxx'; } else if (mode == 'test') { token = 'xxxxxxxxxxxxxxxxxxx'; } else { token = 'xxxxxxxxxxxxxxxxxxxxxxxxx'; } if (token != '') { mixpanel.init(token, { persistence: 'localStorage' }); } </script><!-- end Mixpanel --> <script type="text/javascript"> if (self !== top && typeof mixpanel !== "undefined") { mixpanel.track("inFrame", { "merchant_id": "XXXX(actual number here)", "tid": "XXXX(actual number here)" }); } </script> <style type="text/css"> BODY, TD, INPUT, SELECT, TEXTAREA, BUTTON, .normal { font-family: arial,helvetica,sans-serif; font-size: 10pt; font-weight: normal; } .small { font-size: 10pt; } .medium { font-size: 14pt; } .large { font-size: 18pt; } </style> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <!-- process-transaction-response --> <html> <head> <meta http-equiv="refresh" content="1;url=http://www.myvirtualmerchant.com? ssl_approval_code=++++++& ssl_cvv2_response=& ssl_exp_date=XXXX(actual number here)& ssl_account_balance=0.00& ssl_get_token=& ssl_token=& ssl_departure_date=& ssl_token_response=& ssl_result_message=DECLINED& ssl_invoice_number=XXXX(actual number here)& ssl_description=Name1+Name2& ssl_amount=184.48& ssl_txn_id=GUID& ssl_result=1& ssl_card_number=XXXX(actual number here)& ssl_completion_date=& ssl_txn_time=10%2F28%2F2016+04%3A03%3A18+PM& ssl_avs_response=G"> <style type="text/css"> BODY, TD, INPUT, SELECT, TEXTAREA, BUTTON, .normal { font-family: arial,helvetica,sans-serif; font-size: 10pt; font-weight: normal; } .small { font-size: 10pt; } .medium { font-size: 14pt; } .large { font-size: 18pt; } </style> </head> <form name="frmMenu" action="#" method="POST"> <input type="hidden" name="dispatchMethod" /> <input type="hidden" name="permissionDesc" /> <input type="hidden" name="menuAction" /> <input type="hidden" name="thClientID" value="" /> </form> <!-- start Mixpanel --> </body> </html>