JavaScript game with a lagging Mobile Button Controls - javascript

I've created a simple keyboard controlled JavaScript game (extra task from front-end bootcamp I finished recently). A few days ago I decided to add controls for mobile devices, and while keyboard control works well (response from the game is instantaneous), mobile controls 'suffer' from some kind of lag.
Main game controlling JS code:
var Zombie = require('./zombie.js');
var Brain = require('./brain.js');
var Trap = require('./trap.js');
function Game() {
this.board = document.querySelectorAll('#board div');
this.zombie = new Zombie();
this.brain = new Brain();
this.trap = new Trap();
this.trap2 = new Trap();
this.trap3 = new Trap();
this.trap4 = new Trap();
this.trap5 = new Trap();
this.score = 0;
this.speed = 320;
this.index = function(x, y) {
return x + (y * 10);
}
this.showZombie = function() {
this.board[this.index(this.zombie.x, this.zombie.y)].classList.add('zombie');
}
this.hideVisibleZombie = function() {
document.querySelector('.zombie').classList.remove('zombie');
}
this.showBrain = function() {
this.board[this.index(this.brain.x, this.brain.y)].classList.add('brain');
if(!(this.brain.x === this.trap.x && this.brain.y === this.trap.y)) {
this.board[this.index(this.trap.x, this.trap.y)].classList.add('trap');
}
if(!(this.brain.x === this.trap2.x && this.brain.y === this.trap2.y)) {
this.board[this.index(this.trap2.x, this.trap2.y)].classList.add('trap');
}
if(!(this.brain.x === this.trap3.x && this.brain.y === this.trap3.y)) {
this.board[this.index(this.trap3.x, this.trap3.y)].classList.add('trap');
}
if(!(this.brain.x === this.trap4.x && this.brain.y === this.trap4.y)) {
this.board[this.index(this.trap4.x, this.trap4.y)].classList.add('trap');
}
if(!(this.brain.x === this.trap5.x && this.brain.y === this.trap5.y)) {
this.board[this.index(this.trap5.x, this.trap5.y)].classList.add('trap');
}
}
this.moveZombie = function() {
this.hideVisibleZombie();
if (this.zombie.direction === "right") {
this.zombie.x += 1;
} else if (this.zombie.direction === "left") {
this.zombie.x -= 1;
} else if (this.zombie.direction === "up") {
this.zombie.y -= 1;
} else if (this.zombie.direction === "down") {
this.zombie.y += 1;
}
if (!(this.gameOver())) {
this.showZombie();
this.checkBrainCollision();
}
}
this.turnZombie = function(event) {
switch (event.which /*|| e.which*/) {
case 37:
this.zombie.direction = 'left';
break;
case 38:
this.zombie.direction = 'up';
break;
case 39:
this.zombie.direction = 'right';
break;
case 40:
this.zombie.direction = 'down';
break;
}
}
this.turnMobileZombie = function(event) {
switch (true) {
case event.currentTarget.classList.contains('up'):
this.zombie.direction = 'up';
break;
case event.currentTarget.classList.contains('down'):
this.zombie.direction = 'down';
break;
case event.currentTarget.classList.contains('left'):
this.zombie.direction = 'left';
break;
case event.currentTarget.classList.contains('right'):
this.zombie.direction = 'right';
break;
}
}
this.checkBrainCollision = function() {
if (this.zombie.x === this.brain.x && this.zombie.y === this.brain.y) {
document.querySelector('.brain').classList.remove('brain');
document.querySelectorAll('.trap').forEach(e => e.classList.remove('trap'));
document.querySelector('.eat').play();
this.score++
document.querySelector('#score strong').innerText = this.score;
this.increaseSpeed();
this.brain = new Brain();
this.trap = new Trap();
this.trap2 = new Trap();
this.trap3 = new Trap();
this.trap4 = new Trap();
this.trap5 = new Trap();
this.showBrain();
} else {
return;
}
}
this.gameOver = function() {
if (
(this.zombie.x < 0 || this.zombie.x > 9 || this.zombie.y < 0 || this.zombie.y > 9) ||
((this.zombie.x === this.trap.x && this.zombie.y === this.trap.y) && (this.brain.x !== this.trap.x || this.brain.y !== this.trap.y)) ||
((this.zombie.x === this.trap2.x && this.zombie.y === this.trap2.y) && (this.brain.x !== this.trap2.x || this.brain.y !== this.trap2.y)) ||
((this.zombie.x === this.trap3.x && this.zombie.y === this.trap3.y) && (this.brain.x !== this.trap3.x || this.brain.y !== this.trap3.y)) ||
((this.zombie.x === this.trap4.x && this.zombie.y === this.trap4.y) && (this.brain.x !== this.trap4.x || this.brain.y !== this.trap4.y)) ||
((this.zombie.x === this.trap5.x && this.zombie.y === this.trap5.y) && (this.brain.x !== this.trap5.x || this.brain.y !== this.trap5.y))
) {
document.querySelector('.dead').play();
clearInterval(this.idSetInterval);
document.querySelector('.brain').classList.remove('brain');
document.querySelectorAll('.trap').forEach(e => e.classList.remove('trap'));
document.querySelector('#over').classList.remove('invisible');
document.querySelector('#over').classList.remove('none');
document.querySelector('p span').innerText = this.score;
return true;
} else {
return false;
}
}
var self = this;
document.addEventListener('keydown', function(event) {
self.turnZombie(event);
});
document.querySelectorAll('.mobile-controller div').forEach((e,i) => {
if(e.classList.contains('up') || e.classList.contains('down') || e.classList.contains('left') || e.classList.contains('right')) {
e.addEventListener('click', function(event) {
self.turnMobileZombie(event);
})
};
})
// $(document).on('click', '.mobile-controller div', function(e) {
// var e = jQuery.Event("keydown");
// if ($(this).hasClass('left')) {
// e.which = 37;
// self.turnZombie(e);
// }
// else if ($(this).hasClass('up')) {
// e.which = 38;
// self.turnZombie(e);
// }
// else if ($(this).hasClass('right')) {
// e.which = 39;
// self.turnZombie(e);
// }
// else if ($(this).hasClass('down')) {
// e.which = 40;
// self.turnZombie(e);
// }
// $(document).trigger(e);
// });
this.startGame = function() {
this.idSetInterval = setInterval(function() {
self.moveZombie()
}, this.speed);
}
this.increaseSpeed = function () {
this.speed -= 5;
clearInterval(this.idSetInterval);
this.idSetInterval = setInterval(function() {
self.moveZombie()
}, this.speed);
};
}
module.exports = Game;
Preview of the game here: link
Link to GitHub repo here: link
As You can see, I've tried a jQuery solution - controls work, but still with the same lag. I'd appreciate any help.

Related

JavaScript - The function only execute after set breakpoint

Here is my jQuery for dynamic attached elements. The jq-select-ring button can be multiple on the DOM. Basically, it was attached through an Ajax call.
let cKeyTabShift = false;
$("body").on("keydown", ".jq-select-ring", function (e) {
if (!isMobileSite) {
var keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode == 9) {
if (e.shiftKey) {
cKeyTabShift = true;
} else {
cKeyTabShift = false;
}
}
}
});
$("body").on("focusout", ".jq-select-ring", function () {
if (!isMobileSite) {
const parentIndex = $(this).closest('.flex-item').index();
const $elmSliders = $(this).closest('.container').find("div[id^='touchCarousel-'][role='tabpanel']");
const $nextArrow = $(this).closest('.touch-carousel').find('.touchcarousel-next');
const $prevArrow = $(this).closest('.touch-carousel').find('.touchcarousel-prev');
if (typeof ($elmSliders) != "undefined" && $elmSliders.length > 0) {
if ($elmSliders.length > 1) {
if (parentIndex == 1 && cKeyTabShift == false) {
if (!$nextArrow.hasClass('endArrows')) {
$nextArrow.trigger('click');
}
}
if (parentIndex == 0 && cKeyTabShift == true) {
if (!$prevArrow.hasClass('endArrows')) {
$prevArrow.trigger('click');
cKeyTabShift = false;
}
}
}
}
}
});
The issue is the trigger click is called when I add breakpoint only.
$nextArrow.trigger('click');
$prevArrow.trigger('click');

Javascript: Global Variables Aren't Defined In Other Functions

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.

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

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

How to fix and work with tree toc?(old syntax)

so i bought a site witch is connected to a gestional programm in office..
the site is a little old, it's fully compatible with all the versions of internet explorer but not with other browsers(opera,safari,chrome,firefox...)
the only piece not working is a menu not opening correctly, when you click on it it doesn't happen anything or in chrome it changes the image but it doesn't upload the links. it seems that it doens't upload things in the hiddenframe...
in chrome it gives error in loadchildren function.
in firefox it gives error in function Toc_click ()
TypeError: window.event is undefined
[Break On This Error]
var eSrc = window.event.srcElement;
we searched for the problem and we think that the problem should be in this file
the problem should be a syntax problem, it's compatible in old browsers but not on the new ones. i cannot change completely the code as it is connected with other files(a lot) and sql server...
we already tried to change
document.frames["hiddenframe"].location.replace(strLoc);
by
document.getElementsByName("hiddenframe").location.replace(strLoc);
it doens't work and it doesn't work on IE either...
/* TOC.JS */
var framesTop = parent.parent;
//var L_LoadingMsg_HTMLText = "Loading, click to cancel...";
var LoadDiv = '<DIV ONCLICK="loadFrame(true);" CLASS="clsLoadMsg">';
L_LoadingMsg_HTMLText = LoadDiv + L_LoadingMsg_HTMLText + "</LI>";
function caps(){
var UA = navigator.userAgent;
if(UA.indexOf("MSIE") != -1)
{
this.ie = true;
this.v = UA.charAt(UA.indexOf("MSIE") + 5);
if( this.v == 2 ) this.ie2 = true;
else if( this.v == 3 ) this.ie3 = true;
else if( this.v == 4 ) this.ie4 = true;
else if( this.v == 5 ) this.ie5 = true;
else if( this.v == 6 ) this.ie6 = true;
else this.ie6 = true;
}
else if(UA.indexOf("Mozilla") != -1 && UA.indexOf("compatible") == -1)
{
this.nav = true;
var v = UA.charAt(UA.indexOf("Mozilla") + 8);
if(v == 2 ) this.nav2 = true;
else if(v == 3 ) this.nav3 = true;
else if(v == 4 ) this.nav4 = true;
}
if(UA.indexOf("Windows 95") != -1 || UA.indexOf("Win95") != -1 || UA.indexOf("Win98") != -1 || UA.indexOf("Windows 98") != -1 || UA.indexOf("Windows NT") != -1 || UA.indexOf("Windows XP") != -1) this.win32 = true;
else if(UA.indexOf("Windows 3.1") != -1 || UA.indexOf("Win16") != -1) this.win16 = true;
else if(UA.indexOf("Mac") != -1) this.anymac = true;
else if(UA.indexOf("SunOS") != -1 || UA.indexOf("HP-UX") != -1 || UA.indexOf("X11") != -1) this.unix = true;
else if(UA.indexOf("Windows CE") != -1) this.wince = true;
}
var bc = new caps();
////////////////////////////////////////////
// Not sure why this is here, it puts a scrollbar up when none is needed
// if("object" == typeof(parent.document.all.fraPaneToc)) parent.document.all.fraPaneToc.scrolling = "yes";
////////////////////////////////////////////
var eSynchedNode = null;
var eCurrentUL = null;
var eCurrentLI = null;
var bLoading = false;
function loadFrame( bStopLoad )
{
if( "object" == typeof( eCurrentUL ) && eCurrentUL && !bStopLoad )
{
eCurrentUL.innerHTML = hiddenframe.chunk.innerHTML;
eCurrentUL = null;
bLoading = false;
}
else if( "object" == typeof( eCurrentUL ) && eCurrentUL )
{
eCurrentUL.parentElement.children[1].className = "";
eCurrentUL.parentElement.children[0].src = "bs.gif";
eCurrentUL.parentElement.className = "kid";
eCurrentUL.className = "clsHidden";
eCurrentUL.innerHTML="";
eCurrentUL = null;
bLoading = false;
}
else
{
bLoading = false;
}
return;
}
function GetNextUL(eSrc)
{
var eRef = eSrc;
for(var i = eRef.sourceIndex + 1; i < document.all.length; i++)
{
if( "UL" == document.all[ i ].tagName )
{
return document.all[ i ];
}
else if( "LI" == document.all[ i ].tagName )
{
break;
}
}
return false;
}
function MarkSync(eSrc)
{
if("object" == typeof(aNodeTree)) aNodeTree = null;
if("LI" == eSrc.tagName.toUpperCase() && eSrc.children[1] && eSynchedNode != eSrc )
{
UnmarkSync();
eSrc.children[1].style.fontWeight = "bold";
eSynchedNode = eSrc;
}
}
function UnmarkSync()
{
if("object" == typeof(eSynchedNode) && eSynchedNode )
{
eSynchedNode.children[1].style.fontWeight = "normal";
eSynchedNode = null;
}
}
function MarkActive(eLI)
{
if( "object" == typeof( eLI ) && eLI && "LI" == eLI.tagName.toUpperCase() && eLI.children[1] && eLI != eCurrentLI )
{
MarkInActive();
window.eCurrentLI = eLI;
window.eCurrentLI.children[1].className = "clsCurrentLI";
}
}
function MarkInActive()
{
if( "object" == typeof( eCurrentLI ) && eCurrentLI )
{
window.eCurrentLI.children[1].className = "";
window.eCurrentLI = null;
}
}
function LoadChildren( eLink )
{
var strLoc = "loadtree.asp" + eLink.href.substring( eLink.href.indexOf( "?" ) );
document.frames["hiddenframe"].location.replace(strLoc);
}
function Navigate_URL( eSrc )
{
var eLink = eSrc.parentElement.children[1];
urlIdx = eLink.href.indexOf( "URL=" );
if("object" == typeof(framesTop.fraTopic) && eLink && "A" == eLink.tagName && urlIdx != -1 )
{
if(eLink.target=="fraTopic"||eLink.target=="_top"){
framesTop.fraTopic.location.href = eSrc.parentElement.children[1].href.substring( urlIdx + 4 );
}else{
window.open(eSrc.parentElement.children[1].href,eLink.target);
}
MarkSync(eSrc.parentElement);
}
else if("object" == typeof(framesTop.fraTopic) && eLink && "A" == eLink.tagName && eLink.href.indexOf( "tocPath=" ) == -1 && eLink.href.indexOf( "javascript:" ) == -1 )
{
if(eLink.target=="fraTopic")
{
framesTop.fraTopic.location.href = eSrc.parentElement.children[1].href;
}
else if( eLink.target=="_top" )
{
top.location = eLink.href;
return;
}
else
{
window.open(eSrc.parentElement.children[1].href,eLink.target);
}
MarkSync(eSrc.parentElement);
}
else if( eSynchedNode != eSrc.parentElement && ( urlIdx != -1 || ( eLink.href.indexOf( "javascript:" ) == -1 && eLink.href.indexOf( "tocPath=" ) == -1 ) ) )
{
// START D.S.
if(eLink.target=="fraTopic")
{
if (navigator.userAgent.indexOf("Windows") == -1) {
var MyHref = eSrc.parentElement.children[1].href;
do
{
if (MyHref.indexOf("%2E") != -1) MyHref = MyHref.replace("%2E", ".");
else if (MyHref.indexOf("%2F") != -1) MyHref = MyHref.replace("%2F", "/");
else if (MyHref.indexOf("%3F") != -1) MyHref = MyHref.replace("%3F", "?");
else if (MyHref.indexOf("%3D") != -1) MyHref = MyHref.replace("%3D", "=");
else if (MyHref.indexOf("%26") != -1) MyHref = MyHref.replace("%26", "&");
else break;
}
while (true);
parent.fraTopic.location.href = MyHref;
} else {
parent.fraTopic.location.href = eSrc.parentElement.children[1].href;
}
}
// END D.S.
MarkSync( eSrc.parentElement );
}
}
function Image_Click( eSrc , bLeaveOpen )
{
var eLink = eSrc.parentElement.children[1];
if("noHand" != eSrc.className)
{
eLI = eSrc.parentElement;
MarkActive(eLI);
var eUL = GetNextUL(eLI);
if(eUL && "kidShown" == eLI.className)
{
// hide on-page kids
if( !bLeaveOpen )
{
eLI.className = "kid";
eUL.className = "clsHidden";
eSrc.src = "bs.gif";
}
}
else if(eUL && eUL.all.length)
{
// show on-page kids
eLI.className = "kidShown";
eUL.className = "clsShown";
eSrc.src = "bo.gif";
}
else if("kid" == eLI.className)
{
// load off-page kids
if( !bLoading )
{
bLoading = true;
eLI.className = "kidShown";
eUL.className = "clsShown";
window.eCurrentUL = eUL;
eSrc.src = "bo.gif";
eUL.innerHTML = L_LoadingMsg_HTMLText;
LoadChildren( eLink );
}
}
}
}
function Toc_click ()
{
var eSrc = window.event.srcElement;
event.returnValue = false;
if("A" == eSrc.tagName.toUpperCase() && "LI" == eSrc.parentElement.tagName)
{
var eImg = eSrc.parentElement.children[0];
if(eImg) eImg_click(eImg);
}
else if("SPAN" == eSrc.tagName && "LI" == eSrc.parentElement.tagName)
{
var eImg = eSrc.parentElement.children[0];
if(eImg) eImg_click(eImg);
}
else if("IMG" == eSrc.tagName)
{
}
return event.returnValue;
}
function eImg_click(eImg)
{
if("IMG" == eImg.tagName)
{
Image_Click( eImg , false );
Navigate_URL( eImg );
}
}
function Toc_dblclick()
{
return;
}
function window_load()
{
if( self == top ) location.replace( "default.asp" );
var objStyle = null;
if( bc.win32 && ( bc.ie4 || bc.ie5 || bc.ie6 ) && "object" == typeof ( ulRoot ) && "object" == typeof( objStyle = document.styleSheets[0] ) && "object" == typeof( objStyle.addRule ) )
{
window.eSynchedNode = document.all["eSynchedNode"];
objStyle.addRule( "UL.clsHidden" , "display:none" , 0 );
objStyle.addRule( "UL.hdn" , "display:none" , 0 );
//--ulRoot.onclick=Toc_click;
ulRoot.ondblclick=Toc_dblclick;
if( window.eSynchedNode )
{
MarkActive(window.eSynchedNode);
window.eSynchedNode.all.tags( "B" )[0].outerHTML = eSynchedNode.all.tags("B")[0].innerHTML;
window.scrollTo(0,window.eSynchedNode.offsetTop-(document.body.clientHeight/2));
}
else
{
MarkActive(document.all.tags( "LI" )[0]);
}
}
}
window.onload = window_load;
suggestions?

Categories

Resources