How to disable function based on condistion - JS - javascript

Hope someone can help. I'm new to JS and need some help.
I have the following code:
}
function onBall3Click() {
var ball3 = document.querySelector('.ball3');
alert('Ball3');
if (ball3.innerText == 'OFF') {
ball3.style.backgroundColor = 'yellow';
ball3.innerText = 'ON';
} else if (ball3.innerText == 'ON') {
ball3.style.backgroundColor = 'gray';
ball3.innerText = 'OFF';
}
}
function onBall4Click() {
var ball4 = document.querySelector('.ball4');
alert('Ball4');
var size = prompt("What should be the size of the ball?");
if (size > 1000) {
alert('Too Big!')
} else {
ball4.style.width = size;
ball4.style.height = size;
}
what I need to know is how to disable function onBall4click when the Ball3.innerText = 'OFF'
and how to enable the function once the Ball3.innerText = 'ON'
Appreciate all the support.

I am not an expert in Javascript but I think all you need to do is add a guard clause in the onBall4click function and check if Ball3 is ON before doing anything. The modified function would look something like this:
function onBall4Click() {
var ball3 = document.querySelector(".ball3");
if(ball3.innerText === "OFF") return;
var ball4 = document.querySelector('.ball4');
alert('Ball4');
var size = prompt("What should be the size of the ball?");
if (size > 1000) {
alert('Too Big!')
} else {
ball4.style.width = size;
ball4.style.height = size;
}
}
When you click on Ball 4, the function checks Ball3 and stops executing if it is off.

Related

Google Scripts - Using a drop-down menu to show a balance

So I have used data validation to create a drop-down menu that will then update some cells to show the budget amount that is remaining from another sheet. Nothing is occurring when I try to update the field.
The first check for if a checkbox is marked true all works, so I know it is entering the first if. I just can't seem to get it to enter the second if.
function onEdit(e) {
var sheet=e.range.getSheet();
var rgA1=e.range.getA1Notation();
if (sheet.getName()=="Entry") {
console.log("Entry")
if (e.value == "TRUE") {
submit();
Today();
e.range.setValue("FALSE");
}
if (rgA1=="A8" || rgA1 == "B8") {
var entry = e.source.getSheetByName("Entry");
var summary = e.source.getSheetByName("Summary");
var day = entry.getRange("B9").getValue();
var month = entry.getRange("B10").getValue();
var total = entry.getRange("B11").getValue();
var today = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy");
//var daysRemaining = DATEIF(today, summary.getRange("D4"), "D");cell functions not allow
//var monthsRemaining = DATEIF(today, summary.getRange("D4"), "M");cell functions not allowed
console.log("Entered 2nd if")
if (e.value == summary.getRange("B59").getValue) {
var balance = summary.getRange("E59").getValue
console.log("Entered 3rd if")
}
else if (e.value == summary.getRange("B60").getValue()) {
var balance = summary.getRange("E60").getValue()
}
else if (e.value == summary.getRange("B61").getValue()) {
var balance = summary.getRange("E61").getValue()
}
else if (e.value == summary.getRange("B62").getValue()) {
var balance = summary.getRange("E62").getValue()
}
else if (e.value == summary.getRange("B63").getValue()) {
var balance = summary.getRange("E63").getValue()
}
else if (e.value == summary.getRange("B64").getValue()) {
var balance = summary.getRange("E64").getValue()
}
else if (e.value == summary.getRange("B65").getValue()) {
var balance = summary.getRange("E65").getValue()
}
else if (e.value == summary.getRange("B66").getValue()) {
var balance = summary.getRange("E66").getValue()
}
else if (e.value == summary.getRange("B67").getValue()) {
var balance = summary.getRange("E67").getValue()
}
else if (e.value == summary.getRange("B68").getValue()) {
var balance = summary.getRange("E68").getValue()
}
else if (e.value == summary.getRange("B69").getValue()) {
var balance = summary.getRange("E69").getValue()
}
else if (e.value == summary.getRange("B70").getValue()) {
var balance = summary.getRange("E70").getValue()
}
else if (e.value == summary.getRange("B71").getValue()) {
var balance = summary.getRange("E71").getValue()
}
day.setValue(balance / 56);
month.setValue(balance / 2);
total.setValue(balance);
}
}
}
Any thanks would be hugely appreciated!
EDIT 5/8/20
Fixed using Cooper's suggestions
Also here is a copy of the sheet this script is for.
That's better but you still have some problems at the end.
function onEdit(e) {
var sheet=e.range.getSheet();
var rgA1=e.range.getA1Notation();
if (sheet.getName()=="Entry") {
console.log("Entry")
if (e.value == "TRUE") {
submit();
Today();
e.range.setValue("FALSE");
}
if (rgA1=="A8" || rgA1 == "B8") {
var entry = e.source.getSheetByName("Entry");
var summary = e.source.getSheetByName("Summary");
var dA=entry.getRange('B9:B11').getValues();
var day = dA[0][0];
var month = dA[0][1];
var total = dA[0][2];
var today = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy");
var bvs=summary.getRange('B59:B71').getValues();
var erg=summary.getRange('E59:E71');
var evs=erg.getValues();
for(var i=0;i<bvs.length;i++) {
if(e.value==bvs[i][0]) {
var balance=evs[i][0];
break;
}
}
entry.getRange('B9').setValue(balance/56);
entry.getRange('B10').setValue(balance/2);
entry.getRange('B11').setValue(balance);
//day.setValue(balance / 56);//day is not a range so there is no setValue Method
//month.setValue(balance / 2);//day is not a range so there is no setValue Method
//total.setValue(balance);//day is not a range so there is no setValue Method
}
}
}

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);
}

Javascript and ascii homework

I have an assignment where I have to select an animation and run it. It works except the turbo function doesnt work like its suppose to and I'm not sure how to change the font size here is the link http://turing.plymouth.edu/~besopko/hw6/ascii.html
My php is:
var frameStr;
var frameSeq;
var currentFrame;
var frameanime;
var q;
var startspeed = 250;
function startFunction(){
frameStr = document.getElementById("Frame").value;
if(frameStr.indexOf("\r\n")!=-1){
frameSeq = frameStr.split("=====\r\n");
}
else{
frameSeq = frameStr.split("=====\n");
currentFrame = 0;
q = setInterval(NextFrame, startspeed);
}
}
function AnimeFunction(){
frameanime = document.getElementById("animation").value;
if(frameanime == "EXERCISE"){
$("Frame").value = EXERCISE;
}
else if(frameanime == "JUGGLER"){
$("Frame").value = JUGGLER;
}
else if(frameanime == "BIKE"){
$("Frame").value = BIKE;
}
else if(frameanime == "DIVE"){
$("Frame").value = DIVE;
}
else if(frameanime == "CUSTOM"){
$("Frame").value = CUSTOM;
}
}
function NextFrame(){
document.getElementById("Frame").value = frameSeq[currentFrame];
currentFrame = (currentFrame+1)% frameSeq.length;
}
function stopFunction(){
clearInterval(q);
}
//this function isn't working properly
function turboFunction(){
var speed = document.getElementById("speed1");
if(speed.checked){
startspeed = 50;
q = setInterval(nextFrame, startspeed);
}
else {
startspeed = 250;
q = setInterval(nextFrame, startspeed);
}
}
function sizeFunction(){
text = document.getElementById("size").value;
if(text == "tiny"){
$("Frame").value = //stuck here;
}
}
I'm not sure why the turboFunction() is working incorrectly and I'm not exactly sure how to change the font size of the ascii animation. Any input would be very helpful.

Snake Game in Javascript

I'm really new to Javascript, so I decided to create a simple SnakeGame to embed in HTML. However, my code for changing the snake's direction freezes up after a few turns.
Note: I'm running this in an HTML Canvas.
Source:
var Canvas;
var ctx;
var fps = 60;
var x = 0;
var seconds = 0;
var lastLoop;
var thisLoop;
var tempFPS = 0;
var blockList = [];
var DEFAULT_DIRECTION = "Right";
var pendingDirections = [];
function update() {
x += 1;
thisLoop = new Date();
tempFPS = 1000 / (thisLoop - lastLoop);
lastLoop = thisLoop;
tempFPS = Math.round(tempFPS*10)/10;
if (x==10){
document.getElementById("FPS").innerHTML = ("FPS: " + tempFPS);
}
//Rendering
for (var i = 0; i<blockList.length; i++){
var block = blockList[i];
draw(block.x, block.y);
}
if (x==5){
x=0;
seconds+=1;
//Updates once per x frames
moveBlocks();
}
}
function moveBlocks(){
if(blockList.length === 0){
return;
}
for (var j = 0; j<pendingDirections.length; j++){
if (b >= blockList.length -1){
pendingDirections.shift();
}else {
//Iterates through each direction that is pending
var b = pendingDirections[j].block;
try{
blockList[b].direction = pendingDirections[j].direction;
} catch(err){
alert(err);
}
pendingDirections[j].block++;
}
}
for (var i = 0; i<blockList.length; i++){
var block = blockList[i];
clear(block.x, block.y);
if (block.direction == "Down"){
block.y += BLOCK_SIZE;
} else if (block.direction == "Up"){
block.y -= BLOCK_SIZE;
} else if (block.direction == "Left"){
block.x -= BLOCK_SIZE;
} else if (block.direction == "Right"){
block.x += BLOCK_SIZE;
} else {
alert(block.direction);
}
draw(block.x, block.y);
}
}
function init(){
lastLoop = new Date();
window.setInterval(update, 1000/fps);
Canvas = document.getElementById("Canvas");
ctx = Canvas.getContext("2d");
}
//The width/height of each block
var BLOCK_SIZE = 30;
//Draws a block
function draw(x, y) {
ctx.fillStyle = "#000000";
ctx.fillRect(x,y,BLOCK_SIZE,BLOCK_SIZE);
}
function clear(x,y){
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(x,y,BLOCK_SIZE,BLOCK_SIZE);
}
function processInput(key){
if (key == 110){
//n (new)
newBlock(BLOCK_SIZE*4,0);
newBlock(BLOCK_SIZE*3,0);
newBlock(BLOCK_SIZE*2,0);
newBlock(BLOCK_SIZE*1,0);
newBlock(0,0);
} else if (key == 119){
changeDirection("Up");
} else if (key == 115){
changeDirection("Down");
} else if (key == 97){
changeDirection("Left");
} else if (key == 100){
changeDirection("Right");
} else if (key==122){
var pDir = "Pending Directions: ";
for (var i = 0; i<pendingDirections.length; i++){
pDir += pendingDirections[i].direction + ", ";
}
alert(pDir);
} else if (key == 120){
var dir = "Directions: ";
for (var j = 0; j<blockList.length; j++){
dir += blockList[j].direction + ", ";
}
alert(dir);
} else {
alert("KEY: " +key);
}
}
function changeDirection(d){
var LD = blockList[0].direction;
var valid = false;
if (d == "Up"){
if(LD != "Down"){
valid = true;
}
} else if (d == "Down"){
if(LD != "Up"){
valid = true;
}
} else if (d == "Left"){
if(LD != "Right"){
valid = true;
}
} else if (d == "Right"){
if(LD != "Left"){
valid = true;
}
}
if (d == LD) { valid = false;}
if (valid){
var dir = {'direction' : d, 'block' : 0};
pendingDirections.unshift(dir);
}
}
function newBlock(x, y){
var block = {'x': x, 'y' : y, 'direction' : DEFAULT_DIRECTION};
//This works: alert(block['x']);
draw(x,y);
blockList.push(block);
}
Thanks
As Evan said, the main issue is how you are handling pending directions.
The issue occurs when you turn twice in rapid succession, which causes two pending directions to be added for the same block. If these aren't handled in the correct order, then the blocks may move in the wrong direction. On every update, only one pending direction for each block is needed, so I redesigned how this is handled to avoid multiple directions on one block during a single update.
Here is the link to it: http://jsbin.com/EkOSOre/5/edit
Notice, when a change in direction is made, the pending direction on the first block is updated, overwriting any existing pending direction.
if (valid) {
blockList[0].pendingDirection = direction;
}
Then, when an update occurs, the list of blocks is looped through, and the pending direction of the next block is set to be the current direction of the current block.
if(!!nextBlock) {
nextBlock.pendingDirection = block.direction;
}
If the current block has a pending direction, set the direction to the pending direction.
if(block.pendingDirection !== null) {
block.direction = block.pendingDirection;
}
Then update the block locations like normal.
You also had various other issues, such as using a variable (b) before it was initialized, and how you caught the null/undefined error (you should just do a check for that situation and handle it appropriately), but this was the main issue with your algorithm.
You'll also want to remove the old blocks when the user hits 'n', because the old one is left, increasing the speed and number of total blocks present.
Good luck with the rest of the game, and good luck learning JavaScript.

JavaScript Input Based Background Change?

My function used to work, but now it won't. I'm trying to add an if statement for when the input is left blank, it returns to the default background color.
var path = /^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/g;
function col(obj) {
var val = obj.value;
if (path.test(val)) {
document.body.style.backgroundColor = '#' + val;
}
}
window.onload = function () {
document.getElementById('bgcol').onkeyup = function () {
col(this);
}
if (getElementById('bgcol'.value = null || ""){
document.body.style.backgroundColor = '#000000';
}
}
//end javascript, begin html below
<input id="bgcol" placeholder="enter hexadecimal color"></input>
You need document.getElementById and to clean up your syntax:
if ( document.getElementById('bgcol').value == null || document.getElementById('bgcol').value == "")
Working Fiddle
if (getElementById('bgcol').value == "") {
and
document.getElementById('bgcol').onkeyup = function () {
if (this.value == ""){
document.body.style.backgroundColor = '#000000';
}
else {
col(this);
}
}
and
<input id="bgcol" placeholder="enter hexadecimal color" />
Try this simplified version of your code:
window.onload = function() {
document.getElementById('bgcol').onkeyup = function() {
var col = this.value;
if( !col.match(/^#?(?:[0-9a-f]{3}){1,2}$/i)) col = "#000000";
if( col.charAt(0) != "#") col = "#"+col;
document.body.style.backgroundColor = col;
};
};
It uses a simpler regex and also allows the # to be accepted and optional.

Categories

Resources