character selction option for the players in tic-tac-toe - javascript

i have made a tic-tac-toe game.For which i have to make a character selection module for each player.Players have to choose between x and o.If first one selects 'o' ,other player can not select that.he has to choose 'x'.But including html lines ,the code i have written is almost 50 lines and very fragile, i can't find any other way to shorten this code.selection option is a basic thing in games.Any expert solution on this matter would be appreciated
function Player(name,val){
this.name=name;
this.val=val;
}
var ps=document.getElementById('ps');
ps.addEventListener('click',function(e){
player1=prompt('input player1');
char1=prompt('input char between x/o');
if((char1 != 'x') && (char1 != 'o')){
for(;;){
alert('select between x an o please');
char1=prompt('between x/o');
if((char1 === 'x')|| (char1 === 'o')){
break;
}
}
}
player2 = prompt('input player2');
char2 = prompt('input your char O/X');
if((char2 === char1) || ((char2 != 'x') && (char2 != 'o'))){
for(;;){
alert('you can not have this char');
char2=prompt('try again');
if(((char2 === 'o') || (char2 === 'x')) && (char2 != char1)){
break;
}
}
}
p1=new Player(player1,char1);
p2=new Player(player2,char2);
document.body.innerHTML+='\n'+p1.name+' : '+p1.val+'\n'+p2.name+' : '+p2.val;
});
<input type='button' value='Player Setup' id='ps'>

Instead of using prompt, its better to make use of HTML <input> elements.
Demo on Fiddle
HTML:
<div class="container">
<div class="p1">
<label>Player 1:</label>
<input id="p1" type="text" />
<br />
<br />
<label>Choose your Character:</label>
<br />
<input class="charac" type="radio" name="characP1" value="X" />
<label class="charac">X</label>
<br />
<input class="charac" type="radio" name="characP1" value="O" />
<label class="charac">O</label>
</div>
<div class="p2">
<label>Player 2:</label>
<input id="p2" type="text" />
<br />
<br />
<label>Choose your Character:</label>
<br />
<input class="charac cp2" type="radio" name="characP2" value="X" />
<label class="charac">X</label>
<br />
<input class="charac cp2" type="radio" name="characP2" value="O" />
<label class="charac">O</label>
</div>
<div class="btnContainer">
<input id="btn" class="btn" type="button" value="Submit" />
</div>
<div id="message"></div>
</div>
JavaScript:
var ps = document.getElementById('btn');
var c1 = document.getElementsByName('characP1');
var c2 = document.getElementsByName('characP2');
var msg = document.getElementById('message');
var char1;
var char2;
function Player(name, val) {
this.name = name;
this.val = val;
}
for (i = 0; i < c1.length; i++) {
c1[i].addEventListener('change', function () {
if (this.checked) {
this.value == 'X' ? c2[1].checked = true : c2[0].checked = true;
char1 = this.value;
char2 = this.value == 'X' ? 'O' : 'X';
}
});
}
for (i = 0; i < c2.length; i++) {
c2[i].addEventListener('change', function () {
if (this.checked) {
this.value == 'X' ? c1[1].checked = true : c1[0].checked = true;
char2 = this.value
char1 = this.value == 'X' ? 'O' : 'X';
}
});
}
ps.addEventListener('click', function () {
var player1 = document.getElementById('p1').value;
var player2 = document.getElementById('p2').value;
p1 = new Player(player1, char1);
p2 = new Player(player2, char2);
if (p1.name && p1.val && p2.name && p2.val) {
msg.innerHTML = p1.name + ' : ' + p1.val + '<br />' + p2.name + ' : ' + p2.val;
} else {
msg.innerHTML = 'Please fill all input fields'
}
});
CSS:
.charac {
position: relative;
left: 0px;
}
.container {
width: 250px;
margin: 0 auto;
}
.p1, .p2, #message {
width: 100%;
height: 100%;
border: 4px solid #51634b;
border-radius: 10px;
padding: 10px;
margin: 10px;
}
#message {
text-align: center;
border: none;
}
.btnContainer {
padding: 10px;
margin-left: 40px;
}
input.charac {
position: relative;
top: 3px;
}
input[type=text] {
height: 25px;
background: transparent;
border-radius: 6px;
outline: none;
color: #51634b;
font-size: 12px;
border: 1px solid #51634b;
margin-left: 5px;
padding: 2px;
text-align: center;
}
input[type=text]:focus {
box-shadow: 0px 0px 4px #62745c;
}
input[type=radio] {
cursor: pointer;
}
body {
background: url(http://s25.postimg.org/b6q25p4p7/black_thread.png) repeat black;
}
label {
color: #51634b;
}
#message {
color: #51634b;
font-size: 15px;
}
.btn {
display: block;
width: 120px;
height: 30px;
background-color: transparent;
color: black;
border: 2px solid #51634b;
border-radius: 5px;
cursor: pointer;
color: #51634b;
font-size: 15px;
margin: 15px;
margin: 0 auto;
}
.btn::-moz-focus-inner {
border: 0;
}
.btn:hover {
-webkit-animation: btn 0.5s 1;
-moz-animation: btn 0.5s 1;
-o-animation: btn 0.5s 1;
animation: btn 0.5s 1;
background-color: #51634b;
color: #000000;
}
input.btn:active {
padding: 0;
}
#-webkit-keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}
#-moz-keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}
#-o-keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}
#keyframes btn {
from {
background-color: transparent;
color: #51634b;
}
to {
background-color:#51634b;
color: #000000;
}
}

Related

Keep Lines Containing

I am creating a "Keep Lines containing" project. I almost completed this task. But "Search Lines for" is working only 1 line. Multiple "Search
Lines for" is not working. I need "Search Lines for" in multiple lines.
All used HTML, CSS & javascript codes are here
I created a Codepen page for it. Please check : https://codepen.io/coderco/pen/LYGQyqr
function loadfile(fileid, loadid) {
document.getElementById(loadid).value = 'Loading...';
setTimeout(function() {
loadfile2(fileid, loadid)
}, 1000);
}
function loadfile2(fileid, loadid) {
if (!window.FileReader) {
document.getElementById(loadid).value = 'Your browser does not support HTML5 "FileReader" function required to open a file.';
} else {
fileis = document.getElementById(fileid).files[0];
var fileredr = new FileReader();
fileredr.onload = function(fle) {
var filecont = fle.target.result;
document.getElementById(loadid).value = filecont;
}
fileredr.readAsText(fileis);
}
}
function savefile(saveasid, saveid) {
if (!window.Blob) {
alert('Your browser does not support HTML5 "Blob" function required to save a file.');
} else {
var txtwrt = document.getElementById(saveid).value;
if (document.getElementById('dos').checked == true) txtwrt = txtwrt.replace(/\n/g, '\r\n');
var textblob = new Blob([txtwrt], {
type: 'text/plain'
});
var saveas = document.getElementById(saveasid).value;
var dwnlnk = document.createElement('a');
dwnlnk.download = saveas;
dwnlnk.innerHTML = "Download File";
if (window.webkitURL != null) {
dwnlnk.href = window.webkitURL.createObjectURL(textblob);
} else {
dwnlnk.href = window.URL.createObjectURL(textblob);
dwnlnk.onclick = destce;
dwnlnk.style.display = 'none';
document.body.appendChild(dwnlnk);
}
dwnlnk.click();
}
}
function destce(event) {
document.body.removeChild(event.target);
}
function cleartext() {
document.getElementById('input_output').value = '';
document.getElementById('removed').innerHTML = '';
document.getElementById('removed_box').value = '';
}
function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}
var fieldnum = 0;
var fieldtype = '';
var cacherem = 'no';
var enableregex = 'no';
function makeregexp() {
var regexpoutarr = new Array();
for (var x = 0; x < (fieldnum + 1); x++) {
regexpoutarr[x] = document.getElementById('addfield' + x).value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}
var regexpout = '';
if (fieldtype == 'AND') regexpout = '((?=.*' + regexpoutarr.join(')(?=.*') + ').*)';
if (fieldtype == 'OR') regexpout = '(' + regexpoutarr.join('|') + ')';
if (fieldtype == '') regexpout = document.getElementById('addfield0').value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
return regexpout;
}
function removelines(whatlines) {
var textin = document.getElementById('input_output').value.replace(/\r/g, '');
var toremove = makeregexp();
var textinarr = textin.split('\n');
var textinarrcnt = textinarr.length;
var textoutarr = new Array();
var textoutarrcnt = 0;
var linesremovedcnt = 0;
var casen = 'i';
if (document.getElementById('case_sen').checked == true) casen = '';
if (enableregex == 'yes') toremove = document.getElementById('addfield0').value;
else toremove = makeregexp();
var killfun = 'no';
try {
var toremoveregx = new RegExp(toremove, casen);
} catch (err) {
alert('Something is incorrect (' + err + ') within your regular expression.\nBe sure special characters .*+?^=!:${}()|\\ used as literals have been escaped with a backslash.');
killfun = 'yes';
}
if (killfun == 'no') {
if (whatlines == 'containing' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
if (whatlines == 'notcontaining' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
var removedcachearr = new Array();
if (whatlines == 'containing' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
if (whatlines == 'notcontaining' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
var textout = textoutarr.join('\n');
document.getElementById('input_output').value = textout;
if (cacherem == 'yes') {
var removedcache = removedcachearr.join('\n');
document.getElementById('removed_box').value = removedcache;
}
document.getElementById('removed').innerHTML = '' + linesremovedcnt + ' removed / ' + textoutarrcnt + ' remain.';
}
}
function addfield(field) {
if (field == 'reset') {
document.getElementById('inputfields').innerHTML = '<input type="text" id="addfield0" value="" style="width:100%;" />'
document.getElementById('andbttn').style.display = 'inline-block';
document.getElementById('orbttn').style.display = 'inline-block';
fieldnum = 0;
fieldtype = '';
} else {
fieldnum++;
if (fieldnum == 1) {
if (field == 'andfield') {
document.getElementById('orbttn').style.display = 'none';
fieldtype = 'AND';
} else {
fieldtype = 'OR';
document.getElementById('andbttn').style.display = 'none';
}
}
var newfield = fieldtype + '<input type="text" id="addfield' + fieldnum + '" value="" style="width:100%;" />';
var newdiv = document.createElement('div');
newdiv.innerHTML = newfield;
document.getElementById('inputfields').appendChild(newdiv);
}
resizepage();
}
function disrem() {
var chkedstate = document.getElementById('dremoved').checked;
if (chkedstate == true) {
document.getElementById('removed_box').style.display = 'inline-block';
cacherem = 'yes';
} else {
cacherem = 'no';
document.getElementById('removed_box').value = '';
document.getElementById('removed_box').style.display = 'none';
}
resizepage();
}
function selectele(eleid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(eleid));
range.select();
} else {
var range = document.createRange();
range.selectNode(document.getElementById(eleid));
window.getSelection().addRange(range);
}
}
function regexsrch() {
var chkedstate = document.getElementById('regex_srch').checked;
if (chkedstate == true) {
addfield('reset');
enableregex = 'yes';
document.getElementById('addfielddiv').innerHTML =
'<div style="padding:3px 0px 3px 0px;"><input type="checkbox" id="regex_srch" onclick="regexsrch();" CHECKED />Enable regular expression search. ' +
'Use <span id="catordog" style="color:#990000;" onclick="selectele(this.id)">(cat|dog|bird)</span> for cat OR dog OR bird. Use <span id="catanddog" style="color:#990000;" onclick="selectele(this.id)">((?=.*cat)(?=.*dog)(?=.*bird).*)</span> for cat AND dog AND bird. ' +
'Remember to escape special characters .*+?^=!:${}()|\\ with a backslash when used as literals within a regular expression. Use the <a target="_blank" href="" style="color:#0000FF;">Escape Literal Characters</a> tool. ' +
'Learn more about regular expressions visit <a rel="nofollow" target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" style="color:#0000FF;">developer.mozilla.org</a>.</div>';
} else {
document.getElementById('addfield0').value = '';
enableregex = 'no';
document.getElementById('addfielddiv').innerHTML =
'Add <input type="button" id="andbttn" value="AND" onClick="addfield(\'andfield\');" /> ' +
'<input type="button" id="orbttn" value="OR" onClick="addfield(\'orfield\');" /> search field. ' +
'<input type="button" value="Reset" onClick="addfield(\'reset\');" /> ' +
'<input type="checkbox" id="regex_srch" onclick="regexsrch();" />Enable regular expression search.';
}
resizepage();
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
font-family: arial;
font-size: 16px;
line-height: 1.7;
}
h1 {
display: block;
font-size: 18px;
font-weight: bold;
margin: 0px;
padding: 0px;
}
.se-for {
font-size: 27px;
font-weight: bold;
color: #b93207;
padding-top: 54px;
}
.contentt,
.wordd {
display: block;
margin: 0px;
padding: 8px 10px 8px 10px;
overflow: scroll;
font-family: arial;
font-size: 16px;
line-height: 1.7;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
border-radius: 4px 4px 4px 4px;
width: 100%;
font-size: 18px;
}
.contentt {
height: 400px;
overflow: auto;
}
.wordd {
height: 99px;
overflow: auto;
}
input {
display: inline-block;
height: 33px;
line-height: 1;
vertical-align: middle;
font-size: 16px;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input::-moz-focus-inner {
border: 0;
padding: 0
}
input[type='radio'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='checkbox'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='text'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
border-radius: 12px;
}
input[type='button'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
font-weight: bold;
color: #000000;
border: 1px solid #000000;
background-color: #FFFFFF;
cursor: pointer;
border-radius: 5px;
background: #b93207;
color: #fff;
border: #b93207;
}
input[type='button']:hover {
color: #f9f900;
}
input[type='button']:hover {}
input[type='file'] {
width: 92px;
border-radius: 12px;
overflow: hidden;
padding: 0px;
margin: 0px 0px 0px -92px;
-moz-opacity: 0;
opacity: 0;
cursor: pointer;
}
input[type='file']::-webkit-file-upload-button {
cursor: pointer;
}
div {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table,
td {
padding: 0px;
}
.buttonz {
width: 100%;
display: inline-block;
}
#menu {
position: absolute;
z-index: -1;
left: 0px;
top: 0px;
width: 0px;
height: 0%;
margin: 0px;
overflow: auto;
background-color: #E1E1D2;
border-right: 1px solid #000000;
}
div.navcat {
padding: 10px 0px 5px 12px;
font-size: 18px;
font-weight: bold;
font-style: italic;
}
div.navdiv {
height: 2px;
padding: 0px;
margin: 18px 10px 13px 10px;
background-color: #000000;
}
a.nav {
display: inline-block;
padding: 0px;
margin: 10px 0px 10px 10px;
text-decoration: underline;
color: #000000;
}
#toolpadding {
padding: 10px 10px 10px 10px;
}
#tool {
width: 1100px;
margin: 0px;
padding: 0px;
background-color: #fff;
margin: 0 auto;
}
<div id="tool">
<div id="toolpadding">
<div id="topdiv">
<div class="se-for">Search lines for:</div>
<div id="inputfields" style="padding-top:4px;">
<textarea type="text" id="addfield0" class="wordd">Three</textarea>
</div>
<div class="buttonz">
<input type="button" value="Keep Lines Containing" onClick="if(document.getElementById('addfield0').value!='') {removelines('notcontaining');}" />
<input type="checkbox" id="case_sen" />Case sensitive.
</div>
</div>
<div id="middiv" style="height:120px;">
<textarea id="input_output" class="contentt" wrap="off">
One One One One One One One One One One One One One One One
Three Three Three Three Three Three Three Three Three Three
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Three Three Three Three Three Three Three Three Three Three
Three Three Three Three Three Three Three Three Three Three
Four Four Four Four Four Four Four Four Four Four Four Four
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
</textarea>
</div>
<div id="btmdiv">
<textarea id="removed_box" rows="4" style="display:none; width:100%; margin-top:10px;" wrap="off">
Removed Line Box - Removed/extracted lines will display here.</textarea>
</div>
</div>
</div>

Adding a square root function to a calc using js

So, I made a calculator, and I want to add a square root function, but I know there is no already made function that finds the square root of numbers. So what elements can I combine to find the square root of a number?
const screen = document.querySelector("#screen");
const clearButton = document.querySelector("#clear");
const equalsButton = document.querySelector("#equals");
const decimalButton = document.querySelector("#decimal");
let isFloat = false;
let signOn = false;
let firstNumber = "";
let operator = "";
let secondNumber = "";
let result = "";
const allClear = () => {
isFloat = false;
signOn = false;
firstNumber = "";
operator = "";
secondNumber = "";
result = "";
screen.value = "0";
};
const calculate = () => {
if (operator && result === "" && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
secondNumber = screen.value.substring(firstNumber.length + 3);
switch (operator) {
case "+":
result = Number((Number(firstNumber) + Number(secondNumber)).toFixed(3));
break;
case "-":
result = Number((Number(firstNumber) - Number(secondNumber)).toFixed(3));
break;
case "*":
result = Number((Number(firstNumber) * Number(secondNumber)).toFixed(3));
break;
case "/":
result = Number((Number(firstNumber) / Number(secondNumber)).toFixed(3));
break;
default:
}
screen.value = result;
}
};
clear.addEventListener("click", allClear);
document.querySelectorAll(".number").forEach((numberButton) => {
numberButton.addEventListener("click", () => {
if (screen.value === "0") {
screen.value = numberButton.textContent;
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent === "0") {
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent !== "0") {
screen.value = screen.value.substring(0, screen.value.length - 1) + numberButton.textContent;
} else if (result || result === 0) {
allClear();
screen.value = numberButton.textContent;
} else {
screen.value += numberButton.textContent;
}
});
});
decimalButton.addEventListener("click", () => {
if (result || result === 0) {
allClear();
isFloat = true;
screen.value += ".";
} else if (!isFloat) {
isFloat = true;
if ([" ", "+", "-"].includes(screen.value[screen.value.length - 1])) {
screen.value += "0.";
} else {
screen.value += ".";
}
}
});
document.querySelectorAll(".operator").forEach((operatorButton) => {
operatorButton.addEventListener("click", () => {
if (result || result === 0) {
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (operator && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
calculate();
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (!operator) {
isFloat = false;
firstNumber = screen.value;
operator = operatorButton.dataset.operator;
screen.value += ` ${operatorButton.textContent} `;
} else if (!signOn
&& !["*", "/"].includes(operatorButton.dataset.operator)
&& screen.value[screen.value.length - 1] === " ") {
signOn = true;
screen.value += operatorButton.textContent;
}
});
});
equalsButton.addEventListener("click", calculate);
* {
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
font-weight: 300;
margin: 0;
padding: 0;
}
body {
background-color: #222;
height: 100vh;
}
header {
background-color: #333;
padding: 40px 0;
}
header h1 {
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(to right bottom, #fff, #777);
color: transparent;
font-size: 40px;
letter-spacing: 2px;
text-align: center;
text-transform: uppercase;
}
main {
background-color: #222;
display: flex;
justify-content: center;
padding: 60px 0;
}
main #container {
background-color: #333;
box-shadow: 0 5px 5px #111;
padding: 20px;
}
.clearfix:after {
clear: both;
content: " ";
display: block;
font-size: 0;
height: 0;
visibility: hidden;
}
#container .row:not(:last-child) {
margin-bottom: 9px;
}
#container input,
#container button {
float: left;
}
#container input:focus,
#container button:focus {
outline: none;
}
#container input {
background-color: #222;
border: 1px solid #999;
border-right-width: 0;
color: #999;
font-size: 22px;
font-weight: 300;
height: 80px;
padding-right: 14px;
text-align: right;
width: 261px;
}
#container button {
background-color: #222;
border: none;
box-shadow: 0 3px 0 #111;
color: #999;
font-size: 20px;
height: 80px;
margin-right: 7px;
width: 80px;
}
#container button:active {
box-shadow: 0 2px 0 #111;
transform: translateY(1px);
}
#container #clear,
#container .operator,
#container #equals {
color: #111;
}
#container #clear,
#container .operator {
margin-right: 0;
}
#container #clear {
background-color: #e95a4b;
border: 1px solid #999;
border-left-width: 0;
box-shadow: none;
cursor: pointer;
}
#container #clear:active {
box-shadow: none;
transform: none;
}
#container .operator {
background-color: #999;
box-shadow: 0 3px 0 #555;
}
#container .operator:active {
box-shadow: 0 2px 0 #555;
}
#container #equals {
background-color: #2ecc71;
box-shadow: 0 3px 0 #155d34;
}
#container #equals:active {
box-shadow: 0 2px 0 #155d34;
}
#media only screen and (max-width: 400px) {
header {
padding: 28px 0;
}
header h1 {
font-size: 36px;
}
main {
padding: 40px 0;
}
main #container {
padding: 16px;
}
#container .row:not(:last-child) {
margin-bottom: 7px;
}
#container input {
font-size: 18px;
height: 60px;
padding-right: 10px;
width: 195px;
}
#container button {
font-size: 16px;
height: 60px;
margin-right: 5px;
width: 60px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">
<link href="Project 1.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Calculator</h1>
</header>
<main>
<div id="container">
<div class="row clearfix">
<input id="screen" value="0" disabled type="text">
<button id="clear">AC</button>
</div>
<div class="row clearfix">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button data-operator="+" class="operator">+</button>
</div>
<div class="row clearfix">
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button data-operator="-" class="operator">-</button>
</div>
<div class="row clearfix">
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button data-operator="*" class="operator">×</button>
</div>
<div class="row clearfix">
<button id="decimal">.</button>
<button class="number">0</button>
<button id="equals">=</button>
<button data-operator="/" class="operator">÷</button>
</div>
</div>
</main>
<script src="Project 1.js"></script>
</body>
</html>
This is the code for the calc.. Feel free to edit it and explain to me what you did.
There is already one.
The Math.sqrt() function returns the square root of a number, that is, ∀x≥0,Math.sqrt(x)=x
=the uniquey≥0such thaty2=x
MDN Docs
You can use javascript built in
Math.sqrt(number)

No result from searching using Google Apps Script

I wrote this in google apps script to allow me to open a popup player for youtube in google docs. The other files work fine but this does not
The issue is that the search engine and the UI seem to work, but there is no result from searching, no matter how long I wait. if anyone could point out my mistake and tell me how to fix it that'd be awesome.
function embed(cacheKey, resourceId, resourceType) {
const progress = document.querySelector("#progress");
progress.style.display = "block";
console.log(cacheKey, resourceId, resourceType);
var text;
let checked = document.querySelector('input[type="radio"]:checked').value;
if (checked === 'string') {
text = document.querySelector('input[name="link-text"]').value;
}
let prefs = {
"type": checked,
"string": text
};
google.script.run.withSuccessHandler(function(data) {
if (data.success) {
document.querySelector('#result').innerText = "Video linked!";
setTimeout(function() {
document.querySelector('#result').innerText = "";
}, 3000);
}
if (data.type === "copy" && data.url) {
navigator.permissions.query({
name: "clipboard-write"
}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.writeText(data.url);
alert('URL copied to clipboard');
}
});
}
progress.style.display = "none";
}).DTApi('DT', 'embed', cacheKey, prefs, resourceId, resourceType);
}
function previewEmbed(cacheKey, resourceId, resourceType) {
const progress = document.querySelector("#progress");
progress.style.display = "block";
console.log(cacheKey, resourceId, resourceType);
google.script.run.withSuccessHandler(function(result) {
let container = document.querySelector("#preview");
let data = JSON.parse(result);
console.log(data)
console.log('Trying to preview: ' + Object.keys(data))
let settings = function(id, title) {
const template = "<div class='settings'> \
<h2>Settings</h2> \
<p>How do you want to link your video?</p> \
<input type='radio' id='copy-radio' name='embed-type' value='copy' /><label for='copy-radio'>Copy link to clipboard</label/> \
<br /> \
<input type='radio' id='thumbnail-radio' name='embed-type' value='thumbnail' /><label for='thumbnail-radio'>Thumbnail</label> \
<br /> \
<input type='radio' id='toggle' name='embed-type' value='string' /><label for='toggle'>Text</label> \
<input type='text' id='link-text' name='link-text' value='" + title + "' /> \
<div id='settings-action'> \
<button class='action' onclick='embed(this.parentNode.parentNode.parentNode.dataset.cachekey, this.parentNode.parentNode.parentNode.dataset.resourceid, this.parentNode.parentNode.parentNode.dataset.resourcetype)'>Get Video</button> \
<button onclick='this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode)'>Close</button> \
<div id='result'></div> \
</div>\
</div>";
return template;
}
let previewContainer = document.createElement('div');
previewContainer.setAttribute('class', 'preview-container');
previewContainer.dataset.resourceid = data.resourceId;
previewContainer.dataset.resourcetype = data.resourceType;
previewContainer.dataset.cachekey = data.cacheKey;
if (data.resourceType === "channel") {
previewContainer.innerHTML = '<img src="' + data.preview.high.url + '" />';
} else {
previewContainer.innerHTML = data.preview.items[0].player.embedHtml;
}
container.appendChild(previewContainer);
previewContainer.insertAdjacentHTML('beforeend', settings(data.id, data.title));
progress.style.display = "none";
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
}).DTApi('DT', 'preview', cacheKey, resourceId, resourceType);
}
function search(page, key) {
const progress = document.querySelector("#progress");
progress.style.display = "block";
// If there's a page token, set it
var pageToken = page || "";
var key = key || "";
let term = document.querySelector('#search-input').value;
let checked = document.querySelectorAll('input[name="queryArg"]:checked');
let prev = document.querySelector("#prev");
let next = document.querySelector("#next");
let total = document.querySelector("#total-results");
// Get the checked search types
let args = {};
args.types = [];
// TODO: Validate that there is at least _one_ checked box
// Default to videos
checked.forEach(function(el) {
args.types.push(el.value);
});
args.pageToken = page;
args.key = key;
const container = document.querySelector('#search-result');
container.innerText = ('Searching...');
google.script.run.withSuccessHandler(function(result) {
container.innerText = '';
let data = JSON.parse(result);
console.log(data.data.length);
if (data.data.length === 0) {
container.insertAdjacentHTML('beforeend', '<p>No videos found in your search! Try another search term.</p>');
}
let videoContainers = [];
for (var i = 0; i < data.data.length; i++) {
videoContainers.push(data.data.splice(0, 10))
}
console.log(videoContainers);
videoContainers.forEach(function(items) {
items.forEach(function(vid) {
container.insertAdjacentHTML('beforeend', vid);
});
});
if (data.nextPage == undefined) {
next.disabled = true;
} else {
next.disabled = false;
next.dataset.page = data.nextPage;
next.dataset.cachekey = data.nextKey;
}
if (data.prevPage == undefined) {
prev.disabled = true;
} else {
prev.disabled = false;
prev.dataset.page = data.prevPage;
prev.dataset.cachekey = data.prevKey;
}
document.querySelector('#pagination').style.display = 'block';
progress.style.display = "none";
}).DTApi('DT', 'search', term, args);
}
function getPage(el) {
let page = el.dataset.page;
let key = el.dataset.cachekey;
search(page, key)
}
function paginate(array, page) {
return array.slice(page * 10, 10)
}
$("#doc").click(function() {
google.script.run.withSuccessHandler(showFrames).getVideos();
})
$("#comments").click(function() {
google.script.run.withSuccessHandler(showFrames).getCommentData();
});
function showFrames(frames) {
$("#embed").empty();
console.log(frames.length);
for (var i = 0; i < frames.length; i++) {
$("#embed").append("<iframe src='https://youtube.com/embed/" + frames[i] + "' width='100%' height='480' frameborder='0' allowfullscreen></iframe>");
}
}
#progress {
display: none;
position: absolute;
right: 70px;
top: -5.5px;
}
.search {
width: 80%;
margin: 0 auto;
position: relative;
}
.search>input[type="text"] {
width: 60%;
margin-right: 10px;
}
.search>#search-args {
width: 60%;
}
#search-result {
margin-top: 15px;
min-height: 400px;
display: flex;
display: -webkit-flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
align-content: center;
}
#search-result>div {
transition: box-shadow ease-in-out 0.25s;
width: 300px;
height: 180px
}
#search-result>.video-container:hover {
box-shadow: 0 0 5px blue;
cursor: pointer;
}
#pagination {
display: none;
text-align: right;
margin-right: 20px;
}
#preview {
margin: 15px auto 0;
}
.settings {
display: inline-block;
vertical-align: middle;
width: 35%;
position: relative;
}
#result {
display: inline-block;
margin-left: 15px;
}
#preview img {
width: 45%;
height: auto;
}
#preview iframe,
img {
vertical-align: middle;
}
#preview iframe+.settings {
margin-left: 30px;
}
#preview img+.settings {
margin-left: 30px;
}
.settings>label {
line-height: 36px;
}
#link-text {
visibility: hidden;
font-size: 18px;
margin-bottom: 15px;
margin-left: 15px;
width: 60%;
}
#toggle:checked~#link-text {
visibility: visible;
}
.settings>button {
display: block;
margin-bottom: 15px;
}
.video-container {
background-position: center center;
background-size: cover;
position: relative;
flex: 0 0 auto;
margin: 5px;
}
.type-icon {
display: block;
position: absolute;
bottom: 10px;
right: 10px;
height: 32px;
width: 32px;
}
.action-container {
display: block;
position: absolute;
top: 50%;
transform: translateY(-50%);
height: 65px;
background-color: rgba(250, 250, 250, 0.75);
width: 100%;
text-align: center;
opacity: 0;
transition: all ease-in-out 0.5s;
}
.action-container>span {
padding: 5px;
line-height: 65px;
font-size: 24px;
}
span:hover {
cursor: pointer;
transition: all ease-in-out 0.15s;
}
.video-container:hover>.action-container {
opacity: 1;
}
#embed {
width: 100%;
font-family: sans-serif;
}
#srcSelect {
width: 100%;
margin-bottom: 10px;
}
#srcSelect span {
display: inline-block;
margin-right: 15px;
color: rgba(255, 255, 255, 1);
background-color: rgba(0, 0, 255, 0.8);
cursor: pointer;
border-radius: 3px;
border: 1px solid rgba(0, 0, 180, 0.8);
padding: 12px;
}
#srcSelect span:hover {
color: rgba(0, 0, 180, 1);
background-color: rgba(255, 255, 255, 0.8);
}
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<div class="search">
<input type="text" id="search-input" value="" />
<button id="search-btn" class="action" onclick="search(null)">Search</button>
<button onclick="document.querySelector('#search-result').innerHTML = ''">Clear</button>
<svg id="progress" version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
<path opacity="0.2" fill="#00d" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/>
<path fill="#00d" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
C22.32,8.481,24.301,9.057,26.013,10.047z">
<animateTransform attributeType="xml"
attributeName="transform"
type="rotate"
from="0 20 20"
to="360 20 20"
dur="0.5s"
repeatCount="indefinite"/>
</path>
</svg>
<div id="search-args">
<label><input type="checkbox" name="queryArg" value="video" checked="checked"/>Videos</label>
<label><input type="checkbox" name="queryArg" value="channel" />Channels</label>
<label><input type="checkbox" name="queryArg" value="playlist" />Playlists</label>
</div>
</div>
<div id="preview"></div>
<div id="pagination">
<button id="prev" data-page="" onclick="getPage(this)">Previous</button>
<button id="next" data-page="" onclick="getPage(this)">Next</button>
</div>
<div id="search-result"></div>
The error i'm getting is :
"uncaught reference error: google is not defined"
the error says the issue occurs within line 360. i copied the whole ass code, line for line, from the original editor, where line 360 is:
} else {
the hell should i do? i have looked over the code relentlessly for the past 3 days and have found no evidence of an error other than the fact the search results never come through. i am truly stumped on this one and i need the coding cavalry.
As a user said in the comments, google object is automatically imported in the html file when you're using Apps Script [1]. You need to delete this line: <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=..." async defer></script>, which is causing the error as explained in this other question [2].
[1] https://developers.google.com/apps-script/guides/html/reference/run
[2] Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Know when each element have same CSS property value

I'm making a form using some circles to show the user whether the field is correctly filled or not.
I want to be able to know when all of the circles are green to then change the SUBMIT button background-color.
If you didn't understand just run the snippet full screen and you'll see.
// Système de toggleBox
var toggleCanvas = document.getElementById('newsteller');
let n_state = true;
function toggleNewsteller() {
if (getComputedStyle(document.getElementById('newsteller')).backgroundColor == "rgb(180, 223, 180)") {
n_state = false;
} else {
n_state = true;
}
if (n_state == false) {
document.getElementById('newsteller').style.backgroundColor = "hsl(120, 3%, 93%)";
} else if (n_state == true) {
document.getElementById('newsteller').style.backgroundColor = "rgb(180, 223, 180)";
}
}
function blur_check(id) {
var element_base = document.getElementById(id);
var circleSibling = getCircle(element_base);
if (getComputedStyle(circleSibling).backgroundColor == "rgb(237, 238, 237)") {
circleSibling.style.backgroundColor = 'rgb(180, 223, 180)';
}
if (element_base.value == "") {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
function characters_check(sample) {
var arr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "#", ";", ":", "/", "+", ")", "&", "(", "?", "!", "-", "_", "%", "*", ":", ";", "`", "^", "$"]
for (var i = arr.length - 1; i >= 0; --i) {
if (sample.indexOf(arr[i]) != -1) {
return true;
}
}
}
function passwordBlur() {
var element = document.getElementById('mdpbis');
var circleSibling = getCircle(element);
if (getComputedStyle(circleSibling).backgroundColor == "rgb(237, 238, 237)") {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
function email_check() {
var circleSibling = getCircle(document.getElementById('email'));
var emailString = document.getElementById('email').value;
var arr = ["#"]
for (var i = arr.length - 1; i >= 0; --i) {
if (emailString.indexOf(arr[i]) != -1) {
var arr = ["."]
for (var i = arr.length - 1; i >= 0; --i) {
if (emailString.indexOf(arr[i]) != -1) {
circleSibling.style.backgroundColor = 'rgb(180, 223, 180)';
} else {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
} else {
circleSibling.style.backgroundColor = 'rgb(255, 127, 123)';
}
}
}
function getCircle(elements) {
while (elements = elements.nextSibling) {
if (elements.className === 'circle') {
return elements;
}
}
return false
}
function prenom_confirmation() {
var prenom = document.getElementById('prenom');
var circleStyle = getCircle(prenom).style;
if (characters_check(prenom.value) == true) {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
} else {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
}
}
function nom_confirmation() {
var nom = document.getElementById('nom');
var circleStyle = getCircle(nom).style;
if (characters_check(nom.value) == true) {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
} else {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
}
}
function username_confirmation() {
var username = document.getElementById('username');
var circleStyle = getCircle(username).style;
if (characters_check(username.value) == true) {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
} else {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
}
}
function email_confirmation() {
var email = document.getElementById('email');
var circleStyle = getCircle(email).style;
if (characters_check(email.value) == true) {
circleStyle.backgroundColor = "rgb(237, 238, 237)";
} else {
circleStyle.backgroundColor = 'rgb(255, 127, 123)';
}
}
function mdp_confirmation() {
mdp_check()
var mdp = document.getElementById('mdp');
var circleStyle = getCircle(mdp).style;
if (characters_check(mdp.value) == true && mdp.value.length >= 6) {
circleStyle.backgroundColor = 'rgb(180, 223, 180)';
} else {
circleStyle.backgroundColor = '#FFE68D';
}
}
function mdp_check() {
var mdp = document.getElementById('mdp');
var circleMdp = getCircle(mdp);
var mdpbis = document.getElementById('mdpbis');
var circleMdpbis = getCircle(mdpbis);
if (mdpbis.value == mdp.value) {
circleMdpbis.style.backgroundColor = getComputedStyle(circleMdp).backgroundColor;
} else if (mdpbis.value !== mdp.value) {
circleMdpbis.style.backgroundColor = "rgb(237, 238, 237)";
}
}
* {
margin: 0px;
padding: 0px;
font-family: 'Futura', sans-serif;
-webkit-font-smoothing: anatialised;
}
::selection {
background: wheat;
}
a {
text-decoration: none;
}
body {
background: #DEDEDE;
}
input:focus,
select:focus {
outline: none;
}
.login-form-window {
margin-top: 50px;
width: 90%;
margin-left: 5%;
background: white;
display: block;
box-shadow: 1px 10px 40px 0px rgba(0, 0, 0, 0.10);
}
.window-header {
background: wheat;
color: hsl(120, 3%, 30%);
font-size: 28px;
padding: 10px;
font-weight: 100;
font-weight: 100;
}
.window-info {
padding: 10px;
color: hsl(120, 3%, 60%);
}
.description {
font-size: 19px;
color: hsl(120, 2%, 20%);
padding: 10px;
}
.input-des {
color: hsl(120, 3%, 35%);
margin: 10px;
}
.padding-right {
margin-right: 30px;
}
.form_col {
display: inline-block;
margin-right: 15px;
padding: 3px 0px;
width: 300px;
min-height: 1px;
text-align: right;
}
.text-input {
border: none;
background: hsl(120, 3%, 93%);
width: 150px;
height: 30px;
border-radius: 5px;
padding-left: -2px;
font-size: 15px;
text-align: center;
text-decoration: none;
}
.circle {
margin-left: 20px;
height: 30px;
width: 30px;
border-radius: 15px;
background-color: hsl(120, 3%, 93%);
vertical-align: bottom;
}
.select-country {
height: 30px;
border: none;
background: hsl(120, 3%, 93%);
font-size: 15px;
}
.checkbox {
width: 22px;
height: 22px;
border: none;
background: rgb(180, 223, 180);
border-radius: 4px;
vertical-align: sub;
}
.checkbox,
.submit-button {
cursor: pointer;
}
.submit-button {
padding: 3px 0px;
display: inline-block;
margin-right: 15px;
width: 300px;
border-radius: 5px;
text-align: center;
width: 200px;
background-color: hsl(120, 3%, 93%);
font-size: 19px;
color: hsl(120, 3%, 30%);
}
.submit-button::selection {
background: none;
}
#text::selection {
background: none;
}
<section class="login-form-window">
<p class="window-header">CREER UN COMPTE</p>
<p class="window-info"><a>Samedi 5 Mai</a><a style="float:right">Formulaire d'Inscription</a></p><br>
<form id="form">
<label class="description form_col" id="sex">Sexe:</label>
<input type="radio" name="sex" value="H" class="radio-input" checked="1"><label class="input-des padding-right">Homme</label>
<input type="radio" name="sex" value="F" class="radio-input"><label class="input-des padding-right">Femme</label>
<input type="radio" name="sex" value="O" class="radio-input"><label class="input-des">Autre</label><br><br>
<label class="description form_col">Prénom:</label>
<input id="prenom" type="text" name="prenom" value="" oninput="prenom_confirmation()" class="text-input prenom" autocomplete="given-name" onblur="blur_check('prenom')">
<canvas class="circle"></canvas>
<br><br>
<label class="description form_col">Nom:</label>
<input id="nom" type="text" name="nom" value="" oninput="nom_confirmation()" class="text-input nom" autocomplete="name" onblur="blur_check('nom')">
<canvas class="circle" id="nom"></canvas>
<br><br>
<label class="description form_col">Username:</label>
<input id="username" type="text" name="username" value="" oninput="username_confirmation()" class="text-input username" autocomplete="username" onblur="blur_check('username')">
<canvas class="circle" id="username"></canvas>
<br><br>
<label class="description form_col">Email:</label>
<input id="email" type="text" name="email" value="" class="text-input email" autocomplete="name" onblur=" email_check()" style="width:200px;">
<canvas class="circle" id="email"></canvas>
<br><br>
<label class="description form_col">Mot de passe:</label>
<input id="mdp" type="password" name="mdp" value="" oninput="mdp_confirmation()" class="text-input mdp" autocomplete="new-password" onblur="blur_check('mdp')">
<canvas class="circle" id="mdp"></canvas>
<br><br>
<label class="description form_col">Mot de passe (confirmation):</label>
<input id="mdpbis" type="password" name="mdpbis" value="" class="text-input mdpbis" autocomplete="new-password" oninput="mdp_check()" onblur="passwordBlur()">
<canvas class="circle" id="mdp-bis"></canvas>
<br><br>
<label class="description form_col">Pays de résidence:</label>
<select class="select-country" name="country">
<option value="">France</option>
<option value="">Belgique</option>
<option value="">Suisse</option>
<option value="">Luxembourg</option>
<option value="">États Unis</option>
<option value="">Allemagne</option>
<option value="">Pays-Bas</option>
<option value="">Norvège</option>
</select>
<br><br>
<label class="description form_col">Newsteller:</label>
<canvas class="checkbox" id="newsteller" onclick="toggleNewsteller()"></canvas><br><br>
<label class="description form_col"></label>
<div class="form_col submit-button" id="newsteller" onclick="">SUBMIT</div>
<br><br>
</form>
</section>
Just loop through each circle and check it's background-color value like this:
var x = document.querySelectorAll('.circle'); // get all circle elements
var y="";
x.forEach(circ => { //loop through each circle to check bg-color
if (circ.style.backgroundColor !== 'rgb(180, 223, 180)') {
y += '0';
} else {
y += '1';
}
});
if ( y.indexOf("0") > -1 ) { // are there red circles?
console.log('dont do anything'); //yes there are
} else {
console.log('run submit button css change function'); // no there aren't. go ahead and run a function to change submit css here
}
However, as #TemaniAfif mentioned, I would suggest you add the background-color for green to a css class say, green and red then toggle them like this:
if (emailString.indexOf(arr[i]) != -1) {
circleSibling.classList.add('green');
circleSibling.classList.remove('red');
} else {
circleSibling.classList.add('red');
circleSibling.classList.remove('green');
}
And replace the first snippet above with this:
var x = document.querySelectorAll('.circle'); // get all circle elements
x.forEach(circ => { //loop through each circle to check bg-color
if (circ.classList.contains('green')) {
y += '1';
} else {
y += '0';
}
});
if ( y.indexOf("0") > -1 ) { // are there red circles?
console.log('dont do anything'); //yes there are
} else {
console.log('run submit button css change function'); // no there aren't. go ahead and run a function to change submit css here
}
Toggling css classes instead of inline styles is cleaner and shorter too if you have a lot of circles which results in better site performance.

A issue with the javascript event Object

I am teaching myself JavaScript and to improve my programming logic I decided to make a Hangman game. Everything works but I am having a problem with the win or lose function. The logic is If the indexCompare array length is === to correctGuesses Array length. Display You win If your lives are === to 0 Display you lose. But for some reason when a correct guess is pushed to the correctGuesses Array if it is a letter that appears more then once in the word. Only 1 occurrence of that letter is added to the array. So certain words never result in a win. And the win condition is never fulfilled. And I think it has something to do with me getting the value from the event Object. I might be wrong though. Any help would be greatly appreciated.
var gameCore = window.onload = function() {
var hangmanWords = ["super", "venus", "spanish", "darkness", "tenebris", "meatball", "human", "omega", "alpha", "isochronism", "supercalifragilisticexpialidocious"];
var commentsArray = ["I belive in you! You can do the thing!", "There is still hope keep trying", "Third times a charm", "You can do this", "Think player think! The counter is almost out", "Never give up", "The last melon 0.0", "What the frog you had one job u_u"];
var hints = ["The opposite of ordinary.", "A planet in are solar system.", "One of the largest languages in the world", "The opposite of light", "A rare word for darkness", "A tasty kind of sphear AKA 'ball' ", "You are A?", "A letter in the greek alphabet.", "Another letter in the greek alphabet.", "A word about time that almost no one uses.", "A big word that you know if you have seen mary poppins but never use."]
var correctGuesses = [];
var lives = 7;
var indexCompare = [];
var choosenWord = []
var arrayCounter = [];
//get elements
var showHint = document.getElementById("hint");
var showLivesLeft = document.getElementById("lives");
var showComments = document.getElementById("comment");
var showLoseOrWin = document.getElementById("winOrLoseDisplay");
// click assigner function
var clickAssigner = function(event) {
var letterHandler = document.getElementsByClassName("letters");
for (var i = 0; i < letterHandler.length; i++) {
letterHandler[i].addEventListener("click", compare, false);
}
var hintHandler = document.getElementById("hint");
hintHandler.addEventListener("click", hint, false);
}
clickAssigner(event);
function hint(event) {
if (arrayCounter[0] === 0) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 1) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 2) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 3) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 4) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 5) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 6) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 7) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 8) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 9) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 10) {
showHint.innerHTML = hints[arrayCounter]
};
}
// word selector and display function
// arrayCounter is the same as i
function wordSelector() {
var randomNumber = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
arrayCounter.push(randomNumber);
var livesContainer = document.createElement("p");
var livesNumber = lives;
showLivesLeft.setAttribute("id", "livesNumbers");
showLivesLeft.appendChild(livesContainer);
livesContainer.innerHTML = livesNumber;
var selectedWord = hangmanWords[arrayCounter];
var wordDisplay = document.getElementById("wordDisplay");
var correctWordDisplay = document.createElement("ul");
var playerGuess;
for (var i = 0; i < selectedWord.length; i++) {
correctWordDisplay.setAttribute("id", "correctWordDisplay-UL");
playerGuess = document.createElement("li");
playerGuess.setAttribute("class", "playerGuess");
playerGuess.innerHTML = "_";
indexCompare.push(playerGuess);
wordDisplay.appendChild(correctWordDisplay);
correctWordDisplay.appendChild(playerGuess);
}
}
wordSelector();
// compare function // decrement lives function // remove health bar
function compare(event) {
var livesDisplay = document.getElementById("livesNumbers");
var btnVal = event.target.value;
var word = hangmanWords[arrayCounter];
for (var i = 0; i < word.length; i++) {
if (word[i] === btnVal) {
indexCompare[i].innerHTML = btnVal;
}
}
var c = word.indexOf(btnVal);
if (c === -1) {
event.target.removeAttribute("letters");
event.target.setAttribute("class", "incorrectLetter");
event.target.removeEventListener("click", compare);
lives -= 1;
livesDisplay.innerHTML = lives;
} else {
event.target.removeAttribute("letters");
event.target.setAttribute("class", "correctLetter");
event.target.removeEventListener("click", compare);
correctGuesses.push(event.target.value);
}
comments();
winOrLose();
// console.log(event);
// console.log(word);
}
// comment function
function comments() {
if (lives === 7) {
showComments.innerHTML = "<p>" + commentsArray[0] + "</p>"
};
if (lives === 6) {
showComments.innerHTML = "<p>" + commentsArray[1] + "</p>"
};
if (lives === 5) {
showComments.innerHTML = "<p>" + commentsArray[2] + "</p>"
};
if (lives === 4) {
showComments.innerHTML = "<p>" + commentsArray[3] + "</p>"
};
if (lives === 3) {
showComments.innerHTML = "<p>" + commentsArray[4] + "</p>"
};
if (lives === 2) {
showComments.innerHTML = "<p>" + commentsArray[5] + "</p>"
};
if (lives === 1) {
showComments.innerHTML = "<p>" + commentsArray[6] + "</p>"
};
if (lives === 0) {
showComments.innerHTML = "<p>" + commentsArray[7] + "</p>"
};
}
// win or lose function
function winOrLose() {
for (var i = 0; i < indexCompare.length; i++) {
if (indexCompare.length === correctGuesses.length) {
showLoseOrWin.innerHTML = "<p>" + "YOU WIN!!! :D" + "</p>";
}
}
if (lives === 0) {
showLoseOrWin.innerHTML = "<p>" + "YOU LOSE u_u" + "</p>";
}
}
function reset() {
}
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html,body,div,span,applet,object,iframe,h1,h2,
h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,
img,ins,kbd,q,
s,samp,small,strike,strong,sub,sup,tt,var,b,u,
i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,
legend,table,caption,tbody,tfoot,thead,tr,th,
td,article,aside,canvas,details,embed,figure,figcaption,
footer,header,hgroup,menu,nav,output,ruby,section,
summary,time,mark,audio,video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {
display: block;
}
body {
line-height: 1;
}
ol,ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
#container {
overflow: hidden;
max-width: 60%;
background-color: yellowgreen;
margin: 7em auto;
padding: 1em;
}
#wordDisplay {
height: 6em;
background-color: orangered;
margin-bottom: 0.2em;
text-align: center;
padding-top: 2.4em;
font-size: 26px;
display: flex;
justify-content: center;
}
#correctWordDisplay-UL {
list-style: none;
display: flex;
justify-content: center;
}
.playerGuess {
margin: 0em 0.08em;
font-size: 30px;
}
#hint {
max-width: 26em;
padding: 1em;
background-color: skyblue;
border: 0.5em ridge gold;
font-weight: 900;
margin: 0em auto 1em auto;
text-align: center;
}
#hint:hover {
background-color: coral;
cursor: pointer;
font-style: oblique;
}
#letterDiplay {
width: 14em;
float: left;
text-align: center;
background: crimson;
padding: 1em;
}
.letters {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background-color: darkorange;
border: 3px ridge darkblue;
}
.letters:hover {
background: steelblue;
color: white;
cursor: pointer;
}
#theChanceCounter {
text-align: center;
float: right;
width: 14em;
background-color: crimson;
height: 28.9em;
}
/* #lives{
width: 3em;
height: 3em;
margin: 1em auto 0em auto;
background-color: teal;
color: black;
font-weight: 900;
text-align: center;
} */
#livesNumbers {
margin-top: 1em;
border: 3px solid black;
width: 3em;
height: 3em;
padding: 0.9em 0em 0em 0em;
margin: 1em auto 0em auto;
background-color: teal;
color: black;
font-weight: 900;
text-align: center;
}
.correctLetter {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background: green;
color: yellow;
}
.incorrectLetter {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background: red;
color: yellow;
}
#comment {
background-color: forestgreen;
width: 12em;
height: 4em;
padding: 1em 0.4em 0em 0.4em;
margin: 0.3em auto 0.3em auto;
border: 3px solid black;
}
#winOrLoseDisplay {
width: 18em;
padding: 1em;
background-color: skyblue;
border: 0.5em ridge orange;
font-weight: 900;
margin: 0em auto 1em 1.4em;
text-align: center;
float: left;
}
<div id="container">
<section id="wordDisplay">
</section>
<section id="hint">Click for hint.</section>
<section id="letterDiplay">
<button class="letters" value="a">A</button>
<button class="letters" value="b">B</button>
<button class="letters" value="c">C</button>
<button class="letters" value="d">D</button>
<button class="letters" value="e">E</button>
<button class="letters" value="f">F</button>
<button class="letters" value="g">G</button>
<button class="letters" value="h">H</button>
<button class="letters" value="i">I</button>
<button class="letters" value="j">J</button>
<button class="letters" value="k">K</button>
<button class="letters" value="l">L</button>
<button class="letters" value="m">M</button>
<button class="letters" value="n">N</button>
<button class="letters" value="o">O</button>
<button class="letters" value="p">P</button>
<button class="letters" value="q">Q</button>
<button class="letters" value="r">R</button>
<button class="letters" value="s">S</button>
<button class="letters" value="t">T</button>
<button class="letters" value="u">U</button>
<button class="letters" value="v">V</button>
<button class="letters" value="w">W</button>
<button class="letters" value="x">X</button>
<button class="letters" value="y">Y</button>
<button class="letters" value="z">Z</button>
</section>
<section id="winOrLoseDisplay"></section>
<section id="theChanceCounter">
<div id="lives">
</div>
<div id="comment">
</div>
</section>
</div>
</script>

Categories