User interaction with javascript? - javascript

I have the following code which allows a user to interact with a table to create a game of tic-tac-toe, how do I alter it to replace the 'X' and 'O' text with images instead?
so that when the user clicks on a square an image is displayed instead of plain text ?
<!DOCTYPE html>
<html>
<head>
<title>tic-tac-toe</title>
<style>
td { border: 1px solid black;
width: 2em;
height: 2em;
margin: 0em;
text-align: center;
vertical-align: middle;
}
div.RedBG { background-color: #f00; }
td.BlueBG { background-color: white; }
</style>
</head>
<body>
<center><table id="t1"></table></center>
<div id="m1"></div>
<script>
var board = var board = [[0,0,0],[0,0,0],[0,0,0]];
var free = 9;
var turn = 0;
function numToLetter(num) {
switch (num) {
case 0: return " "
case 1: return "O"
case 2: return "X"
}
}
function clearMessage() {
m1 = document.getElementById("m1");
m1.style.display = "none";
}
function showMessage(message,style) {
m1 = document.getElementById("m1");
m1.innerHTML = message;
m1.style.display = "block";
m1.className = style;
}
...

alter the numToLetter function to return a source for an image contained in td or to assign the source to the image...
i think returning the source would be easier and cleaner.
In that case: in the numToLetter calling code assign the source to the appropriate grid square...
function numToSource(num) {
switch (num) {
case 0: return "path/to/blank.png";
case 1: return "path/to/O.png";
case 2: return "path/to/X.png";
}
}
function assignImageSource(gridId, num){
var element = document.getElementById(gridId);
var source = numberToSource(num);
element.src = source;
}

Related

how to remove the quotes or get element from this (javascript)

As topic, how can I remove the quote in the picuture below or get the img element from this?
(https://i.stack.imgur.com/kdPAP.png)
I m new to javascript and start making an image slider that can pop up a window while clicked to the image.
I cloned the li object which is clicked, and try to open it in the new window, it do work but how can I get the img only without the li?
Right now i m trying to call the cloned this object with innerHTML, but it shows the img element with quote, is there any way to remove the quote?
the quote that i want to remove
first time ask a question in here, if i violate any rules in the post, i delete the post, sorry for causing any inconvenience.
Here is the code
<!DOCTYPE html>
<html>
<head>
<style>
.risuto1 {
max-width: 480px;
max-height: 270px;
margin: auto;
position: relative;
}
ul {
list-style-type: none;
margin: auto;
padding: 0;
}
.aitemu>img {
max-width: 100%;
}
.aitemu {
display: none;
position: relative;
}
.aitemu.akutibu {
display: block;
}
.risuto1>.mae,
.tsugi {
width: auto;
height: auto;
padding: 20px;
top: 102.6px;
position: absolute;
cursor: pointer;
background-color: red;
}
.risuto1>.tsugi {
left: 431.8px;
}
</style>
</head>
<body>
<script>
var risuto1 = document.createElement("div");
risuto1.classList.add("risuto1");
document.body.appendChild(risuto1);
var suraidaaitemu = document.createElement("ul");
suraidaaitemu.classList.add("suraidaaitemu");
risuto1.appendChild(suraidaaitemu);
var imejisosurisuto = ["https://pbs.twimg.com/media/CGGc3wKVEAAjmWj?format=jpg&name=medium", "https://pbs.twimg.com/media/EYCXvuzU8AEepqD?format=jpg&name=large", "https://s3-ap-northeast-1.amazonaws.com/cdn.bibi-star.jp/production/imgs/images/000/668/074/original.jpg?1626914998", "https://livedoor.blogimg.jp/rin20064/imgs/7/3/73251146.jpg", "https://www.tbs.co.jp/anime/oregairu/character/img/chara_img_02.jpg"]
//var imejirisuto=[]
for (var n = 0; n < imejisosurisuto.length; n++) {
var imeji = document.createElement("img");
imeji.src = imejisosurisuto[n];
var aitemu = document.createElement("li");
aitemu.classList.add("aitemu");
suraidaaitemu.appendChild(aitemu);
aitemu.appendChild(imeji);
aitemu.onclick=atarashivindou;
}
var akutibunasaishonoko = document.querySelector(".suraidaaitemu").firstChild;
akutibunasaishonoko.classList.add("akutibu");
var mae = document.createElement("div");
mae.classList.add("mae");
mae.innerHTML = "&#10094";
risuto1.appendChild(mae);
var tsugi = document.createElement("div");
tsugi.classList.add("tsugi");
tsugi.innerHTML = "&#10095";
risuto1.appendChild(tsugi);
var tensuu = 0;
var suraido = document.querySelector(".suraidaaitemu").children;
var gokeisuraido = suraido.length;
tsugi.onclick = function () {
Tsugi("Tsugi");
}
mae.onclick = function () {
Tsugi("Mae");
}
function Tsugi(houkou) {
if (houkou == "Tsugi") {
tensuu++;
if (tensuu == gokeisuraido) {
tensuu = 0;
}
}
else {
if (tensuu == 0) {
tensuu = gokeisuraido - 1;
}
else {
tensuu--;
}
}
for (var i = 0; i < suraido.length; i++) {
suraido[i].classList.remove("akutibu");
}
suraido[tensuu].classList.add("akutibu");
}
function atarashivindou(){
var Atarashivindou = window.open("", "_blank", "width: 1000px, max-height: 562.5px");
var kakudaigazou=document.createElement("div");
kakudaigazou.classList.add("kakudaigazou");
Atarashivindou.document.body.appendChild(kakudaigazou);
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
}
</script>
</body>
.innerHTML is a string. You don't want to append a string, but the element. So change this:
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
...to this:
var koronimeji=this.querySelector("img").cloneNode();
kakudaigazou.append(koronimeji);

How to change all :root variables with one function

Similar question : But can't able to get answer
Can be answer to this question : But has to split on each :
If possible to get all variable in one function and change each values
If there are 2-4 variable than easy to change but when that change to 10 or more
var root = document.querySelector(':root');
function func() {
root.style.setProperty('--r', 'brown');
root.style.setProperty('--b', 'lightblue');
root.style.setProperty('--g', 'lightgreen');
}
:root {
--r: red;
--b: blue;
--g: green;
}
.text1 {
color: var(--r)
}
.text2 {
color: var(--b)
}
.text3 {
color: var(--g)
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="func()">Change</button>
Is there a way to automatic(dynamically) get all the variables without writing each variable while values array is self entered
var root = document.querySelector(':root');
var roots = getComputedStyle(root);
var re = roots.getPropertyValue('--r')
var bl = roots.getPropertyValue('--b')
var gr = roots.getPropertyValue('--g')
function func() {
root.style.setProperty('--r', 'brown');
root.style.setProperty('--b', 'lightblue');
root.style.setProperty('--g', 'lightgreen');
}
function func2() {
root.style.setProperty('--r', re);
root.style.setProperty('--b', bl);
root.style.setProperty('--g', gr);
}
:root {
--r: red;
--b: blue;
--g: green;
}
.text1 {
color: var(--r)
}
.text2 {
color: var(--b)
}
.text3 {
color: var(--g)
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="func()">Change</button>
<button onclick="func2()">Orignal</button>
But when getting back to original values then each value is entered by separate variable and for each it is defined .
Is there a way to have a approach which takes original values and variables in separate array automatically.
Thanks for help in advance
I understand you want to first read all the declared variables from the css and store them, so they might be resetted after applying new values?
This code will do this, given that there's just one ':root' declaration in one stylesheet (easily complemented in case 'splitted' declaration in more places needed)
let variableLookup = {
'--r': {
newValue: 'teal'
},
'--b': {
newValue: 'orange'
},
'--g': {
newValue: 'purple'
}
}
var root = document.querySelector(':root');
function setNewColors() {
const cssText = [...document.styleSheets]
.map(styleSheet => [...styleSheet.cssRules]
.filter(CSSStyleRule => CSSStyleRule.selectorText === ':root'))
.flat()[0].cssText
// cssText = ':root { --r: red; --b: blue; --g: green; }'
cssText.match(/{(.*)}/)[1].trim()
.split(';')
.filter(Boolean)
.forEach(declaration => {
const [variable, oldValue] = declaration.split(':').map(str => str.trim())
let entry = variableLookup[variable]
if (entry) entry.oldValue = oldValue
})
console.log('variableLookup >>', variableLookup)
Object.entries(variableLookup).forEach(([variable, {newValue}]) => {
root.style.setProperty(variable, newValue);
})
}
function resetColors() {
Object.entries(variableLookup).forEach(([variable, {oldValue}]) => {
if (oldValue) root.style.setProperty(variable, oldValue)
})
}
:root {
--r: red;
--b: blue;
--g: green;
}
.text1 {
color: var(--r)
}
.text2 {
color: var(--b)
}
.text3 {
color: var(--g)
}
:root {
--c: magenta;
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="setNewColors()">Change to new colors</button>
<button onclick="resetColors()">Reset old colors</button>
Since the OP is interested in a version without using .split() these could be replaced by using a regex and .match()
const declarations = '--r: red; --b: blue; --g: green;'
const regex1 = /^[\w-:\s]+(?=;)|(?<=;)[\w-:\s]+/g
const declarationsArr = declarations.match(regex1)
console.log(declarationsArr) // ["--r: red", " --b: blue", " --g: green"]
const regex2 = /[\w-]+(?=:)|(?<=:\s)[\w-]+/g
const declarationsSplit = declarationsArr.map(d => d.match(regex2))
console.log(declarationsSplit) // [["--r", "red"], ["--b", "blue"], ["--g", "green"]]
One method can be entering all variables and values in different arrays and fetching values from them . Where variables = values which need to be equal have same index number
var root = document.querySelector(':root');
variable = ['--r', '--b', '--g'];
values = ['violet', 'lightblue', 'lightgreen']
function func() {
for (let i = 0; i < 3; i++)
root.style.setProperty(variable[i], values[i]);
}
:root {
--r: red;
--b: blue;
--g: green;
}
.text1 {
color: var(--r)
}
.text2 {
color: var(--b)
}
.text3 {
color: var(--g)
}
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="func()">Change</button>
const root = document.documentElement;
function changeVariables(...values) {
const variables = ["--r", "--g", "--b"];
for (const variable of variables) {
root.style.setProperty(variable, values[variable.indexof(variables)]);
}
}
//Simply execute function like this
changeVariables("#000", "#808080", "#FF0000");
setting new-colors you want to change
backup original-colors
Try the example bellow
var root = document.querySelector(':root');
var $divEle = $("div[class^='text']"); // get all element with class starting with 'text'
var arrCssVar = ['--r', '--b','--g'];
var backupOrgColor= {}
var newColor = {'--r':'brown', '--b':'lightblue', '--g':'lightgreen'}; // ordering color what you want to change
// backup original colors
$divEle.map(function(i, v) {
if(i < arrCssVar.length){
var compStyle = getComputedStyle(this);
// setting key/value pair to Obj
backupOrgColor[arrCssVar[i]] = compStyle.getPropertyValue(arrCssVar[i]);
}
});
// change color
function setNewColors() {
arrCssVar.map(function (key, value) {
//console.log(key + ": key :change: value : "+ newColor[key]);
root.style.setProperty(key, newColor[key]);
});
}
// reset original color
function resetColors() {
arrCssVar.map(function (key, value) {
//console.log(key + ": key :: value : "+ backupOrgColor[key]);
root.style.setProperty(key, backupOrgColor[key]);
});
}
:root {
--r: red;
--b: blue;
--g: green;
}
.text1 {
color: var(--r)
}
.text2 {
color: var(--b)
}
.text3 {
color: var(--g)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
<button onclick="setNewColors()">Change</button>
<button onclick="resetColors()">Orignal</button>
Try this example.
Initialize two arrays, one is empty for the current colors form the css and second for a new colors.
Need to define how many variables, then get them and put in an empty array.
Create two functions with loops, in the first we assign the new colors for variables, in the second reset.
const root = document.body;
// Colors arrays
const cssVarColors = [];
const newColors = ['brown', 'lightblue', 'lightgreen'];
// Create an array of variable colors from css.
const cssRootArray = document.styleSheets[0].cssRules;
for (const i of cssRootArray) {
// Check, if :root in the css.
if (i.selectorText.includes('root')) {
const rootArrayLength = i.style.length;
for (let j = 0; j < rootArrayLength; j++) {
const key = i.style[j];
// Create object { key/variable : value/color }
const value = getComputedStyle(root).getPropertyValue(key);
cssVarColors.push({[key]: value});
}
}
}
// We change colors, with variable keys and indexes.
function changeColor() {
for (const i in cssVarColors) {
const key = Object.keys(cssVarColors[i]);
// Check, if newColor array don't have a color.
if (!newColors[i]) {
return;
}
root.style.setProperty(key, newColors[i]);
}
variables();
}
change.addEventListener('click', changeColor);
const root = document.body;
// Colors arrays
const cssVarColors = [];
const newColors = ['brown', 'lightblue', 'lightgreen'];
// Create an array of colors from a css variables file.
const cssRootArray = document.styleSheets[0].cssRules;
for (const i of cssRootArray) {
// Check, if :root in the css.
if (i.selectorText.includes('root')) {
const rootArrayLength = i.style.length;
for (let j = 0; j < rootArrayLength; j++) {
const key = i.style[j];
// Create object { key/variable : value/color }
const value = getComputedStyle(root).getPropertyValue(key);
cssVarColors.push({
[key]: value,
});
}
}
}
// We change colors, with variable keys and indexes.
function changeColor() {
for (const i in cssVarColors) {
const key = Object.keys(cssVarColors[i]);
// Check, if newColor array don't have a color.
if (!newColors[i]) {
return;
}
root.style.setProperty(key, newColors[i]);
}
variables();
}
// Can't separate in loop by [key, value],
// because key has a specific value.
function resetColor() {
for (const i in cssVarColors) {
if (!newColors[i]) {
return;
}
const key = Object.keys(cssVarColors[i]);
const value = Object.values(cssVarColors[i]);
root.style.setProperty(key, value);
}
variables();
}
// Change button
change.addEventListener('click', changeColor);
// Reset button
reset.addEventListener('click', resetColor);
// extra for view
cssVarColors.forEach(clr => {
const el = document.createElement('span');
el.textContent = JSON.stringify(clr);
document.getElementById('variables').appendChild(el);
});
:root {
--r: red;
--b: blue;
--g: green;
--m: magenta;
--black: black;
}
.text1 {
color: var(--r);
}
.text2 {
color: var(--b);
}
.text3 {
color: var(--g);
}
/* Extra style */
body {
display: grid;
grid-template-columns: 50px 150px;
grid-template-rows: auto;
}
section {
grid-column: 1;
}
#variables {
grid-column: 2;
display: flex;
flex-direction: column;
}
span:nth-of-type(1) {
border: 5px solid var(--r);
}
span:nth-of-type(2) {
border: 5px solid var(--b);
}
span:nth-of-type(3) {
border: 5px solid var(--g);
}
span:nth-of-type(4) {
border: 5px solid var(--m);
}
span:nth-of-type(5) {
border: 5px solid var(--black);
}
<section>
<div class="text1">Hello</div>
<div class="text2">Bye</div>
<div class="text3">World</div>
</section>
<div id="variables"></div>
<button id="change">Change</button>
<button id="reset">Reset</button>

Show images in quiz 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>

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.

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

Categories