Show images in quiz javascript - javascript

I'm trying to create a quiz that tests users awareness of real and fake emails. What I want to do is have the question displayed at the top saying "Real or Fake", then have an image displayed underneath which the user needs to look at to decided if it's real or fake. There are two buttons, real and fake, and regardless of whether they choose the right answer I want to swap the original image with annotated version - showing how users could spot that it was fake or real.
But I'm not sure how to show the annotated version once the answer has been submitted. Could someone help?
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("<img src= 'netflix_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'dropbox_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'gov_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'paypal_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'gmail.jpg' />", ["Real", "Fake"], "Fake")
];
//create quiz
var quiz = new Quiz(questions);
// display
populate();
body {
background-color: #538a70;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border: 2px solid #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
font-size: 60px;
text-align: center;
color: #000000;
padding: 2px 0px;
}
#score {
color: #000000;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #000000;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #a0a0a0;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #00994d;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<div class="grid">
<div id="quiz">
<h1>Can you spot the fake email?</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>

When user clicks button I trigger class and I add it second name, on second I have written to get swapped, I wrote you basically full project, and please read the whole comments, to understand logic
//Calling Elements from DOM
const button = document.querySelectorAll(".check");
const images = document.querySelectorAll(".image");
const answer = document.querySelector("h1");
//Declaring variable to randomly insert any object there to insert source in DOM Image sources
let PreparedPhotos;
//Our Images Sources and With them are its fake or not
//fake: true - yes its fake
//fake: false - no its real
const image = [
[
{
src:
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1200px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg",
fake: true
},
{
src:
"http://graphics8.nytimes.com/images/2012/04/13/world/europe/mona-lisa-like-new-images/mona-lisa-like-new-images-custom4-v3.jpg",
fake: false
}
],
[
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/Creacion_de_Adan__Miguel_Angel_f5adb235-bfa8-4caa-8ffb-c5328cbad953_grande.jpg?12799626327330268216",
fake: false
},
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/First-image_Fb-size_grande.jpg?10773543754915177139",
fake: true
}
]
];
//Genrating Random Photo on HTML
function setRandomPhoto() {
//Random Number which will be length of our array of Object
//if you array includes 20 object it will generate random number
// 0 - 19
const randomNumber = Math.floor(Math.random() * image.length);
//Decalaring our already set variable as Array Object
PreparedPhoto = image[randomNumber];
//Our first DOM Image is Variables first object source
images[0].src = PreparedPhoto[0].src;
//and next image is next object source
images[1].src = PreparedPhoto[1].src;
}
//when windows successfully loads, up function runs
window.addEventListener("load", () => {
setRandomPhoto();
});
//buttons click
//forEach is High Order method, basically this is for Loop but when you want to
//trigger click use forEach - (e) is single button whic will be clicked
button.forEach((e) => {
e.addEventListener("click", () => {
//decalring variable before using it
let filtered;
//finding from our DOM image source if in our long array exists
//same string or not as Image.src
//if it exists filtered variable get declared with that found obect
for (let i = 0; i < image.length; i++) {
for (let k = 0; k < 2; k++) {
if (image[i][k].src === images[0].src) {
filtered = image[i][k];
}
}
}
//basic if else statement, if clicked button is Fake and image is true
//it outputs You are correct
//if clicked button is Real and Image is false it outputs Correct
//Else its false
//Our image checking comes from filtered variable
if (e.innerText === "Fake" && filtered.fake === true) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else if (e.innerText === "Real" && filtered.fake === false) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else {
answer.innerHTML = "You are Wrong";
images.forEach((image) => {
image.classList.toggle("hidden");
});
}
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100%;
min-height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.image-fluid {
display: flex;
}
.image-fluid .image {
width: 200px;
margin: 0 10px;
transition: 0.5s;
}
.image-fluid .image:nth-child(1).hidden {
transform: translateX(110px);
}
.image-fluid .image:nth-child(2).hidden {
transform: translateX(-110px);
}
<div class="container">
<div class="image-fluid">
<img src="" class="image hidden">
<img src="" class="image hidden">
</div>
<div class="button-fluid">
<button class="check">Fake</button>
<button class="check">Real</button>
</div>
</div>
<h1></h1>

Related

using JS to make tic tac toe

I have made a tic tac toe using JS however it has some problems My code is:
let x = [];
let o = [];
let xTurn = false;
let winPat = [
['00', '10', '20'],
['01', '11', '21'],
['02', '12', '22'],
['00', '01', '02'],
['10', '11', '12'],
['20', '21', '22'],
['00', '11', '22'],
['02', '11', '20']
];
const tableR = document.getElementsByClassName('tableR');
const button = document.getElementById('btn')
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
let newElement = document.createElement('td');
tableR.item(i).appendChild(newElement);
newElement.addEventListener('click', () => {
if (elementIsEmpty(newElement)) {
const img = document.createElement('img');
if (xTurn) {
img.src = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ARed_X.svg&psig=AOvVaw1B-fppvlN2x5oSCGllnXGc&ust=1634565535566000&source=images&cd=vfe&ved=0CAkQjRxqFwoTCMjbg6XN0fMCFQAAAAAdAAAAABAD';
x.push(String(i) + String(j))
} else {
img.src = 'https://www.google.com/imgres?imgurl=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2Fd%2Fd0%2FLetter_o.svg%2F407px-Letter_o.svg.png&imgrefurl=https%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ALetter_o.svg&tbnid=p-B77Lz3DDttwM&vet=12ahUKEwizlYTWzdHzAhXMg9gFHTSaBJkQMygAegUIARDaAQ..i&docid=K2HPZsIMOu4d5M&w=407&h=768&q=pixture%20of%20o&ved=2ahUKEwizlYTWzdHzAhXMg9gFHTSaBJkQMygAegUIARDaAQ';
o.push(String(i) + String(j))
}
newElement.append(img)
checkWinOrDraw(xTurn)
xTurn = !xTurn
}
})
}
}
const td = document.getElementsByTagName('td')
button.addEventListener('click', () => {
reset();
});
function elementIsEmpty(el) {
return (/^(\s| )*$/.test(el.innerHTML));
}
function checkWinOrDraw(xTurn) {
for (let i = 0; i < winPat.length; i++) {
if (xTurn) {
if (winPat[i].every(element => x.includes(element))) {
alert('X wins')
reset()
return
}
} else {
if (winPat[i].every(element => o.includes(element))) {
alert('O wins')
reset()
return
}
}
}
for (let item of td) {
if (elementIsEmpty(item))
return
}
alert('Draw')
reset()
}
function reset() {
x = [];
o = [];
for (let item of td) {
item.textContent = ''
}
}
body {
margin: 0px;
background-color: #3c4552;
color: aliceblue;
text-align: center;
}
header {
height: 75px;
background-color: #1f1e1c;
padding: 20px;
font-size: large;
}
table {
border-collapse: collapse;
margin: 40px auto;
}
td {
border: 7px solid black;
height: 121px;
width: 121px;
cursor: pointer;
}
button {
background-color: #1f1e1c;
color: white;
width: 25%;
height: 50px;
font-size: larger;
border: black solid 2px;
border-radius: 7px;
cursor: pointer;
}
img {
display: block;
width: 100%;
height: 100%;
}
<header>
<h1>TicTacToe</h1>
</header>
<main>
<table>
<tr class="tableR"></tr>
<tr class="tableR"></tr>
<tr class="tableR"></tr>
</table>
</main>
<footer>
<button id="btn">RESET</button>
</footer>
my problem is that when the game ends, say X wins, the image is not rendered on the screen, and alert() is called. I googled a lot and found no solutions.
details and clarity:
the image is not rendered on screen at the end of the game. try on your computer and see. alert() is called before the image is present in-game which results in a bad user experience. hence I need a solution.
Here your append() function is not able to complete image load & your checkWinOrDraw() function got called that's why this is happening.
Please try with the below code i am calling the checkWinOrDraw() once image gets loaded or failed.
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
let newElement = document.createElement('td');
tableR.item(i).appendChild(newElement);
newElement.addEventListener('click', () => {
if (elementIsEmpty(newElement)) {
const img = document.createElement('img');
if (xTurn) {
img.src = 'https://dummyimage.com/20x20/3a4ca6/fff';
x.push(String(i) + String(j))
} else {
img.src = 'https://dummyimage.com/30x30/fff/fff';
o.push(String(i) + String(j))
}
console.log(xTurn)
xTurn = !xTurn
img.addEventListener('load', checkWinOrDraw)
img.addEventListener('error', checkWinOrDraw)
newElement.appendChild(img)
}
})
}
}
function checkWinOrDraw(e,xTurn) {
//console.log('checking',xTurn)
for (let i = 0; i < winPat.length; i++) {
if (xTurn) {
if (winPat[i].every(element => x.includes(element))) {
alert('X wins')
reset()
return
}
} else {
if (winPat[i].every(element => o.includes(element))) {
alert('O wins')
reset()
return
}
}
}
for (let item of td) {
if (elementIsEmpty(item))
return
}
alert('Draw')
reset()
}

How to add a button that becomes active after conditions are met js

I continue to make a game on js game "Believe / Don't Believe". Assertion titles appear on the screen one by one. The user responds to each statement in turn. There are 5 statements in total. If the user clicked on the False button then the following statement appears. And if it's true then a description appears. You can go to the next question by clicking on the white circle under the headings, which turns into red if an answer has already been given to it (any), or by clicking on the Next button.
Question:
How do I add a Next button to go to the next question? Until the user has answered the question, it is not active until he gives an answer.
How to add a button that appears after the user answers all the questions (all the balls below are filled)
const data = [
{stmt: "question 1", desc: "text 1"},
{stmt: "question 2", desc: "text 2"},
{stmt: "question 3", desc: "text 3"},
];
let curStmt = 0;
function showStmt(idx) {
document.getElementById('progress-item-' + curStmt).classList.remove('current');
curStmt = idx;
document.getElementById('stmt').innerText = data[idx].stmt;
document.getElementById('desc').innerText = data[idx].desc;
document.getElementById('progress-item-' + idx).classList.add('current');
applyComplete(data[idx].complete);
}
function applyComplete(val) {
val = (val) ? true : false;
document.getElementById('desc').style.visibility = (val) ? 'visible' : 'hidden';
document.getElementById('btnTrue').disabled = val;
document.getElementById('btnFalse').disabled = val;
}
function createProgressBar() {
const parent = document.getElementById('progress');
parent.innerHTML = '';
for (let i = 0; i < data.length; i++) {
const item = document.createElement('div');
item.setAttribute('data-idx', i);
item.id = 'progress-item-' + i;
item.classList.add('item');
if (data[i].complete)
item.classList.add('complete');
parent.appendChild(item);
}
}
function btnClick(val) {
data[curStmt].complete = true;
document.getElementById('progress-item-' + curStmt).classList.add('complete');
if (val || (curStmt === data.length - 1)) {
applyComplete(true);
} else {
showStmt(curStmt + 1);
}
}
document.getElementById('progress').addEventListener(
'click',
function (e) {
if (e.target.classList.contains('item')) {
const newIdx = e.target.getAttribute('data-idx') - 0;
if (newIdx != curStmt) {
showStmt(newIdx);
}
}
},
true
);
createProgressBar();
showStmt(0);
.section {
margin: 10px 0;
}
#progress .item {
height: 10px;
width: 10px;
margin: 0 5px;
border: 2px solid red;
border-radius: 50%;
display: inline-block;
cursor: pointer;
}
#progress .item.current {
border-color: blue;
}
#progress .item.complete {
background-color: green;
}
#progress .item:not(.complete):hover {
background-color: lime;
}
<div class="section">
<div id="stmt"></div>
<div id="desc"></div>
</div>
<div class="section buttons">
<button id="btnTrue" onclick="btnClick(true)">True</button>
<button id="btnFalse" onclick="btnClick(false)">False</button>
<div>
<div id="progress" class="section"></div>
const data = [
{stmt: "question 1", desc: "text 1"},
{stmt: "question 2", desc: "text 2"},
{stmt: "question 3", desc: "text 3"},
];
let curStmt = 0;
let answered =[];
function btnNext() {
console.log('Next button clicked');
document.getElementById('btnTrue').disabled = false;
document.getElementById('btnFalse').disabled = false;
}
function btnAfterComplete() {
console.log('Completed button clicked');
}
function showStmt(idx) {
document.getElementById('progress-item-' + curStmt).classList.remove('current');
curStmt = idx;
document.getElementById('stmt').innerText = data[idx].stmt;
document.getElementById('desc').innerText = data[idx].desc;
document.getElementById('progress-item-' + idx).classList.add('current');
applyComplete(data[idx].complete);
}
function applyComplete(val) {
val = (val) ? true : false;
document.getElementById('desc').style.visibility = (val) ? 'visible' : 'hidden';
document.getElementById('btnTrue').disabled = val;
document.getElementById('btnFalse').disabled = val;
}
function createProgressBar() {
const parent = document.getElementById('progress');
parent.innerHTML = '';
for (let i = 0; i < data.length; i++) {
const item = document.createElement('div');
item.setAttribute('data-idx', i);
item.id = 'progress-item-' + i;
item.classList.add('item');
if (data[i].complete)
item.classList.add('complete');
parent.appendChild(item);
}
}
function btnClick(val) {
data[curStmt].complete = true;
answered.push(val);
document.getElementById('progress-item-' + curStmt).classList.add('complete');
if (val || (curStmt === data.length - 1)) {
applyComplete(true);
} else {
showStmt(curStmt + 1);
document.getElementById('btnTrue').disabled = true;
document.getElementById('btnFalse').disabled = true;
}
document.getElementById('btnNext').style.visibility = ((curStmt == answered.length) && (answered.length != data.length)) ? 'visible' : 'hidden';
document.getElementById('btnAfterComplete').style.visibility = (answered.length == data.length) ? 'visible' : 'hidden';
}
document.getElementById('progress').addEventListener(
'click',
function (e) {
if (e.target.classList.contains('item')) {
const newIdx = e.target.getAttribute('data-idx') - 0;
if (newIdx != curStmt) {
showStmt(newIdx);
}
}
},
true
);
createProgressBar();
showStmt(0);
.section {
margin: 10px 0;
}
#progress .item {
height: 10px;
width: 10px;
margin: 0 5px;
border: 2px solid red;
border-radius: 50%;
display: inline-block;
cursor: pointer;
}
#progress .item.current {
border-color: blue;
}
#progress .item.complete {
background-color: green;
}
#progress .item:not(.complete):hover {
background-color: lime;
}
#btnNext{
visibility: hidden;
}
#btnAfterComplete{
visibility: hidden;
}
<div class="section">
<div id="stmt"></div>
<div id="desc"></div>
</div>
<div class="section buttons">
<button id="btnTrue" onclick="btnClick(true)">True</button>
<button id="btnFalse" onclick="btnClick(false)">False</button>
<button id="btnNext" onclick="btnNext()">Next</button>
<button id="btnAfterComplete" onclick="btnAfterComplete()">Complted</button>
<div>
<div id="progress" class="section"></div>
Please check the snippet
You can do it either by modifying the disabled attribute or by adding/removing a class.I recommend using the disabled attribute.
Modifying attribute
You will want to switch between <button disabled="true"> and <button disabled="false">
With javascript, it could look like this:
if flag=1:
document.getElementById("your-btn").disabled = true;
else:
document.getElementById("your-btn").disabled = false;
Example for the same
const myFunction=()=>{
document.getElementById("your-btn").disabled = false;
}
<h1>Activate the disabled button conditionally</h1>
<button type="button" id="your-btn" disabled="false">Click Me!</button>
<button type="button" onclick="myFunction()">Click me to Activate the previous button</button>
Do tell me wether I was of any help :)

How to make a reset button appear after certain requirements?

So, i want a reset button to appear on my page when the score of the player reaches 5. But i can't seem to make it appear.
if (Score == 5) {
btnQuestion.disabled = true;
txtQuestionFeedback.innerText = "Correct! \n Congratulations, you've got 5 stars!";
imgScore5.src = "Images/StarOn.gif";
document.getElementById(btnReset).innerHTML = btnReset;
}
Try the following:
1) Insert your button element inside a DIV like this for easier reading
<div id="resetButtonDiv">
<button id="resetButton"></button> <!-- here goes your button config -->
</div>
2) Change the style like this using JS
<script>
function showResetButton() {
document.getElementById("resetButton").style.display = "none";
if (Score == 5) {
// Replace "Score" with your variable or element
document.getElementById("resetButton").style.display = "show";
}
}
showResetButton()
</script>
This was my way to do it:
ScoreBoard = function(sId, sIntoNode = '', fnOnChange = null) {
this.m_sId = sId != '' ? sId : 'scoreboard';
this.m_iScore = 0;
this.m_fnOnChange = fnOnChange;
if(sIntoNode != '') {
let TargetNode = document.getElementById(sIntoNode);
if(TargetNode) {
TargetNode.innerHTML = TargetNode.innerHTML + '<div class="scoreboard-score" id="' + this.m_sId + '">0</div>';
}
}
}
ScoreBoard.prototype.SetScore = function(iNewScore) {
this.m_iScore = iNewScore;
let scoreBoard = document.getElementById(this.m_sId);
if(scoreBoard) {
scoreBoard.innerHTML = this.m_iScore;
}
if(this.m_fnOnChange && typeof this.m_fnOnChange == 'function') {
this.m_fnOnChange(this);
}
}
ScoreBoard.prototype.AddScore = function(iAmount) {
this.SetScore(this.m_iScore + iAmount);
}
ScoreBoard.prototype.Reset = function() {
this.SetScore(0);
}
ScoreBoard.prototype.GetScore = function() {
return this.m_iScore;
}
function OnScoreChange(target) {
let resetBtn = document.getElementById('myScore-reset');
if(resetBtn) {
if(target.GetScore() >= 5) {
resetBtn.style.display = "block";
} else {
resetBtn.style.display = "none";
}
}
}
var myScore = new ScoreBoard('myScore', 'score', OnScoreChange);
var i = 0;
function test() {
myScore.AddScore(1);
i++;
if(i < 20) setTimeout(test, 1000);
}
test();
div#score {
padding: 12px;
background-color: darkgrey;
font-family: Arial;
border-radius: 12px;
box-shadow: 0 0 12px 3px black;
}
div.score-head {
background-color: black;
color: white;
padding: 6px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
div.scoreboard-score {
background-color: #EAEAEA;
padding: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
div#score button {
display: none;
}
<div id="score">
<button onClick="myScore.Reset();" id="myScore-reset">Reset Score</button>
<div class="score-head">Score:</div>
</div>
I've sorted it guys!
Instead, i just used a visibility attribute on the button to hide it on page startup. And then called on that attribute in a Function for HideButton().
```
function ShowResetButton() {
document.getElementById("btnReset").style.visibility = "visible";
}
```
But thank you all for your input! i really appreciate it!
Take it easy,
Happy coding!

Get localStorage value on page load

I've searched the internet but I can't seem to find anything that works for me.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heating System Control</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
strLED1 = "";
strLED2 = "";
strText1 = "";
strText2 = "";
var LED1_state = 0;
var LED2_state = 0;
function GetArduinoIO()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null)
{
// XML file received - contains analog values, switch values and LED states
document.getElementById("input1").innerHTML =
this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
document.getElementById("input2").innerHTML =
this.responseXML.getElementsByTagName('analog')[1].childNodes[0].nodeValue;
// LED 1
if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
document.getElementById("LED1").innerHTML = "ON";
document.getElementById("LED1").style.backgroundColor = "green";
document.getElementById("LED1").style.color = "white";
LED1_state = 1;
}
else {
document.getElementById("LED1").innerHTML = "OFF";
document.getElementById("LED1").style.backgroundColor = "red";
document.getElementById("LED1").style.color = "white";
LED1_state = 0;
}
// LED 2
if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
document.getElementById("LED2").innerHTML = "ON";
document.getElementById("LED2").style.backgroundColor = "green";
document.getElementById("LED2").style.color = "white";
LED2_state = 1;
}
else {
document.getElementById("LED2").innerHTML = "OFF";
document.getElementById("LED2").style.backgroundColor = "red";
document.getElementById("LED2").style.color = "white";
LED2_state = 0;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs" + strLED1 + strLED2 + nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 1000);
strLED1 = "";
strLED2 = "";
}
function GetButton1()
{
if (LED1_state === 1)
{
LED1_state = 0;
strLED1 = "&LED1=0";
}
else
{
LED1_state = 1;
strLED1 = "&LED1=1";
}
}
function GetButton2()
{
if (LED2_state === 1)
{
LED2_state = 0;
strLED2 = "&LED2=0";
}
else
{
LED2_state = 1;
strLED2 = "&LED2=1";
}
}
function SendText1()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText2 = "&txt2=" + document.getElementById("txt_form1").form_text1.value + "&end2=end";
request.open("GET", "ajax_inputs" + strText2 + nocache, true);
request.send(null);
}
function SendText2()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText1 = "&txt1=" + document.getElementById("txt_form2").form_text2.value + "&end1=end";
request.open("GET", "ajax_inputs" + strText1 + nocache, true);
request.send(null);
}
function clsTxt1()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form1").form_text1.value = "";
}, 500)
}
function clsTxt2()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form2").form_text2.value = "";
}, 500)
}
function Threshold1()
{
var thr1 = document.getElementById("txt_form1").form_text1.value;
document.getElementById("thresh1").innerHTML = thr1;
}
function Threshold2()
{
var thr2 = document.getElementById("txt_form2").form_text2.value;
document.getElementById("thresh2").innerHTML = thr2;
}
</script>
<style>
.IO_box
{
float: left;
margin: 0 20px 20px 0;
border: 1px solid black;
padding: 0 5px 0 5px;
width: 100px;
height: 196px;
text-align: center;
}
h1
{
font-family: Helvetica;
font-size: 120%;
color: blue;
margin: 5px 0 10px 0;
text-align: center;
}
h2
{
font-family: Helvetica;
font-size: 85%;
color: black;
margin: 10px 0 5px 0;
text-align: center;
}
p, form
{
font-family: Helvetica;
font-size: 80%;
color: #252525;
text-align: center;
}
button
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
input
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
.small_text
{
font-family: Helvetica;
font-size: 70%;
color: #737373;
text-align: center;
}
textarea
{
resize: none;
max-width: 90px;
margin-bottom: 1px;
text-align: center;
}
</style>
</head>
<body onload="GetArduinoIO(); Threshold1()">
<h1>Heating System Control</h1>
<div class="IO_box">
<h2>Room One</h2>
<p>Temp1 is: <span id="input1">...</span></p>
<button type="button" id="LED1" onclick="GetButton1()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form1" name="frmText">
<textarea name="form_text1" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText1(); clsTxt1(); Threshold1();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh1">...</span></p>
</div>
<div class="IO_box">
<h2>Room Two</h2>
<p>Temp2 is: <span id="input2">...</span></p>
<button type="button" id="LED2" onclick="GetButton2()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form2" name="frmText">
<textarea name="form_text2" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText2(); clsTxt2(); Threshold2();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh2">...</span></p>
</div>
</body>
</html>
So my question is, How can I keep the value inserted in the text area even after I reload the page (from the "Threshold1()" function)? I found a few examples with "localStorage" and JQuery, but I have no idea how to call the saved value when I reload the page.
Any help would be appreciated.
Thanks in advance,
Stefan.
Local Storage Explained
The localStorage object likes to store strings, so how would one store large objects, let's say some complex data structure? - Simple, JavaScript has a neat function built in, look up JSON.stringify(object). So all you would need to do is something like below to store some complex object is something like the code I've provided below. Then to retrieve an object from the localStorage you'll want to use JSON.parse(object);.
To look into localStorage, I strongly suggest you take a look at the likes of MDN and if you want to look into the JSON.parse and JSON.stringify functions, you can also find them both here:
JSON.parse() link
JSON.stringify() link
// vanilla js version of $(document).ready(function(){/*code here*/});
window.ready = function(fnc) {
if (typeof fnc != "function") {
return console.error("You need to pass a function as a param.");
}
try { // try time out for some old IE bugs
setTimeout(function () {
document.addEventListener("DOMContentLoaded", fnc());
}, 10)
} catch (e) {
try { // sometimes timeout won't work
document.addEventListener("DOMContentLoaded", fnc());
} catch (ex) {
console.log(ex);
}
}
};
// shorter than $(document).ready();
ready(function() {
var object = {
name: "Jack",
age: 30,
location: "U.S.A.",
get_pay: function() {
console.log("test");
}
},
test;
console.log(object);
var obj_string = JSON.stringify(object);
// run a test
var run_test = function() {
// output the stored object
test = localStorage.getItem("test");
console.log(test);
// to make js turn it into an object again
test = JSON.parse(localStorage.getItem("test"));
console.log(test);
};
// demo of trying to store an actual object
try {
localStorage.setItem("test", object);
run_test();
} catch (e) {
console.log(e);
}
// demo of trying to store the string
try {
localStorage.setItem("test", obj_string);
run_test();
} catch (e) {
console.log(e);
}
});
You can use this JSFiddle : http://jsfiddle.net/xpvt214o/45115/
here we are using Cookie concept and jquery.cookie.js to accomplish what you are trying to do.
to properly check the fiddle you need to press "Run" every time, you can open the same fiddle in 2 tabs write something in the first fiddle then just press run in the 2nd fiddle tab the value should automatically update, here the
$(function(){}); replicates your pageload
My question isn't exactly answered, but I completely avoided storing info on a device. Now I'm just reading the value straight from the arduino and it works. But thanks to everyone that provided some help.

Calculate the word amount from an <input>?

The following code converts text into equal paragraphs, based on the users input character amount.
Is it possible for the input box to calculate the amount of words for each paragraph instead of being based on the character amount?
JSFiddle
If an updated fiddle could please be provided, would be much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content');
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
custom = parseInt(document.getElementById("custom").value);
chunkSize = (custom>0)?custom:chunkSize;
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" id="custom" placeholder="Custom Characters per box">
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
How about this? It uses jQuery, but as you used the library in your original submission, I hope that won't be an issue:
HTML
<textarea id="input"></textarea>
<br/>
<button id='divide'>Divide</button>
<div id="paras"></div>
CSS
#input {
resize: none;
height: 200px;
width: 100%;
}
JS
$(function() {
$("#divide").click(function() {
var text = $("#input").val();
var wpp = 10 // words per paragraph
var words = text.split(" ");
var paras = [];
for (i = 0; i < words.length; i += wpp) {
paras.push(words.slice(i, i + wpp).join(" "));
}
$.each(paras, function(i, para) {
$("#paras").append("<p>" + para + "</p>");
});
});
})
JSFiddle

Categories