Javascript: Global Variables Aren't Defined In Other Functions - javascript

I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].

try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!

You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.

My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.

Related

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

Snake in JavaScript: I can't get my snakes tail longer

I made a snake game that works almost completely. I have one snake head, and an array which contains the head and all of the tails. When the snake eats a food, the food moves location, but my tail isn't getting bigger when I eat the food. I don't have an IMMENSE understanding of arrays, perhaps I'm doing it wrong?
Here is the code:
setSize(400, 400);
var background = new Rectangle(getWidth(), getHeight());
background.setPosition(0, 0);
background.setColor(Color.black);
add(background);
// ------------------------------------------------
var gameTime = 0;
var snakeX = (Randomizer.nextInt(0, 19)) * 20;
var snakeY = (Randomizer.nextInt(0, 19)) * 20;
var foodX;
var foodY;
var snakeFood = new Rectangle(20, 20);
snakeFood.setColor(Color.red);
var food_eaten = 0;
var snakeSpeed = 20;
var keyLeft = false;
var keyRight = false;
var keyUp = false;
var keyDown = false;
var snake_size = 10;
var snakeHead = new Rectangle(20, 20);
snakeHead.setColor(Color.green);
var snakes = [snakeHead];
// ------------------------------------------------
function start(){
setup();
keyDownMethod(checkKey);
setTimer(counter, 250);
}
function counter(){
gameTime += 0.25;
updateSnake();
}
function setup(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
snakeHead.setPosition(snakeX, snakeY);
add(snakeHead);
snakeFood.setPosition(foodX, foodY);
add(snakeFood);
}
function checkKey(e){
if(e.keyCode == Keyboard.LEFT){
keyRight = false;
keyUp = false;
keyDown = false;
keyLeft = true;
}else if(e.keyCode == Keyboard.RIGHT){
keyLeft = false;
keyUp = false;
keyDown = false;
keyRight = true;
}else if(e.keyCode == Keyboard.UP){
keyRight = false;
keyLeft = false;
keyDown = false;
keyUp = true;
}else if(e.keyCode == Keyboard.DOWN){
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = true;
}
}
function updateSnake(){
if(foodX == snakeX && foodY == snakeY){
eat();
}
var dirX = 0;
var dirY = 0;
if(keyLeft == true){
dirX = -(snakeSpeed);
dirY = 0;
}else if(keyRight == true){
dirX = snakeSpeed;
dirY = 0;
}else if(keyUp == true){
dirY = -(snakeSpeed);
dirX = 0;
}else if(keyDown == true){
dirY = snakeSpeed;
dirX = 0;
}
// moving the snake head
snakeHead.setPosition(snakeX + dirX, snakeY + dirY);
snakeX += dirX;
snakeY += dirY;
// moving the snake body
if(snakes.length > 1){
for(var i = 0; i < snakes.length; i++){
var curr_body = snakes[i];
curr_body.setPosition(snakeX + dirX, snakeY + dirY);
}
}
}
function eat(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
var tail = new Snake(snakeX, snakeY);
snakeFood.setPosition(foodX, foodY);
}
function Snake(x, y){
var snakeBody = new Rectangle(20, 20);
if(keyLeft == true){
snakeBody.setPosition(x + snake_size, y);
}if(keyRight == true){
snakeBody.setPosition(x - snake_size, y);
}if(keyUp == true){
snakeBody.setPosition(x, y + snake_size);
}if(keyDown == true){
snakeBody.setPosition(x, y - snake_size);
}
snakeBody.setColor(Color.green);
snakes.push(snakeBody);
add(snakeBody);
}
In your eat() function, you assign a new Snake object to a var tail, but then do nothing with it. I think you need to add it to your snakes array (which I assume represents the entire snake?)

how to programming the code in Xcalc.js

function Operator(input) {
this.operator = input;
if (!input) {
console.log("Operator has no input.");
}
this.solve = function(segment1, segment2, x) {
var v1 = segment1.coefficient;
if (segment1.type=="variable") {
v1 = x;
}
var v2 = segment2.coefficient;
if (segment2.type=="variable") {
v2 = x;
}
if (this.operator=="+") {
return new Segment(v1 + v2);
} else if (this.operator=="-") {
return new Segment(v1 - v2);
} else if (this.operator=="*") {
return new Segment(v1 * v2);
} else if (this.operator=="/") {
return new Segment(v1 / v2);
} else if (this.operator=="^") {
return new Segment(Math.pow(v1, v2));
}
};
}//Class for special functions
function MathFunction(input) {
this.f=input;
if (!input) {
console.log("Math function has no input.");
}
this.solve = function(segment) {
var v = segment.coefficient;
if (this.f=="sin") {
return new Segment(Math.sin(v));
} else if (this.f=="cos") {
return new Segment(Math.cos(v));
} else if (this.f=="tan") {
return new Segment(Math.tan(v));
} else if (this.f=="asin") {
return new Segment(Math.asin(v));
} else if (this.f=="acos") {
return new Segment(Math.acos(v));
} else if (this.f=="atan") {
return new Segment(Math.atan(v));
} else if (this.f=="abs") {
return new Segment(Math.abs(v));
}
};
}
//Class for a segment of math (a container)
function Segment(input) {
this.sections = [];
this.type="section";
this.operator=0;
this.coefficient=0;
this.mathFunction=0;
this.variable="";
var removeBrackets = function(value) {
if (!value) return "";
//While there are brackets around the string
while (value.substr(0, 1)=="(" && value.substr(value.length-1, 1)==")") { var openBrackets=1;
//See if the end bracket closes the opening bracket or not
for (var i=1; i<value.length&&openBrackets>0; i++) {
if (value.substr(i, 1)=="(") openBrackets++;
if (value.substr(i, 1)==")") openBrackets--;
}
i-=1;
//If it corresponds to different brackets, do nothing
if (openBrackets!==0 || i!=value.length-1) {
break
pue.substr(i, 1)=="(") {
openBrackets++;
} else if (value.substr(i, 1)==")") {
openBrackets--;
}
if (i==index) {
//If no brackets are open (and if the operator is actually - and not just a minus sign), break the loop.
var r=0;
if (trig=="sin") {
r=/(a)?sin/g;
} else if (trig=="cos") {
r=/(a)?cos/g;
} else if (trig=="tan") {
r=/(a)?tan/g;
} else {
return -1;
}
for (matches=r.exec(value); matches; matches=r.exec(value)) if (RegExp.$1 != "a") index=matches.index;
var inBrackets=true;
while (inBrackets && index!=-1) {
var openBrackets=0;
//Find how many brackets are opened or closed at a given point in the string
for (var i=0; i<value.length; i++) {
if (value.substr(i, 1)=="(") {
openBrackets++;
} else if (value.substr(i, 1)==")") {
openBrackets--;
}
if (i==index) {
//If no brackets are open (and if the operator is actually - and not just a minus sign), break the loop.
if (openBrackets===0) {
inBrackets=false;
break;
}
}
str+="<div class='answer'>= " + this.solve().coefficient + "</div>";
str+="</div>";
return str;
};
//constructor
if (input!==undefined) {
if (typeof(input)=="string") {
//Remove excess whitespace
input = input.replace(/\s/g, "");
//get rid of unnecessary brackets surrounding the section
input = removeBrackets(input);
//Find the last instance of each operator in the string
var addition = findLast("+", input);
var subtraction = findLast("-", input);
var division = findLast("/", input);
var exponent = findLast("^", input); //Find the first exponent, since those work in reverse
var bracket1 = findLast("(", input);
var sin = findLastTrig("sin", input);
var cos = findLastTrig("cos", input);
var tan = findLastTrig("tan", input);
var asin = findLast("asin", input);
var acos = findLast("acos", input);
var atan = findLast("atan", input);
var abs = findLast("abs", input);
var multiplication = findLast("*", input);
var multiplication2 = findMultiplicationBrackets(input); //Find brackets that are the same as multiplication
var functionMultiplication = -1;
if (sin>multiplication) functionMultiplication=sin;
if (cos>multiplication) functionMultiplication=cos;
if (tan>multiplication) functionMultiplication=tan;
if (asin>multiplication) functionMultiplication=asin;
if (acos>multiplication) functionMultiplication=acos;
if (atan>multiplication) functionMultiplication=atan;
if (abs>multiplication) functionMultiplication=abs;
//Push back each half of the equation into a section, in reverse order of operations
if (addition != -1 && (subtraction == -1 || addition>subtraction)) {
this.sections.push(new Segment(input.substring(0, addition)));
this.sections.push(new Segment(input.substring(addition+1)));
this.operator = new Operator("+");
} else if (subtraction != -1) {
if (subtraction>0) {
this.sections.push(new Segment(input.substring(0, subtraction)));
} else {
this.sections.push(new Segment(0));
}
this.sections.push(new Segment(input.substring(subtraction+1)));
this.operator = new Operator("-");
} else if (functionMultiplication >0 && functionMultiplication > multiplication && functionMultiplication > division) {
this.sections.push(new Segment(input.substring(0, functionMultiplication)));
this.sections.push(new Segment(input.substring(functionMultiplication)));
this.operator = new Operator("*");
} else if (multiplication2 != -1 && (division == -1 || multiplication>division) && (multiplication == -1 || multiplication2>multiplication)) {
this.sections.push(new Segment(input.substring(0, multiplication2)));
this.sections.push(new Segment(input.substring(multiplication2)));
this.operator = new Operator("*");
} else if (multiplication != -1 && (division == -1 || multiplication>division)) {
this.sections.push(new Segment(input.substring(0, multiplication)));
this.sections.push(new Segment(input.substring(multiplication+1)));
this.operator = new Operator("*");
} else if (division != -1) {
this.sections.push(new Segment(input.substring(0, division)));
this.sections.push(new Segment(input.substring(division+1)));
this.operator = new Operator("/");
} else if (exponent != -1) {
this.sections.push(new Segment(input.substring(0, exponent)));
this.sections.push(new Segment(input.substring(exponent+1)));
this.operator = new Operator("^");
} else if (sin != -1 && (cos == -1 || sin>cos) && (tan == -1 || sin>tan) && (asin == -1 || sin>asin) && (acos == -1 || sin>acos) && (atan == -1 || sin>atan) && (abs == -1 || sin>abs)) {
this.sections.push(new Segment(input.substring(sin+3)));
this.mathFunction = new MathFunction("sin");
this.type = "function";
} else if (cos != -1 && (tan == -1 || cos>tan) && (asin == -1 || cos>asin) && (acos == -1 || cos>acos) && (atan == -1 || cos>atan) && (abs == -1 || cos>abs)) {
this.sections.push(new Segment(input.substring(cos+3)));
this.mathFunction = new MathFunction("cos");
this.type = "function";
} else if (tan != -1 && (asin == -1 || tan>asin) && (acos == -1 || tan>acos) && (atan == -1 || tan>atan) && (abs == -1 || tan>abs)) {
this.sections.push(new Segment(input.substring(tan+3)));
this.mathFunction = new MathFunction("tan");
this.type = "function";
} else if (asin != -1 && (acos == -1 || asin>acos) && (atan == -1 || asin>atan) && (abs == -1 || asin>abs)) {
this.sections.push(new Segment(input.substring(asin+4)));
this.mathFunction = new MathFunction("asin");
this.type = "function";
} else if (acos != -1 && (atan == -1 || acos>atan) && (abs == -1 || acos>abs)) {
this.sections.push(new Segment(input.substring(acos+4)));
this.mathFunction = new MathFunction("acos");
this.type = "function";
} else if (atan != -1 && (abs == -1 || atan>abs)) {
this.sections.push(new Segment(input.substring(atan+4)));
this.mathFunction = new MathFunction("atan");
this.type = "function";
} else if (abs != -1) {
this.sections.push(new Segment(input.substring(abs+3)));
this.mathFunction = new MathFunction("abs");
this.type = "function";
} else if (bracket1 != -1) {
var openBrackets=1;
for (var i=bracket1+1; i<input.length&&openBrackets>0; i++) {
if (input.substr(i, 1)=="(") openBrackets++;
if (input.substr(i, 1)==")") openBrackets--;
}
if (openBrackets===0) {
var bracket2=i-1;
if (bracket1>0) this.sections.push(new Segment(input.substring(0, bracket1)));
if (bracket2-bracket1!=1) this.sections.push(new Segment(input.substring(bracket1+1, bracket2)));
if (bracket2!=input.length-1) this.sections.push(new Segment(input.substring(bracket2+1)));
this.operator = new Operator("*");
} else {
console.log("Brackets nesting error: " + input);
}
//If there are no operators, just push the input itself
} else {
var xLocation=input.toLowerCase().indexOf("x");
if (xLocation!=-1) {
if (xLocation>0) {
this.sections.push(new Segment(input.substring(0, xLocation)));
this.sections.push(new Segment("x"));
this.operator=new Operator("*");
} else {
this.variable="x";
this.type="variable";
}
} else {
this.coefficient = parseFloat(input);
this.type = "value";
}
}
} else if (typeof(input)=="number") {
this.coefficient = input;
this.type = "value";
}
} else {
console.log("Segment has no input.");
}
}
//One point on a graph
function Point(x, y) {
this.x = x || 0;
this.y = y || 0;
}
//MathFunction to create graphs
function Graph(value, width, height, rangeX, rangeY) {
var autoRange=false;
//Default params
if (rangeX===undefined) {
rangeX=10;
}
if (rangeY===undefined) {
autoRange = true;
}
//Properties
this.expression = new Segment(value);
this.points = [];
this.canvas = document.createElement("canvas");
this.canvas.width=width || 400;
this.canvas.height=height || 400;
this.min=undefined;
this.max=undefined;
this.x1 = 0-Math.abs(rangeX);
this.x2 = 0+Math.abs(rangeX);
this.y1 = 0-Math.abs(rangeY);
this.y2 = 0+Math.abs(rangeY);
var startMouse = new Point(0, 0);
var mousePos = new Point(0, 0);
var timer=0;
var stage=0;
var img=0;
var magnitudeX = 0;
var magnitudeY = 0;
//Gets minimum y value in the set of points
this.getMin = function() {
if (this.min===undefined) {
if (this.points.length>0) {
var min = this.points[0].y;
for (var i=1; i<this.points.length; i++) {
if (this.points[i].y<min) min = this.points[i].y;
}
this.min=min;
return min;
} else {
return 0;
}
} else {
return this.min;
}
};
//Gets maximum y value in the set of points
this.getMax = function() {
if (this.max===undefined) {
if (this.points.length>0) {
var max = this.points[0].y;
for (var i=1; i<this.points.length; i++) {
if (this.points[i].y>max) max = this.points[i].y;
}
this.max=max;
return max;
} else {
return 0;
}
} else {
return this.max;
}
};
//Updates the points and graph
this.update = function() {
var accuracy = (this.x2-this.x1)/this.canvas.width;
this.points = [];
for (var i=this.x1; i<=this.x2; i+=accuracy) {
this.points.push(new Point(i, this.expression.result(i)));
}
if (autoRange) {
if (this.getMax()-this.getMin()>100000) {
this.y1=-100;
this.y2=100;
} else {
this.y1=this.getMin()-5;
this.y2=this.getMax()+5;
}
autoRange = false;
}
magnitudeX = Math.ceil(Math.log(this.x2-this.x1));
magnitudeY = Math.ceil(Math.log(this.y2-this.y1));
this.redraw();
};
var drawAxes = function(_x1, _x2, _y1, _y2, redraw) {
stage.strokeStyle="#bdc3c7";
stage.fillStyle="#bdc3c7";
var limit=0;
var i=0;
//Draw the y axis if it is in the view
if (0>=_x1-30 && 0<=_x2+30) {
stage.lineWidth=2;
stage.beginPath();
stage.moveTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width, 0);
stage.lineTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width, this.canvas.height);
stage.closePath();
stage.stroke();
stage.textAlign = "right";
stage.textBaseline="middle";
stage.lineWidth=1;
limit = (Math.abs(_y2)>Math.abs(_y1))?Math.abs(_y2):Math.abs(_y1);
for (i=0; i<=limit; i+=Math.pow(10, Math.floor(Math.log(_y2-_y1) / Math.LN10))/4) {
if (i===0) continue;
if (i<=_y2+50) {
if (redraw || (i>=this.y2-50)) {
stage.beginPath();
stage.moveTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-5, this.canvas.height-((i-_y1)/(_y2-_y1))*this.canvas.height);
stage.lineTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width+5, this.canvas.height-((i-_y1)/(_y2-_y1))*this.canvas.height);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(i*100)/100), this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-8, this.canvas.height-((i-_y1)/(_y2-_y1))*this.canvas.height);
}
}
if (i>=_y1-50) {
if (redraw || (-i<=this.y1+50)) {
stage.beginPath();
stage.moveTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-5, this.canvas.height-((-i-_y1)/(_y2-_y1))*this.canvas.height);
stage.lineTo(this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width+5, this.canvas.height-((-i-_y1)/(_y2-_y1))*this.canvas.height);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(-i*100)/100), this.canvas.width/2-(((_x2+_x1)/2)/(_x2-_x1))*this.canvas.width-8, this.canvas.height-((-i-_y1)/(_y2-_y1))*this.canvas.height);
}
}
}
}
//Draw the x axis if it is in the view
if (0>=_y1-50 && 0<=_y2+50) {
stage.lineWidth=2;
stage.beginPath();
stage.moveTo(0, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height);
stage.lineTo(this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height);
stage.closePath();
stage.stroke();
stage.textAlign = "center";
stage.textBaseline="top";
stage.lineWidth=1;
limit = (Math.abs(_x2)>Math.abs(_x1))?Math.abs(_x2):Math.abs(_x1);
for (i=0; i<=limit; i+=Math.pow(10, Math.floor(Math.log(_x2-_x1) / Math.LN10))/4) {
if (i===0) continue;
if (i<=_x2+50) {
if (redraw || (i>=this.x2-50)) {
stage.beginPath();
stage.moveTo(((i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height-5);
stage.lineTo(((i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+5);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(i*100)/100), ((i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+8);
}
}
if (i>=_x1-50) {
if (redraw || (-i<=this.x1+50)) {
stage.beginPath();
stage.moveTo(((-i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height-5);
stage.lineTo(((-i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+5);
stage.closePath();
stage.stroke();
stage.fillText(""+(Math.round(-i*100)/100), ((-i-_x1)/(_x2-_x1))*this.canvas.width, this.canvas.height/2+(((_y2+_y1)/2)/(_y2-_y1))*this.canvas.height+8);
}
}
}
}
}.bind(this);
//Updates the canvas
this.redraw = function() {
if (this.points.length>1) {
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
stage.lineCap="round";
var offsetY = -this.y1;
drawAxes(this.x1, this.x2, this.y1, this.y2, true);
//Draw all the points
stage.strokeStyle="#2980b9";
stage.lineWidth=1;
stage.beginPath();
stage.moveTo(0, this.canvas.height-((this.points[0].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
for (var i=1; i<this.points.length; i++) {
if (Math.abs((this.canvas.height-((this.points[i].y+offsetY)/(this.y2-this.y1))*this.canvas.height)-(this.canvas.height-((this.points[i-1].y+offsetY)/(this.y2-this.y1))*this.canvas.height))<=this.canvas.height) {
stage.lineTo((i/this.points.length)*this.canvas.width, this.canvas.height-((this.points[i].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
}
stage.moveTo((i/this.points.length)*this.canvas.width, this.canvas.height-((this.points[i].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
}
stage.closePath();
stage.stroke();
img = stage.getImageData(0, 0, this.canvas.width, this.canvas.height);
} else {
console.log("Not enough points to graph.");
}
};
this.setRange = function(_x1, _x2, _y1, _y2) {
this.x1=_x1;
this.x2=_x2;
this.y1=_y1;
this.y2=_y2;
this.update();
};
var getMousePos = function(evt) {
var rect = this.canvas.getBoundingClientRect();
var root = document.documentElement;
// return relative mouse position
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return new Point(mouseX, mouseY);
}.bind(this);
var startDrag = function(event) {
document.addEventListener("mousemove", dragMouse, false);
document.addEventListener("mouseup", endDrag, false);
this.canvas.removeEventListener("mouseover", startMouseOver, false);
this.canvas.removeEventListener("mousemove", moveMouse, false);
startMouse = getMousePos(event);
}.bind(this);
var redrawLine = function() {
var offsetX = ((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var offsetY = ((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
this.setRange(this.x1-offsetX, this.x2-offsetX, this.y1+offsetY, this.y2+offsetY);
startMouse = mousePos;
}.bind(this);
var dragMouse = function(event) {
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
mousePos = getMousePos(event);
var newx1 = this.x1-((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var newx2 = this.x2-((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var newy1 = this.y1+((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
var newy2 = this.y2+((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
if (Math.abs(newx1-this.x1)>this.canvas.width/2 || Math.abs(newy1-this.y1)>this.canvas.height/2) {
redrawLine();
} else {
drawAxes(newx1, newx2, newy1, newy2, false);
stage.putImageData(img, mousePos.x-startMouse.x, mousePos.y-startMouse.y);
}
}.bind(this);
var endDrag = function(event) {
document.removeEventListener("mousemove", dragMouse, false);
document.removeEventListener("mouseup", endDrag, false);
this.canvas.addEventListener("mouseover", startMouseOver, false);
this.canvas.addEventListener("mousemove", moveMouse, false);
mousePos = getMousePos(event);
var offsetX = ((mousePos.x-startMouse.x)/this.canvas.width)*(this.x2-this.x1);
var offsetY = ((mousePos.y-startMouse.y)/this.canvas.height)*(this.y2-this.y1);
this.setRange(this.x1-offsetX, this.x2-offsetX, this.y1+offsetY, this.y2+offsetY);
}.bind(this);
var startMouseOver = function(event) {
this.canvas.addEventListener("mousemove", moveMouse, false);
this.canvas.addEventListener("mouseout", endMouseOver, false);
}.bind(this);
var moveMouse = function(event) {
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
stage.putImageData(img, 0, 0);
mousePos = getMousePos(event);
var offsetY = -this.y1;
//Draw the coordinate
stage.fillStyle="#2980b9";
stage.beginPath();
stage.arc(mousePos.x, this.canvas.height-((this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y+offsetY)/(this.y2-this.y1))*this.canvas.height, 4, 0, 2*Math.PI);
stage.closePath();
stage.fill();
stage.fillStyle="#000";
stage.strokeStyle="#FFF";
stage.lineWidth=4;
stage.textBaseline="alphabetic";
var txt="(" + (Math.round(this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].x*100)/100).toFixed(2) + ", " + (Math.round(this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y*100)/100).toFixed(2) + ")";
if (mousePos.x<stage.measureText(txt).width/2+2) {
stage.textAlign = "left";
} else if (mousePos.x>this.canvas.width-stage.measureText(txt).width/2-2) {
stage.textAlign = "right";
} else {
stage.textAlign = "center";
}
stage.strokeText(txt, mousePos.x, -10+this.canvas.height-((this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
stage.fillText(txt, mousePos.x, -10+this.canvas.height-((this.points[Math.round(mousePos.x/this.canvas.width*this.points.length)].y+offsetY)/(this.y2-this.y1))*this.canvas.height);
}.bind(this);
var endMouseOver = function(event) {
this.canvas.removeEventListener("mousemove", moveMouse, false);
this.canvas.removeEventListener("mouseout", endMouseOver, false);
stage.clearRect(0, 0, this.canvas.width, this.canvas.height);
stage.putImageData(img, 0, 0);
}.bind(this);
//Returns the canvas element
this.getCanvas = function() {
return this.canvas;
};
//If canvas drawing is supported
if (this.canvas.getContext) {
//Get the canvas context to draw onto
stage = this.canvas.getContext("2d");
stage.font = "12px sans-serif";
this.canvas.style.backgroundColor="#FFF";
//Make points
this.update();
this.canvas.addEventListener("mousedown", startDrag, false);
this.canvas.addEventListener("mouseover", startMouseOver, false);
} else {
console.log("Canvas not supported in this browser.");
this.canvas = document.createElement("div");
this.canvas.innerHTML="Canvas is not supported in this browser.";
}
}
ntById("wrapper").className="";
var timer = setTimeout(function() {
var graph = XCalc.graphExpression(input, 400, 400);
document.getElementById("result").innerHTML = "";
document.getElementById("result").appendChild(graph.getCanvas());
document.getElementById("wrapper").className="solved";
}, 800);
} else {
document.getElementById("result").innerHTML = "<div class='error'>Error: Improperly nested brackets. Remember to only use round brackets and close all opened brackets.</div>";
}
}
window.onload = function() {
document.getElementById("simplify").addEventListener("click", simplifyText);
simplifyText();
};
<html>
<head>
<script src="exmath.js"></script>
</head>
<body>
<div id="top"><h1>Maths equation plotter</h1>
f(x) = <input type="text" value="(x+4)^2*(x-6)+60sinx" id="input" /><input type="button" value="Graph" id="simplify" />
</div>
<div id="wrapper">
<div id="result"></div>
</div>
</body>
</html>
I have some code in XCalc.js i want to support particular equation in(algebra equation,quadratic,linear,nonlinear equation) in based on equation how to programming in XCalc.js and how to show the steps based on equation so please help me to improve my code.refer this link:https://github.com/davepagurek/XCalc

The color will not change on a div, generated by a script

var BGLinks = (function() {
var that = {};
// can be set like BGLinks.parameter
that.version = 'NIV';
that.clickTooltip = false;
that.apocrypha = false;
that.showTooltips = true;
that.host = 'www.biblegateway.com';
var showTimer = 0;
var hideTimer = 0;
var container;
var addedCSS = false;
var setupRun = false;
var delay = 1000;
var bgHost;
var toolsHost;
var cdHost;
var browser = navigator.appVersion;
var book_string = 'Genesis|Gen?|Gn|Exodus|Exod?|Ex|Leviticus|Le?v|Numbers|Nu?m|Nu|Deuteronomy|Deut?|Dt|Josh?ua|Josh?|Jsh|Judges|Ju?dg|Jg|Ru(?:th)?|Ru?t|(?:1|i|2|ii) ?Samuel|(?:1|i|2|ii) ?S(?:a|m)|(?:1|i|2|ii) ?Sam|(?:1|i|2|ii) ?Kin(?:gs?)?|(?:1|i|2|ii) ?Kgs|(?:1|i|2|ii) ?Chronicles|(?:1|i|2|ii) ?Chr(?:o?n)?|(?:1|i|2|ii) ?Cr|Ezra?|Nehemiah|Neh?|Esther|Esth?|Jo?b|Psalms?|Psa?|Proverbs|Pro?v?|Ecclesiastes|Ec(?:cl?)?|Song (?:O|o)f Solomon|Song (?:O|o)f Songs?|Son(?:gs?)?|SS|Isaiah?|Isa?|Jeremiah|Je?r|Lamentations|La(?:me?)?|Ezekiel|Eze?k?|Daniel|Da?n|Da|Hosea|Hos?|Hs|Jo(?:el?)?|Am(?:os?)?|Obadiah|Ob(?:ad?)?|Jon(?:ah?)?|Jnh|Mic(?:ah?)?|Mi|Nah?um|Nah?|Habakkuk|Hab|Zephaniah|Ze?ph?|Haggai|Hagg?|Hg|Zechariah|Ze?ch?|Malachi|Ma?l|Matthew|Matt?|Mt|Mark|Ma(?:r|k)|M(?:r|k)|Luke?|Lk|Lu?c|John|Jn|Ac(?:ts?)?|Romans|Ro?m|(?:1|i|2|ii) ?Corinthians|(?:1|i|2|ii) ?C(?:or?)?|Galatians|Gal?|Gl|Ephesians|Eph?|Philippians|Phil|Colossians|Co?l|(?:1|i|2|ii) ?Thessalonians|(?:1|i|2|ii) ?Th(?:e(?:ss?)?)?|(?:1|i|2|ii) ?Timothy|(?:1|i|2|ii) ?Tim|(?:1|i|2|ii) ?T(?:i|m)|Ti(?:tus)?|Ti?t|Philemon|Phl?m|Hebrews|Heb?|Jam(?:es)?|Jms|Jas|(?:1|i|2|ii) ?Peter|(?:1|i|2|ii) ?Pe?t?|(?:1|i|2|ii|3|iii) ?J(?:oh)?n?|Jude?|Revelations?|Rev|R(?:e|v)';
var apoc_books = '|Tobit?|To?b|Judi(?:th?)?|Jdt|(?:1|2) ?Mac(?:cabees)?|(?:1|2) ?Ma?|Wi(?:sdom)?|Wi?s|Sir(?:ach)?|Ba(?:ruc?h)?|Ba?r';
that.linkVerses = function() {
updateURLs();
insertBiblerefs(document.body);
if (that.showTooltips === true) {
addBiblerefListeners();
}
setup();
}
var updateURLs = function() {
bgHost = window.location.protocol + '//' + that.host;
toolsHost = bgHost + '/share/tooltips/data';
cdHost = bgHost + '/public/link-to-us/tooltips';
}
var insertBiblerefs = function(node) {
if (node.nodeType === 3) {
var new_nodes = searchNode(node,0);
return new_nodes;
}
else if (node.tagName != undefined && node.tagName.match(/^(?:a|h\d|img|pre|input|option)$/i)) {
return null;
}
else {
var children = node.childNodes;
var i = 0;
while(i<children.length) {
var new_nodes = insertBiblerefs(children[i]);
i += new_nodes +1;
}
}
return null;
}
var searchNode = function(node, inserted_nodes) {
var apoc_string = that.apocrypha === true ? apoc_books : '';
//finds book and chapter for each verse that been separated by &,and,etc...
var book_chap = '((?:('+book_string+apoc_string+')(?:\.)? ?)?(?:(\\d*):)?(\\d+(?:(?:ff|f|\\w)|(?:\\s?(?:-|–|—)\\s?\\d+)?)))([^a-z0-9]*)';
var regex_string = '(?:'+book_string+apoc_string+')(?:\.)? ?\\d+:\\d+(?:ff|f|\\w)?(?:\\s?(?:(?:(?:-|–|—)\\s?(?:(?:'+book_string+apoc_string+')(?:\.)?\\s)?)|(?:(?:,|;|&|&|and|cf\\.|cf)))\\s?(?:(?:(?:vv.|vs.|vss.|v.) ?)?\\d+\\w?)(?::\\d+\\w?)?)*';
var regex = new RegExp(regex_string,'i');
var verse_match = node.nodeValue.match(regex);
if (verse_match == null) {
return inserted_nodes;
} else {
var text = node.nodeValue;
var before_text = text.substr(0,text.indexOf(verse_match[0]));
var after_text = text.substr(text.indexOf(verse_match[0])+verse_match[0].length);
if (before_text.length > 0) {
var newTxtNode = document.createTextNode(before_text);
node.parentNode.insertBefore(newTxtNode, node);
inserted_nodes++;
}
var book_chap_regex = new RegExp(book_chap, 'gi');
var book;
var chapter;
var verse;
while (matched = book_chap_regex.exec(verse_match[0])) {
// break up what may be multiple references into links.
if (matched[2] != '' && matched[2] != null) {
book = matched[2];
}
if (matched[3] != '' && matched[3] != null) {
chapter = matched[3];
}
verse = matched[4];
var newLinkNode = document.createElement("a");
newLinkNode.className = 'bibleref';
newLinkNode.target = '_BLANK';
var passage = book+' '+chapter+':'+verse;
newLinkNode.href = bgHost+'/passage/?search='+passage+'&version='+that.version+'&src=tools';
newLinkNode.innerHTML = matched[1];
if (that.clickTooltip === true) {
newLinkNode.onclick=function() {return false};
}
node.parentNode.insertBefore(newLinkNode, node);
inserted_nodes++;
if (matched[6] != '') {
var newTxtNode = document.createTextNode(matched[5]);
node.parentNode.insertBefore(newTxtNode, node);
// do we need to update inserted_nodes with this?
}
}
if (after_text.length > 0) {
var newTxtNode = document.createTextNode(after_text);
node.parentNode.insertBefore(newTxtNode, node);
node.parentNode.removeChild(node);
inserted_nodes = searchNode(newTxtNode,inserted_nodes+1);
}
else {
node.parentNode.removeChild(node);
}
}
return inserted_nodes;
}
var addCSS = function() {
if (!addedCSS) {
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
if (browser.search('MSIE 6.0') != -1) {
browser = 'ie6';
css.href = cdHost+'/theme/bglinks-ie.css';
} else {
css.href = cdHost+'/theme/popover.css';
}
css.media = "screen";
var n1 = document.getElementsByTagName("head")[0].childNodes[0]
n1.parentNode.insertBefore(css,n1);
addedCSS = true;
}
}
var addBiblerefListeners = function() {
var links = document.getElementsByTagName('a');
for ( var i = 0;i< links.length;i++) {
var link = links[i]
if (link.className && link.className == 'bibleref') {
if (that.clickTooltip !== true) {
addListener(link,'mouseover', linkMouseover);
addListener(link,'mouseout', linkMouseout);
} else {
addListener(link,'click', toggleTooltip);
}
}
}
}
var addListener = function (listen_object, action, callback) {
if (listen_object.addEventListener) {
if (action == 'mouseover') {
listen_object.addEventListener("mouseover",callback,false);
} else if (action == 'mouseout') {
listen_object.addEventListener("mouseout",callback,false);
} else if (action == 'click') {
listen_object.addEventListener("click",callback,false);
}
} else if (listen_object.attachEvent) {
if (action == 'mouseover') {
listen_object.attachEvent("onmouseover",callback);
} else if (action == 'mouseout') {
listen_object.attachEvent("onmouseout",callback);
} else if (action == 'click') {
listen_object.attachEvent("onclick",callback);
}
} else {
if (action == 'mouseover') {
listen_object.onmouseover = callback;
} else if (action == 'mouseout'){
listen_object.onmouseout = callback;
} else if (action == 'click') {
listen_object.onclick = callback;
}
}
}
var toggleTooltip = function(e) {
if (!e) {
e = window.event;
}
link = e.target || e.srcElement;
var reference;
var bibleref;
if (bibleref = link.getAttribute('data-bibleref')) {
reference = bibleref;
} else {
reference = link.href.match(/search=(.*?)(?:&.*)?$/)[1];
}
var id = reference.replace(/%20| /g, '');
var id = reference.replace(/:/g, '_');
var tooltip = document.getElementById('bg_popup-'+id);
if (tooltip === null || tooltip.style.display == 'none') {
showTooltip(e);
} else {
hideTooltip(e);
}
}
var showTooltip = function(e) {
if (!e) {
e = window.event;
}
link = e.target || e.srcElement;
var reference;
var bibleref;
if (bibleref = link.getAttribute('data-bibleref')) {
reference = bibleref;
} else {
reference = link.href.match(/search=(.*?)(?:&.*)?$/)[1];
}
var id = reference.replace(/%20| /g, '');
id = id.replace(/:/g, '_');
id = id.replace(/ /g, '');
var tooltip = document.getElementById('bg_popup-'+id);
hideAllTooltips(e);
if (tooltip === null) {
tooltip = getTooltip(reference, link);
} else {
tooltip_loc = tooltipLocation(link);
tooltip.style.left = tooltip_loc.offsetX+'px';
tooltip.style.top = tooltip_loc.offsetY+'px';
tooltip.style.display = 'block';
}
}
var hideTooltip = function(e) {
if (!e) {
e = window.event;
}
target = e.target || e.srcElement;
var reference;
var bibleref;
if (bibleref = link.getAttribute('data-bibleref')) {
reference = bibleref;
} else {
reference = link.href.match(/search=(.*?)(?:&.*)?$/)[1];
}
reference = reference.replace(/%20| /g, '');
reference = reference.replace(/:/g, '_');
var tooltip = document.getElementById('bg_popup-'+reference);
if (tooltip) {
tooltip.style.display = 'none';
}
}
var hideAllTooltips = function(e) {
var divs = container.children;
for (var i = 0;i < divs.length;i++) {
divs[i].style.display = 'none';
}
}
var linkMouseover = function(e) {
if (!e) {
e = window.event;
}
if (e.target.nodeName.toLowerCase() == 'a') {
window.clearTimeout(showTimer);
showTimer = window.setTimeout(function() {showTooltip(e)}, delay);
}
}
var linkMouseout = function(e) {
if (!e) {
e = window.event;
}
if (e.target.nodeName.toLowerCase() == 'a' && showTimer) {
window.clearTimeout(showTimer);
window.clearTimeout(hideTimer);
hideTimer = window.setTimeout(function() {hideTooltip(e)}, delay);
}
}
var tooltipMouseover = function(e) {
if (!e) {
e = window.event;
}
var relNode = e.relatedTarget || e.fromElement;
while (relNode && relNode != null && (!relNode.className || relNode.className.indexOf('bg_popup-outer') == -1) && relNode.nodeName.toLowerCase() != 'body') {
relNode = relNode.parentNode;
}
if (relNode && relNode.className && relNode.className.indexOf('bg_popup-outer') != -1) return;
window.clearTimeout(showTimer);
window.clearTimeout(hideTimer);
}
var tooltipMouseout = function(e) {
if (!e) {
e = window.event;
}
var relNode = e.relatedTarget || e.toElement;
while (relNode && relNode != null && (!relNode.className || relNode.className.indexOf('bg_popup-outer') == -1) && relNode.nodeName.toLowerCase() != 'body') {
relNode = relNode.parentNode;
}
if (relNode && relNode.className && relNode.className.indexOf('bg_popup-outer') != -1) return;
window.clearTimeout(hideTimer);
hideTimer = window.setTimeout(function() {hideAllTooltips(e)}, delay);
}
var createContainer = function() {
container = document.createElement('div');
container.id = 'bg_popup-container';
document.body.appendChild(container);
}
var getTooltip = function(reference, link) {
var tooltip = document.createElement('div');
tooltip.style.display='none';
tooltip.className = 'bg_popup bg_popup-outer';
var tooltip_loc = tooltipLocation(link);
tooltip.style.top = tooltip_loc.offsetY+'px';
tooltip.style.left = tooltip_loc.offsetX+'px';
var id = 'bg_popup-'+reference.replace(/%20/g, '');
id = id.replace(/:/g, '_');
id = id.replace(/ /g, '');
tooltip.id=id;
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference.replace(/%20/g, ' ')+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-spinner"><img alt="loading" src="'+cdHost+'/theme/images/tools/spinner.gif"/></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
tooltip.style.display = 'block';
addCloseButton(tooltip);
tooltip = container.appendChild(tooltip);
if (that.clickTooltip !== true) {
addListener(tooltip,'mouseover', tooltipMouseover);
addListener(tooltip,'mouseout', tooltipMouseout);
}
var remote_passage = document.createElement('script');
remote_passage.type = 'text/javascript';
remote_passage.src = toolsHost+'/?search='+reference+'&version='+that.version+'&callback=BGLinks.updateTooltip';
remote_passage.id = 'bg_remote_passage_script-'+reference.replace(/%20/g, '');
remote_passage.id = remote_passage.id.replace(/:/g, '_');
remote_passage.id = remote_passage.id.replace(/ /g, '');
var hook = document.getElementsByTagName('script')[0];
hook.parentNode.insertBefore(remote_passage, hook);
return tooltip;
}
that.updateTooltip = function(tooltip_content) {
var id = 'bg_popup-'+tooltip_content.reference.replace(/%20/g, '');
id = 'bg_popup-'+tooltip_content.reference.replace(/:/g, '_');
id = id.replace(/ /g, '');
var tooltip = document.getElementById(id);
var reference_display = tooltip_content.reference_display.replace(/%20/g,' ');
if (tooltip_content.text == undefined) {
if (tooltip.text == undefined) {
tooltip_content.text = 'Retrieving Passage...'
}
else {
tooltip_content.text = tooltip.text;
reference_display = tooltip.reference_display;
}
}
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference_display+' '+tooltip_content.version+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-content-bible"><p>'+tooltip_content.text+' <a class="bg_popup-copyright" href="'+bgHost+tooltip_content.version_url+'" target="_blank">('+tooltip_content.version+')</a> <a class="bg_popup-more" href="'+bgHost+'/passage/?search='+tooltip_content.reference+'&version='+tooltip_content.version+'&src=tools" target="_blank">More</a></p></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
addCloseButton(tooltip);
}
var addCloseButton = function(tooltip) {
var divs = tooltip.getElementsByTagName('div');
for (var i = 0; i < divs.length;i++) {
if (divs[i].className == 'bg_popup-header_right') {
addListener(divs[i], 'click', hideAllTooltips);
}
}
}
var tooltipLocation = function(link) {
var tooltip_height = 234;
var tooltip_width = 362;
if (typeof(window.innerWidth) == 'number') {
width = window.innerWidth;
height = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
width = document.body.clientWidth;
height = document.body.clientHeight;
}
var display_loc = {};
var offsetPos = getOffsetPos(link);
var leftPos = offsetPos.leftPos;
var topPos = offsetPos.topPos;
if (link.offsetWidth/link.parentNode.offsetWidth >.5) {
leftPos = getOffsetPos(link.parentNode);
leftPos = leftPos.leftPos;
}
if ((leftPos + tooltip_width+5) > width) {
leftPos -= tooltip_width;
if ((leftPos + tooltip_width + link.offsetWidth) <= width) leftPos += link.offsetWidth;
if (leftPos + tooltip_width + 25 <= width) leftPos += 25;
if (leftPos - (link.offsetWidth/2) >= 0) leftPos -= (link.offsetWidth/2);
} else {
if (leftPos + (link.offsetWidth/2) <= width && link.offsetWidth/link.parentNode.offsetWidth <=.5) leftPos += (link.offsetWidth/2);
if (leftPos - 35 >= 0) {
leftPos -= 35;
}
}
var scrollY = window.pageYOffset || document.documentElement.scrollTop || 0;;
if ((topPos+link.offsetHeight+tooltip_height+15) <= height +scrollY || topPos-tooltip_height+5 <0) {
topPos += link.offsetHeight + 10;
} else {
topPos -= tooltip_height + 10;
}
display_loc.offsetY = topPos;
display_loc.offsetX = leftPos;
return (display_loc);
}
var getOffsetPos = function(linkObj) {
var topPos = leftPos = 0;
do {
topPos += linkObj.offsetTop;
leftPos += linkObj.offsetLeft;
if(document.all) {
topPos+=linkObj.clientTop;
leftPos+=linkObj.clientLeft;
}
} while ((linkObj = linkObj.offsetParent) != null);
return {'topPos' : topPos, 'leftPos' : leftPos};
}
var setup = function() {
if (!setupRun) {
if (that.showTooltips === true) {
addCSS();
addListener(document, 'click', hideAllTooltips);
}
createContainer();
setupRun = true;
}
}
return that;
})();
$(document).ready(function() {
BGLinks.linkVerses();
});
This is the script, located at http://churchofcwa.wikia.com/wiki/MediaWiki:Common.js/bglinks.js, that I am encountering an error with css, this script was copied from https://www.biblegateway.com/public/link-to-us/tooltips/bglinks.js and is not made by me. The issue I am encountering is via the css page (MediaWiki:Common.css) when changing the color of the script by
.bg_popup-content-bible {color:#000000}
The font color of the p tag within that div does not change. Originally I had it set to the p tag specifically of that div, but a css checker said that styling would be overqualified, and it was not functional nevertheless. What the script does is take all Bible verses listed on a page, and automatically links them to Biblegateway and creates a preview popup when hovering. However, the font is very unreadable and so I have tried to change it to black.
The popup currently has a near-white font (that blends with the popup)
and needs to have a black font, with the rest of the page content needs the near white font. When the script runs through it generates a div surrounding each bible verse, and the js applies to it (the div in which the Bible verse text appears is in the bg_popup-content-bible with a <p> tag), making it popup like so.
I have noted that in the script there is a section that calls for a "addedCSS"
var addCSS = function() {
if (!addedCSS) {
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
if (browser.search('MSIE 6.0') != -1) {
browser = 'ie6';
css.href = cdHost + '/theme/bglinks-ie.css';
} else {
css.href = cdHost + '/theme/popover.css';
}
css.media = "screen";
var n1 = document.getElementsByTagName("head")[0].childNodes[0]
n1.parentNode.insertBefore(css, n1);
addedCSS = true;
}
}
I do not believe it is possible to change the url that the addedCss pull from, from the MediaWiki:Common.css, as this script was not made for the specific system being used (when removing or altering the variable the script does not work). I don't know if this is not happening because of a javascript issue (which is beyond me, and it's difficult to alter the script without breaking it) or if it's just a matter of incorrect css, but I have been working on this for several months here and there, and would like to get this final detail to work.
Try changing it to
.bg_popup-content-bible {color:#000000 !important;}
Ignore the CSS specificity checker. I have tested the below css on your site and it works. Make sure to put it in your site.css.
.bg_popup-content-bible p {
color: #000000;
}
It needs to be written as above because it has to override the <p> styling you've already set earlier in site.css:
p {
color: #f5f5f5
}
EDIT
It is not a problem with the script. Based on what you have said in the comments it seems like you are unable to actually edit / output css. So the other option is just to modify the script you've posted above:
Change this:
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference_display+' '+tooltip_content.version+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-content-bible"><p>'+tooltip_content.text+' <a class="bg_popup-copyright" href="'+bgHost+tooltip_content.version_url+'" target="_blank">('+tooltip_content.version+')</a> <a class="bg_popup-more" href="'+bgHost+'/passage/?search='+tooltip_content.reference+'&version='+tooltip_content.version+'&src=tools" target="_blank">More</a></p></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
to this:
tooltip.innerHTML = '<div class="bg_popup-header"><div class="bg_popup-header_title"><strong>'+reference_display+' '+tooltip_content.version+'</strong></div></div><div class="bg_popup-content"><div class="bg_popup-content-bible"><p style="color:#000000">'+tooltip_content.text+' <a class="bg_popup-copyright" href="'+bgHost+tooltip_content.version_url+'" target="_blank">('+tooltip_content.version+')</a> <a class="bg_popup-more" href="'+bgHost+'/passage/?search='+tooltip_content.reference+'&version='+tooltip_content.version+'&src=tools" target="_blank">More</a></p></div></div><div class="bg_popup-footer"><a class="bg_popup-bglogo" href="'+bgHost+'/" target="_blank"></a></div>';
Given the way Stack formats the code above, to make it very clear you are editing the part of the line above that says:
<p>'+tooltip_content.text+'
and making it:
<p style="color:#000000">'+tooltip_content.text+'

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Categories

Resources