So whenever the moves variable is equal to 10 (why 10 and not 9? I dunno the moves variable increases 2 times instead of 1 the last time xD), the alert that the game is a draw does not happen and why's that?
I'm making a tic tac toe game by the way.
var moves = 0;
var randomOneTwo = doGetRandom(1,2)
var randomPlayBot = 0;
var turn = randomOneTwo == 1 ? "X": "O"
var score1 = 0;
var score2 = 0;
var win = 0;
var canPlay = false;
var dummy = score2;
var dummy2 = score1;
var whoWon = 5;
window.addEventListener("load", _loaded);
function _loaded() {
document.getElementById("plpl").textContent = "The Player " + turn + " is playing."
var ids = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9'];
var vale = [0, 0, 0, 0, 0, 0, 0, 0, 0 ,0];
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).addEventListener("click", doSet);
}
addEventListener("click", bot);
addEventListener("click", doWin);
function doSet(){
if (this.innerHTML !== "") {
return;
}
this.innerHTML = turn;
moves++
canPlay = true;
turn == "X" ? turn = "O": turn = "X"
document.getElementById("plpl").textContent = "The Player " + turn + " is playing."
turn == "X" ? vale[nc] = 100: vale[nc] = -100;
}
function bot(){
if ((canPlay == true) && (document.getElementById("bplays").checked == true)) {
do{
randomPlayBot = doGetRandom(0, 8)
}
while(document.getElementById(ids[randomPlayBot]).innerHTML !== "" && moves < 8)
document.getElementById(ids[randomPlayBot]).innerHTML = turn;
moves++
turn == "X" ? turn = "O": turn = "X"
document.getElementById("plpl").textContent = "The Player " + turn + " is playing."
turn == "X" ? vale[randomPlayBot] = 100: vale[randomPlayBot] = -100;
canPlay = false;
}
}
function doWin(){
console.log(vale)
let sum1 = vale[0] + vale[1] + vale[2];
let sum2 = vale[3] + vale[4] + vale[5];
let sum3 = vale[6] + vale[7] + vale[8];
let sum4 = vale[0] + vale[3] + vale[6];
let sum5 = vale[1] + vale[4] + vale[7];
let sum6 = vale[2] + vale[5] + vale[8];
let sum7 = vale[0] + vale[4] + vale[8];
let sum8 = vale[2] + vale[4] + vale[6];
for (i = 0; i <= 8; i++) {
if ((sum1 == 300 || sum2 == 300 || sum3 == 300 || sum4 == 300 || sum5 == 300 || sum6 == 300 || sum7 == 300 || sum8 == 300)) {
whoWon = 1;
score2 == dummy ? score2++:
document.getElementById("sc1").innerHTML = "O: " + score2;
for (j = 0; j < ids.length; j++) {
document.getElementById(ids[j]).textContent = ""
}
canPlay = false;
moves = 0;
}
else if ((sum1 == -300 || sum2 == -300 || sum3 == -300 || sum4 == -300 || sum5 == -300 || sum6 == -300 || sum7 == -300 || sum8 == -300)) {
whoWon = -1;
score1 == dummy2 ? score1++:
document.getElementById("sc2").innerHTML = "X: " + score1;
for (j = 0; j < ids.length; j++) {
document.getElementById(ids[j]).textContent = ""
}
canPlay = false;
moves = 0;
}
else if(moves == 10){
whoWon = 0;
for (j = 0; j < ids.length; j++) {
document.getElementById(ids[j]).textContent = ""
}
canPlay = false;
moves = 0;
}
else{
return;
}
}
if (whoWon == 1) {
alert("The Player O won and so he gets 1 point!")
}
else if(whoWon == -1){
alert("The Player X won and so he gets 1 point!")
}
else if(whoWon == 0){
alert("It's a draw and so nobody won any points!");
}
whoWon = 5;
dummy = score2;
dummy2 = score1;
sum1 = 0;
sum2 = 0;
sum3 = 0;
sum4 = 0;
sum5 = 0;
sum6 = 0;
sum7 = 0;
sum8 = 0;
for(k = 0; k <= 8; k++){
vale[k] = 0;
}
}
}
function doGetRandom(min, max) {
let h = Math.random() * (max - min) + min;
return Math.round(h);
}
function doGetNum(n){
nc = n;
}
-------------------------------------------------------------//--------------------------------------------------------------------
Edit 1: Html
<h1 class="hd-1" id="plpl"></h1>
<table>
<tr>
<td id="sc1">O: 0</td>
<td id="sc2">X: 0</td>
</tr>
</table>
<table id="tb-ttt">
<tr>
<td class="td-ttt" id="b1" onclick="doGetNum('0')"></td>
<td class="td-ttt" id="b2" onclick="doGetNum('1')"></td>
<td class="td3-ttt" id="b3" onclick="doGetNum('2')"></td>
</tr>
<tr>
<td class="td-ttt" id="b4" onclick="doGetNum('3')"></td>
<td class="td-ttt" id="b5" onclick="doGetNum('4')"></td>
<td class="td3-ttt" id="b6" onclick="doGetNum('5')"></td>
</tr>
<tr>
<td class="td2-ttt" id="b7" onclick="doGetNum('6')"></td>
<td class="td2-ttt" id="b8" onclick="doGetNum('7')"></td>
<td class="td4-ttt" id="b9" onclick="doGetNum('8')"></td>
</tr>
</table>
<form name="F">
Player vs CPU <input type="radio" name="bot" value="" checked id="bplays">
Player vs Player <input type="radio" name="bot" value="" id="plvpl">
</form>
Related
so i have this error:
quiz.js:121 Uncaught TypeError: Cannot set properties of undefined (setting 'innerHTML')
at pytanie (quiz.js:121:28)
at czas (quiz.js:24:5)
at onload (quiz2.html:9:23)
I tried solve it for 3 days but still i don't know what is a problem. I will be very glad if you can help me!
code:
function czas()
{
var i = 59;
var min = 5;
window.myinterval = setInterval(function() {
document.getElementById('czas').innerHTML = "Pozostały czas: " + min + ": " + i;
if(i == 0 && min == 0)
{
clearInterval(myinterval);
getwyniki();
}
else
{
i--;
if(i == 0 && min > 0)
{
i = 1;
min--;
}
}
}, 3000);
pytanie();
}
function getwyniki() {
clearInterval(myinterval);
var amountCorrect = 0;
for(var i = 0; i <= 5; i++)
{
var radiosname = document.getElementsByName('pytanie' + i);
for(var j = 0; j < radiosname.length; j++)
{
var radiosvalue = radiosname[j];
if(radiosvalue.checked){
if(radiosvalue.value == 't')
{
amountCorrect++;
radiosvalue.nextSibling.style.color = "green";
}
else
{
radiosvalue.nextSibling.style.color = "red";
}
}
else
{
radiosvalue.nextSibling.style.color = "";
}
}
}
if(amountCorrect <= 10 && amountCorrect >= 8)
{
document.getElementById('ocena').innerHTML = ("Twoja ocena to: " + 5);
}
if(amountCorrect == 7)
{
document.getElementById('ocena').innerHTML = ("Twoja ocena to: " + 4);
}
if(amountCorrect == 6)
{
document.getElementById('ocena').innerHTML = ("Twoja ocena to: " + 3);
}
if(amountCorrect == 5)
{
document.getElementById('ocena').innerHTML = ("Twoja ocena to: " + 2);
}
if(amountCorrect < 5)
{
document.getElementById('ocena').innerHTML = ("Twoja ocena to: " + 1);
}
document.getElementById('wyniki').innerHTML = "Poprawnie udzielone odpowiedzi: " + amountCorrect + "<br>" + "<h3>dobrze odpowiedzi były to:<br> 1.a <br> 2.c<br> 3.d<br> 4.a</h3>";
}
function pytanie()
{
var pytanie = ["pytanie 1", "pytanie 2", "pytanie 3", "pytanie 4", "pytanie 5", "pytanie 6", "pytanie 7", "pytanie 8", "pytanie 9", "pytanie 10",];
var ask = pytanie.slice();
var tmpArray =[0];
var pname = [];
for(var i = 0; i <= 5; i++)
{
//document.getElementById('p1').innerHTML = "sda";
//console.log('i :' +i);
var tmp = i+1;
if (tmp < 5)
{
pname[i] = document.getElementById('p' + tmp);
console.log(pname[i]);
}
if (i == 0)
{
tmpArray[0] = Math.floor(Math.random() * ask.length);
}
else
{
do
{
var flag = false;
var liczba = Math.floor(Math.random() * ask.length);
for(var j = 0; j < tmpArray.length;j++)
{
console.log("liczba: " + liczba + "ar: " + tmpArray[j]);
if (liczba == tmpArray[j])
flag = true;
}
}while(flag == true);
tmpArray.push(liczba);
}
}
for(var j = 0; j < pytanie.length; j++)
{
console.log('tmp: ' + tmpArray[j]);
//console.clear();
pname[j].innerHTML = pytanie[tmpArray[j]];
console.log('pname: ' + pname[j]);
}
}
html:
<p id="p1"></p>
<input type="radio" name="pytanie1" value="t"><span>a)</span>
<input type="radio" name="pytanie1" value="f"><span>b)</span>
<input type="radio" name="pytanie1" value="f"><span>c)</span>
<input type="radio" name="pytanie1" value="f"><span>d)</span>
<h3>Pytanie 2</h3>
and same 3 more blocks with id's + 1. ^
id's: p1, p2, p3, p4. This error doesn't do anything for my quiz but i want my quiz clear without errors.
I tried change id's, delete table and make new but it doesn't do anything. But i saw that when I delete [j] from "pname[j].innerHTML = pytanie[j];" then the error disappear, but if i delete [j] it will assign same question to that id's. I want to assign random question to id's p1 p2 p3 p4 and I tried anything what i know and what i find in internet.
Based on the response in the comment the problem was pname[j].innerHTML = pytanie[tmpArray[j]];.
And more precisely the loop for(var j = 0; j < pytanie.length; j++) where pytanie.length was used instead of pname.length.
Because pytanie has more elements then pname this resulted in an out-of-bounds access at pname[j].innerHTML with the result that pname[j]. evaluates to undefined.
I'm programming a checkers game for a high school project. I have a weird variable behaviour and I can't figure out why it's happening. Let me show you the code:
var player = 1;
var lastClicked;
var wasClicked = false;
var isEmpty = new Array(8);
for (var i = 0; i < 8; i++) {
isEmpty[i] = new Array(8);
for (var j = 0; j < 8; j++) {
isEmpty[i][j] = true;
}
}
function CreateBoard() {
var board = document.createElement("table");
board.cellSpacing = 0;
for (var i = 0; i < 8; i++) {
var tr1 = document.createElement("tr");
for (var j = 0; j < 8; j++) {
var td1 = document.createElement("td");
td1.setAttribute("id", "td" + i + j);
td1.addEventListener("click", function () { CheckIandJForLater(i, j); });
if (i % 2 == 0) {
if (j % 2 == 0)
td1.style.backgroundColor = "beige";
else
td1.style.backgroundColor = "black";
}
else {
if (j % 2 == 0)
td1.style.backgroundColor = "black";
else
td1.style.backgroundColor = "beige";
}
tr1.appendChild(td1);
}
board.appendChild(tr1);
}
document.body.appendChild(board);
}
function CheckIandJForLater(i, j) { // A function which is meant to show the weird behavior, which prevents me from using function I want to use in the event listener
alert("Function i: " + i);
alert("Function j: " + j);
}
function DeployPieces() {
CreateBoard();
var pieceIndex = 1;
for (var i = 0; i < 8; i++) {
if (i < 3) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td1 = document.getElementById("td" + i + j);
var circle1 = document.createElement("span");
circle1.setAttribute("class", "redCircle");
circle1.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle1.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td1.appendChild(circle1);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td2 = document.getElementById("td" + i + j);
var circle2 = document.createElement("span");
circle2.setAttribute("class", "redCircle");
circle2.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle2.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td2.appendChild(circle2);
isEmpty[i][j] = false;
}
}
}
else if (i > 4) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td3 = document.getElementById("td" + i + j);
var circle3 = document.createElement("span");
circle3.setAttribute("class", "whiteCircle");
circle3.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle3.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td3.appendChild(circle3);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td4 = document.getElementById("td" + i + j);
var circle4 = document.createElement("span");
circle4.setAttribute("class", "whiteCircle");
circle4.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle4.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td4.appendChild(circle4);
isEmpty[i][j] = false;
}
}
}
}
}
function AlertToPressOnSquare() {
alert("Player " + player + ", please press on the square to which you would like to move the piece");
if (player == 1)
player = 2;
else if (player == 2)
player = 1;
}
function MoveToSquare(i, j) { //The function I want to use in the td1 event listener
if (wasClicked && isEmpty[i][j]) {
var lastClickedId = lastClicked.getAttribute("id");
var lastClickedLocation = lastClickedId[6] + lastClickedId[7];
var v1 = parseInt(lastClickedId[6], 10);
var v2 = parseInt(lastClickedId[7], 10);
var tdFrom = document.getElementById("td" + lastClickedLocation);
var tdTo = document.getElementById("td" + i.toString() + j.toString());
if (lastClicked.getAttribute("class") == "whiteCircle") {
if (v1 == i - 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
else if (lastClicked.getAttribute("class") == "redCircle") {
if (v1 == i + 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
alert("Player " + player + ", please press on the piece you would like to move");
wasClicked = false;
}
}
So, the weird behavior is as follows: Every time I click on a td in the table and run the CheckIandJForLater function, I get the value 8 for both i and j. They should not get these values, as i and j are supposed to be updated in the for loop. Moreover, they should never reach the value of 8, since both the loops run between 0 and 7.
It's also worth noting that if I put alert(i); and alert(j); regularly, without the CheckIAndJForLater function, their values are printed fine.
I really struglle in finding out how to solve this weird behavior. May someone help me? Thank you.
Why is that behavior happening? Is there a solution?
My mortgage calculator includes a down payment field for either a value or a percentage.
If the user enters a value, the percentage is calculated and displayed. If the user enters a percentage, the value is calculated and displayed.
The problem I am having is that once entered, only the value can be modified, not the percentage.
The relevant code is
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
Please see my jsfiddle
function fn(num, places, comma) {
var isNeg = 0;
if (num < 0) {
num = num * -1;
isNeg = 1;
}
var myDecFact = 1;
var myPlaces = 0;
var myZeros = "";
while (myPlaces < places) {
myDecFact = myDecFact * 10;
myPlaces = Number(myPlaces) + Number(1);
myZeros = myZeros + "0";
}
onum = Math.round(num * myDecFact) / myDecFact;
integer = Math.floor(onum);
if (Math.ceil(onum) == integer) {
decimal = myZeros;
} else {
decimal = Math.round((onum - integer) * myDecFact)
}
decimal = decimal.toString();
if (decimal.length < places) {
fillZeroes = places - decimal.length;
for (z = 0; z < fillZeroes; z++) {
decimal = "0" + decimal;
}
}
if (places > 0) {
decimal = "." + decimal;
}
if (comma == 1) {
integer = integer.toString();
var tmpnum = "";
var tmpinteger = "";
var y = 0;
for (x = integer.length; x > 0; x--) {
tmpnum = tmpnum + integer.charAt(x - 1);
y = y + 1;
if (y == 3 & x > 1) {
tmpnum = tmpnum + ",";
y = 0;
}
}
for (x = tmpnum.length; x > 0; x--) {
tmpinteger = tmpinteger + tmpnum.charAt(x - 1);
}
finNum = tmpinteger + "" + decimal;
} else {
finNum = integer + "" + decimal;
}
if (isNeg == 1) {
finNum = "-" + finNum;
}
return finNum;
}
function sn(num) {
num = num.toString();
var len = num.length;
var rnum = "";
var test = "";
var j = 0;
var b = num.substring(0, 1);
if (b == "-") {
rnum = "-";
}
for (i = 0; i <= len; i++) {
b = num.substring(i, i + 1);
if (b == "0" || b == "1" || b == "2" || b == "3" || b == "4" || b == "5" || b == "6" || b == "7" || b == "8" || b == "9" || b == ".") {
rnum = rnum + "" + b;
}
}
if (rnum == "" || rnum == "-") {
rnum = 0;
}
rnum = Number(rnum);
return rnum;
}
function computeForm(form) {
var VappraisedValue = document.calc.appraisedValue.value;
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
}
<form name="calc" method="post" action="#">
<table border='1' cellpadding='4' cellspacing='0'>
<tbody>
<tr>
<td nowrap>
Home value:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="appraised-value" type="number" min="0" max="10000000" step="25000" class="form-control" name="appraisedValue" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''" onblur="if(this.value=='')this.value=this.defaultValue">
</td>
</tr>
<tr>
<td nowrap>
Down payment:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="down-payment" type="number" min="0" max="10000000" step="5000" class="form-control" name="downPayment" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<input id="down-payment-percent" type="number" min="0" max="100" step="1" class="form-control" name="downPaymentPercent" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<span class="input-group-addon">%</span>
</td>
</tr>
</tbody>
</table>
</form>
The issue is the way you are updating the Payment / Percent values - every time either value is updated, the code in computeForm uses the value in Payment to update Percent, and only then the value of Percent (just updated) is used to set Payment. As a result, whatever is in Payment will always win.
A couple of options to get it working the way you want it to:
You could pass a variable in the "onKeyUp" events of Payment and Percent that tells ComputeForm which to use to update the other, using an if(which === "pmt") { [code_to_update_payment] } else { [code_to_update_pct] } type construct.
You could break out the update code into two separate functions, function updatePmt() { } function updatePct() { } and then call each from the respective "onKeyUp" method in the HTML.
Either should work equally well to solve the behavior you are experiencing.
I have a problem. I'm trying to do a show/hide on the "activationframe" and "equipmentframe" divs based on a radio button selection. I had it working fine but then the client decided to add styled radio buttons to the equation. That has broken my show/hide toggle. How do I incorporate that into the styled radio button JS?
Here is the styled radio buttons script:
var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";
document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');
var Custom = {
init: function() {
var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
for(a = 0; a < inputs.length; a++) {
if((inputs[a].type == "radio") && inputs[a].className == "styled") {
span[a] = document.createElement("span");
span[a].className = inputs[a].type;
if(inputs[a].checked == true) {
position = "0 -" + (radioHeight*2) + "px";
span[a].style.backgroundPosition = position;
}
inputs[a].parentNode.insertBefore(span[a], inputs[a]);
inputs[a].onchange = Custom.clear;
if(!inputs[a].getAttribute("disabled")) {
span[a].onmousedown = Custom.pushed;
span[a].onmouseup = Custom.check;
} else {
span[a].className = span[a].className += " disabled";
}
}
}
inputs = document.getElementsByTagName("select");
for(a = 0; a < inputs.length; a++) {
if(inputs[a].className == "styled") {
option = inputs[a].getElementsByTagName("option");
active = option[0].childNodes[0].nodeValue;
textnode = document.createTextNode(active);
for(b = 0; b < option.length; b++) {
if(option[b].selected == true) {
textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
}
}
span[a] = document.createElement("span");
span[a].className = "select";
span[a].id = "select" + inputs[a].name;
span[a].appendChild(textnode);
inputs[a].parentNode.insertBefore(span[a], inputs[a]);
if(!inputs[a].getAttribute("disabled")) {
inputs[a].onchange = Custom.choose;
} else {
inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
}
}
}
document.onmouseup = Custom.clear;
},
pushed: function() {
element = this.nextSibling;
if(element.checked == true && element.type == "radio") {
this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
} else {
this.style.backgroundPosition = "0 -" + radioHeight + "px";
}
},
check: function() {
element = this.nextSibling;
this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
group = this.nextSibling.name;
inputs = document.getElementsByTagName("input");
for(a = 0; a < inputs.length; a++) {
if(inputs[a].name == group && inputs[a] != this.nextSibling) {
inputs[a].previousSibling.style.backgroundPosition = "0 0";
}
element.checked = true;
}
},
clear: function() {
inputs = document.getElementsByTagName("input");
for(var b = 0; b < inputs.length; b++) {
if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
inputs[b].previousSibling.style.backgroundPosition = "0 0";
}
}
},
choose: function() {
option = this.getElementsByTagName("option");
for(d = 0; d < option.length; d++) {
if(option[d].selected == true) {
document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
}
}
}
}
window.onload = Custom.init;
Here is my old script that does the show/hide:
function showhideInstall(installtype) {
if (installtype == "equipmentswap") {
document.getElementById("activationframe").style.display = 'none';
document.getElementById("equipmentframe").style.display = 'block';
} else {
document.getElementById("activationframe").style.display = 'block';
document.getElementById("equipmentframe").style.display = 'none';
}
}
And finally, my HTML:
<div id="activationtoggle">
<form class="radiobuttons">
<input type="radio" name="installtype" value="activation" class="styled" onclick="showhideInstall(this.value);" checked> New Activation
<input type="radio" name="installtype" value="equipmentswap" class="styled" onclick="showhideInstall(this.value);" > Equipment Swap
</form>
</div>
<div id="activationframe">
<div id="activationchecklist">
code here
</div>
<div id="equipmentframe">
<div id="equipmentswap">
<h2>Equipment Swap</h2>
more code here
</div>
Any help would be GREATLY appreciated. I'm middling at JS (at best) and this has proven to be a giant time sink.
Had a friend help me resolve the problem, thanks for the help, everyone.
Here is the JS he supplied me with:
function showhideInstall(installtype) {
if (installtype == "equipmentswap") {
document.getElementById("activationframe").style.display = 'none';
document.getElementById("equipmentframe").style.display = 'block';
} else {
document.getElementById("activationframe").style.display = 'block';
document.getElementById("equipmentframe").style.display = 'none';
}
}
function newactivation( indexNum ) {
var inputs = document.getElementsByTagName("label");
for(a = 0; a < inputs.length; a++) {
if( inputs[a].id == "activation" + indexNum ){
inputs[a].style.color = "#b5b5b5";
}
}
var activechecked = 0;
for (var i = 1; i<= 7; i++) {
if(document.getElementById("activationcheck" + i).checked == true){
activechecked ++;
}else if(document.getElementById("activationnocheck" + i).checked == true){
activechecked ++;
}
}
if (activechecked <= 6) {document.getElementById("next").disabled= true;}
if (activechecked == 7) {document.getElementById("next").disabled= false; document.getElementById("next").style.cursor= "pointer"; }
}
function equipmentswap( indexNum ) {
var inputs = document.getElementsByTagName("label");
for(a = 0; a < inputs.length; a++) {
if( inputs[a].id == "equip" + indexNum ){
inputs[a].style.color = "#b5b5b5";
a=inputs.length + 1;
}
}
var activechecked = 0;
for (var i = 1; i<= 7; i++) {
if(document.getElementById("swapcheck" + i).checked == true){
activechecked ++;
}else if(document.getElementById("swapnocheck" + i).checked == true){
activechecked ++;
}
}
if (activechecked <= 6) {document.getElementById("equipnext").disabled= true;}
if (activechecked == 7) {document.getElementById("equipnext").disabled= false; document.getElementById("next").style.cursor= "pointer"; }
}
I have a HTML page with three sets of images on. I want each image from each set to stay visible for 5 seconds, then fade out together and, when all three are invisible, fade back in together. Then the process begins again. I am trying to do this without using JQuery.
I wrote a JavaScript to do this, and it works, but after a while strange things happen. Images stop fading out, in, or do so too soon.
Here is the relevant HTML:
<body onload="HideAll(fade1Image2, fade1Image3, fade1Image4, fade2Image2,
fade2Image3, fade2Image4, fade3Image2, fade3Image3, fade3Image4);
SetVariables(4,4,4);">
<div id="fade1Image1" style="position:absolute;top:0px;left:312px;">
<img src="Images/Home/Power_Station/PowerStation1.jpg" alt="Power Station 1" />
</div>
<div id="fade1Image2" style="position:absolute;top:0px;left:312px;">
<img src="Images/Home/Power_Station/PowerStation2.jpg" alt="Power Station 2" />
</div>
<div id="fade1Image3" style="position:absolute;top:0px;left:312px;">
<img src="Images/Home/Power_Station/FenceLine1.jpg" alt="Fence Line 1" />
</div>
<div id="fade1Image4" style="position:absolute;top:0px;left:312px;">
<img src="Images/Home/Power_Station/FenceLine2.jpg" alt="Fence Line 2" />
</div>
<div id="fade2Image1" style="position:absolute;top:208px;left:0px;">
<img src="Images/Home/LNG_Terminal_Set/LNGTerminal1.jpg" alt="LNG Terminal 1" />
</div>
<div id="fade2Image2" style="position:absolute;top:208px;left:0px;">
<img src="Images/Home/LNG_Terminal_Set/LNGTerminal2.jpg" alt="LNG Terminal 2" />
</div>
<div id="fade2Image3" style="position:absolute;top:208px;left:0px;">
<img src="Images/Home/LNG_Terminal_Set/LNGTerminal3.jpg" alt="LNG Terminal 3" />
</div>
<div id="fade2Image4" style="position:absolute;top:208px;left:0px;">
<img src="Images/Home/LNG_Terminal_Set/LNGTerminal4.jpg" alt="LNG Terminal 4" />
</div>
<div id="fade3Image1" style="position:absolute;top:416px;left:312px;">
<img src="Images/Home/Airports/AirPort1.jpg" alt="Air Port 1" />
</div>
<div id="fade3Image2" style="position:absolute;top:416px;left:312px;">
<img src="Images/Home/Airports/AirPort2.jpg" alt="Air Port 2" />
</div>
<div id="fade3Image3" style="position:absolute;top:416px;left:312px;">
<img src="Images/Home/Airports/T1_Tracker.jpg" alt="TI Tracker 1" />
</div>
<div id="fade3Image4" style="position:absolute;top:416px;left:312px;">
<img src="Images/Home/Airports/Targets_Tracked_no_alarm.jpg" alt="TI Tracker 2" />
</div>
And Here is the JavaScript:
var TimeToFade = 1000.0;
var maxCount;
var count;
function SetVariables()
{
maxCount = new Array(arguments.length);
count = arguments.length + 1;
for (var x = 0; x < arguments.length; x++)
{
maxCount[x] = arguments[x];
}
}
function fade(counter)
{
var eid, countx;
for (var x = 1; x < count; x++)
{
countx = counter % maxCount[x-1];
if (countx == 0)
countx = maxCount[x-1];
eid = "fade" + x + "Image" + countx;
var element = document.getElementById(eid);
if(element == null)
return;
if(element.FadeState == null)
{
if(element.style.opacity == null
|| element.style.opacity == ''
|| element.style.opacity == '1')
{
element.FadeState = 2;
}
else
{
element.FadeState = -2;
}
}
if(element.FadeState == 1 || element.FadeState == -1)
{
element.FadeState = element.FadeState == 1 ? -1 : 1;
element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
}
else
{
element.FadeState = element.FadeState == 2 ? -1 : 1;
element.FadeTimeLeft = TimeToFade;
if (x == 3)
setTimeout("animateFade(" + new Date().getTime() + ",'" + counter + "')", 33);
}
}
}
function animateFade(lastTick, counter)
{
var eid, countx;
for (var x = 1; x < count; x++)
{
countx = counter % maxCount[x-1];
if (countx == 0)
countx = maxCount[x-1];
eid = "fade" + x + "Image" + countx;
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var element = document.getElementById(eid);
if(element.FadeTimeLeft <= elapsedTicks)
{
element.style.opacity = element.FadeState == 1 ? '1' : '0';
element.style.filter = 'alpha(opacity = '
+ (element.FadeState == 1 ? '100' : '0') + ')';
element.FadeState = element.FadeState == 1 ? 2 : -2;
if (element.FadeState == 2 && x == count-1)
{
setTimeout(function(){fade(counter)}, 5000);
hidetext(TextBlock1, TextBlock2, Text2Block1, Text2Block2, Text3Block1, Text3Block2);
}
else if (x == count-1)
{
counter++;
fade(counter);
}
if (x == count-1)
return;
}
else if (element.FadeTimeLeft > elapsedTicks)
{
element.FadeTimeLeft -= elapsedTicks;
var newOpVal = element.FadeTimeLeft/TimeToFade;
if(element.FadeState == 1)
newOpVal = 1 - newOpVal;
element.style.opacity = newOpVal;
element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
}
}
setTimeout("animateFade(" + curTick + ",'" + counter + "')", 33);
}
function HideAll()
{
for (var i = 0; i < arguments.length; i++)
{
arguments[i].style.opacity = 0;
arguments[i].style.filter = 'alpha(opacity = 0)';
arguments[i].FadeState = -2;
}
setTimeout(function(){fade(1)}, 5000);
}
I can't see what I have done to produce this error; any help would be greatly appreciated.
To see the code in action, click here.
This doesn't really answer the question, but I rewrote the javascript from scratch and it seems to work. So, for completeness, here it is:
var Count = new Array(1, 1, 1);
var MaxCount = new Array(8, 6, 5);
var FadeState = "out";
var FadeTime = new Array(100, 100, 100);
function Fade()
{
for (var x = 0; x < 3; x++)
{
var id = "fade" + (x+1) + "Image" + Count[x];
var element = document.getElementById(id)
if (FadeState == "out")
{
if (FadeTime[x] > 0)
{
FadeTime[x]-= 5;
element.style.filter = 'alpha(opacity = ' + FadeTime[x] + ')';
element.style.opacity = FadeTime[x]/100;
}
else
{
Count[x]++;
if (Count[x] > MaxCount[x])
Count[x] = 1;
if (x == 2)
FadeState = "back";
}
}
else
{
if (FadeTime[x] < 100)
{
FadeTime[x]+= 5;
element.style.filter = 'alpha(opacity = ' + FadeTime[x] + ')';
element.style.opacity = FadeTime[x]/100;
}
else
{
if (x == 2)
FadeState = "pause";
}
}
}
switch (FadeState)
{
case "back":
FadeState = "in";
Fade();
break;
case "pause":
FadeState = "out";
setTimeout(function(){Fade()}, 5000);
break;
default:
setTimeout(function(){Fade()}, 20);
}
}
function HideAll()
{
for (var i = 0; i < arguments.length; i++)
{
var element = document.getElementById(arguments[i]);
element.style.opacity = 0;
element.style.filter = 'alpha(opacity = 0)';
}
setTimeout(function(){Fade()}, 5000);
}
You need to put quotes around the ids, when you call the HideAll method
HideAll('fade1Image2', 'fade1Image3', 'fade1Image4', 'fade2Image2',
'fade2Image3', 'fade2Image4', 'fade3Image2', 'fade3Image3', 'fade3Image4')
And you need to actually find the elements before setting their styles..
function HideAll()
{
for (var i = 0; i < arguments.length; i++)
{
var element = document.getElementById( arguments[i] );
element.style.opacity = 0;
element.style.filter = 'alpha(opacity = 0)';
element.FadeState = -2;
}
setTimeout(function(){fade(1)}, 5000);
}