How to make several buttons with call functions all work - javascript

I'm trying to have multiple buttons which each have an individual call function, but either all the buttons do the same thing or none of them work at all.
So this is my first button:
<button id="study" onclick="call();">Study</button>
And this is its script:
var callCount = 0;
function one() {
changeImage1('Call one');
{
var img = document.getElementById("image");
img.src="images/tumblr_dash.gif";
document.getElementById("action").innerHTML = "You have decided to study";
}
}
function two() {
changeImage2('Call two');
{
var img = document.getElementById("image");
img.src="images/tumblr_dash.gif";
document.getElementById("action").innerHTML = "You have decided to start studying in a minute";
}
}
function three() {
changeImage3('Call three');
{
var img = document.getElementById("image");
img.src="images/study.gif";
document.getElementById("action").innerHTML = "You are currently studying";
}
}
function call(){
callCount++;
var btn = document.getElementById('study');
if(callCount == 1) one();
else if(callCount == 2) two();
else if(callCount == 3) three();
else btn.disabled = true;
//callOne = false /*!callOne;*/
}
And that works fine. But when I put in my second button:
<button id="eat" onclick="call1();">Eat</button>
Which has this script:
var callCount1 = 0;
function one1() {
changeImage1('Call one');
{
var img = document.getElementById("image");
img.src="images/tumblr_dash.gif";
document.getElementById("action").innerHTML = "You have decided to study";
}
}
function two1() {
changeImage2('Call two');
{
var img = document.getElementById("image");
img.src="images/tumblr_dash.gif";
document.getElementById("action").innerHTML = "You have decided to start eating in a minute";
}
}
function three1() {
changeImage3('Call three');
{
var img = document.getElementById("image");
img.src="images/eat.gif";
document.getElementById("action").innerHTML = "You are currently eating";
}
}
function call1(){
callCount1++;
var btn = document.getElementById('eat');
if(callCount1 == 1) one();
else if(callCount1 == 2) two();
else if(callCount1 == 3) three();
else btn.disabled = true;
//callOne = false /*!callOne;*/
}
It performs the same functions as the first button, instead of doing what I'm asking it to. I've tried changing the numbers of the ChangeImage function but it does nothingHow do I fix this?

Function call1() calls one() two() and three() instead of one1() two1() and three1(). That may be the problem.

Related

changing a Javascript image on event listener click

i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%
cannot see why my code is not working
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
CSS
#sunset{
width:25%
}
The first if statement doesn't check if the first_click var is true (assuming that is what you intend to do). Since it is empty it would return false and the else statement would run, keeping your image at 25%.
try this:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click == true) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
Have you tried adding height to your container ? This should work
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
first_click = false;
}
else {
content.style.width = "25%";
}
});
#sunset{
width:25%;
background: #000;
height: 200px;
}
<div id="sunset"></div>
The problem is that you're not toggling the first_click variable to true or false when the image is clicked. The code below fixes this by setting first_click = !first_click:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function() {
if (first_click) {
content.style.width = "100%";
} else {
content.style.width = "25%";
}
first_click = !first_click;
});
#sunset {
width: 25%
}
<img id="sunset" src="https://dummyimage.com/150/f8f">

How do I restart my timer and refresh my vital stats without refreshing the window?

I'm trying this in vanilla javascript. I have a little virtual pet who randomly loses life stats every second. When these get to zero, the screen changes. My restart button takes me back to the screen I want but my timer isn't running after hitting restart so the stats don't go down.
I feel my problem is with my timePassed() and restart() functions (to the bottom of the code) but I'm getting myself in a tangle now. Also don't want to just have the restart button refresh the window as its hosted in codepen and its not allowed.
I'm really stuck. Can you help?
//set up levels to a start at a maximum of 4
var hunger=4;
var happiness=4;
var health=4;
//create a random number 1-3
function answer(){
return Math.floor(Math.random() * 3)+1;
}
//time count starts at 0
var i=0;
//every minute take away 1 randomly from x, y or z
function decrease(){
if (answer() === 1){
hunger--;
}else if (answer()===2){
health--;
}else if(answer()===3){
happiness--;
}};
//show gameplay board
function showX(){
var x = document.getElementById("game");
x.style.display = "block";
}
function hideScreen() {
var y = document.getElementById("game");
y.style.display = "none";
}
function hideX() {
var z = document.getElementById("dead");
z.style.display = "none";
}
function changeStar() {
var star = document.getElementById('star');
if (happiness===4) {
star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png";
}
else if (happiness===3){
star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s2.png";
}else if (happiness===2){
star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s3.png";
}else if (happiness===1){
star.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s4.png";
}
}
function changeDonut() {
var donut = document.getElementById('donut');
if (hunger===4) {
donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png";
}
else if (hunger===3){
donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h2.png";
}else if (hunger===2){
donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h3.png";
}else if (hunger===1){
donut.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h4.png";
}
}
function changeHeart() {
var heart = document.getElementById('heart');
if (health===4) {
heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png";
} else if (health===3){
heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l2.png";
}else if (health===2){
heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l3.png";
}else if (health===1){
heart.src = "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l4.png";
}
}
function x(){
document.getElementById('dead').innerHTML = '<span class="deadline">Oh, no! You killed Benny! You survived for ' + i + ' seconds. Can you do better next time?</span>';
}
//when clicking on pill, food , game or drink, make a sou
//on dying, make a sound.
//have a restart button on the death screen
document.getElementById("food").onclick= function feed(){
if (hunger<4){
hunger++;
}
}
document.getElementById("drink").onclick= function drink(){
if (hunger<4){
hunger++;
}
}
document.getElementById("pill1").onclick= function heal(){
if (health<4){
health++;
}
}
document.getElementById("games").onclick= function play(){
if (happiness<4){
happiness++;
}
}
var munchAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562342736/sounds/zapsplat_human_eat_biscuit_mouth_closed_28532.mp3');
var slurpAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562342736/sounds/zapsplat_human_drink_from_glass_slurp_single_21665.mp3');
var laughAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562343433/sounds/zapsplat_human_male_middle_aged_laugh_slightly_sinister_003_32379.mp3');
var pillAudio = new Audio('https://res.cloudinary.com/dytmcam8b/video/upload/v1562343433/sounds/noisecreations_SFX-NCFREE02_Synth-Swell.mp3');
function myAudioFunction(verb) {
if(verb === 'munch') {
munchAudio.play();
} else if(verb === 'slurp') {
slurpAudio.play();
} else if(verb === 'laugh'){
laughAudio.play();
}else if(verb === 'pill'){
pillAudio.play();
}
}
//function that uses random number to decrease vital stats and change images as the stats go down
function timePassed(){
i++;
answer();
decrease();
changeStar();
changeDonut();
changeHeart();
// once stats hit 0, stop timer and hide Benny to show death message
if (hunger==0|| happiness==0|| health==0){
clearInterval(timer);
x();
hideScreen();
}
}
var timer= setInterval('timePassed()', 1000);
//restart function
function restart(){
health=4;
happiness=4;
hunger=4;
showX();
hideX();
timePassed();
}
var button = document.getElementById("restart");
button.onclick = function() {
restart();
};
Could you please try ending your reset function by calling the timer variable again?
I suspect that the setInterval is interrupted when the restart function is called and the time passes function thereby called again.

Converting a big amount of if elses to a switch/case for a smaller code

Because I have a lot of if else statements for unique id's, I would like to change the code to a switch/case. After doing some research at switches I do understand a bit of it now. Although I cannot get how I should change this function to a switch:
window.onload = function () {
function check() {
if (document.querySelector('#switch-wrapper-1 input').checked) {
document.querySelector('#switch-wrapper-1 p').textContent = "Disabled";
$('#card-1').addClass('card-disabled');
} else {
document.querySelector('#switch-wrapper-1 p').textContent = "Visible";
$('#card-1').removeClass('card-disabled');
}
if (document.querySelector('#switch-wrapper-2 input').checked) {
document.querySelector('#switch-wrapper-2 p').textContent = "Disabled";
$('#card-2').addClass('card-disabled');
} else {
document.querySelector('#switch-wrapper-2 p').textContent = "Visible";
$('#card-2').removeClass('card-disabled');
}
if (document.querySelector('#switch-wrapper-3 input').checked) {
document.querySelector('#switch-wrapper-3 p').textContent = "Disabled";
$('#card-3').addClass('card-disabled');
} else {
document.querySelector('#switch-wrapper-3 p').textContent = "Visible";
$('#card-3').removeClass('card-disabled');
}
}
document.getElementById('input-1').onchange = check;
document.getElementById('input-2').onchange = check;
document.getElementById('input-3').onchange = check;
check();
}
I will try to show my imagination on how to sort of do this so you will understand better what I want:
window.onload = function (){
function check(){
var switchWrapper = document.querySelector('.switch-wrapper input').checked; // Overall class for all inputs
switch(scenario){
case 0:
document.getElementById("switch-wrapper-1 input").textContent = "Disabled";
break;
case 1:
document.getElementById("switch-wrapper-2 input").textContent = "Disabled";
break;
case 2:
document.getElementById("switch-wrapper-3 input").textContent = "Disabled";
break;
default:
document.getElementsByClassname("switch-wrapper input").textContent = "Enabled";
}
}
document.getElementById('switch-wrapper-1 input').onchange = check;
document.getElementById('switch-wrapper-2 input').onchange = check;
document.getElementById('switch-wrapper-3 input').onchange = check;
check();
}
This is definitely not how it should work, but if someone could correct it or make something that works it would be great
I made a fiddle here https://jsfiddle.net/4heoz0nd/
Look at this fiddle fiddle
you need no jQuery.
only this lttle script before the closing body tag:
Array.from(document.querySelectorAll('[id^="switch-wrapper-"] input[type=checkbox]')).forEach(function(elem){
elem.onchange=function(){
this.parentNode.querySelector('p').innerHTML = (this.checked) ? 'Disabled' : "Visible";
//when you have mor than 9 cards take the number with an regex..
var newSel = '#card-'+ this.id[6];
document.querySelector(newSel).classList.toggle('card-disabled');
}
});

How can i make a HTML button run three functions one after another

My code has three functions. I want one button to run function one when pressed the first time then function 2 when pressed the second time function 3 when pressed the third time and then for it to reset.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green]
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
</script>
</head>
<body>
<button id="sequence" onclick="changeyellow" onclick="changered" onclick="changegreen">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>
You can use only one function and a global variable that contains the current color like this :
<!DOCTYPE html>
<html>
<head>
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green];
var currentColor = 0;
function changeColor() {
var img = document.getElementById("light");
img.src= lights[currentColor];
if (currentColor === (lights.length - 1)) {
currentColor = 0;
} else {
currentColor++;
}
return false;
}
</script>
</head>
<body>
<button id="sequence" onclick="changeColor();">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>
There are several ways you could handle it, but here's an easy one:
above:
function changered()
add this:
var cur_button = 1
Then change your button to this:
<button id="sequence" onclick="handle_click()">sequence</button>
and add this function:
function handle_click()
{
if(cur_button == 1)
{
cur_button = 2
changered()
}
else if(cur_button == 2)
{
cur_button = 3
changeyellow()
}
else if(cur_button == 3)
{
cur_button = 1
changegreen()
}
}
There you go
<input type="button" name="btnn" onclick="runFunction()" />
<script>
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png";
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png";
var green = "https://s29.postimg.org/5ljr1ha3r/green.png";
var lights =[red,yellow,green];
var a =1;
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
function runFunction()
{
if(a==1)
{
changered();
a++;
}
if(a==2)
{
changeyellow();
a++;
}
if(a==3)
{
changegreen();
a=1;
}
}
I can use the switch statement, and simply reference the lights array to determine which to display next. Seems pretty painless.
var red = "https://snowmonkey.000webhostapp.com/images/red.png"
var yellow = "https://snowmonkey.000webhostapp.com/images/yellow.png"
var green = "https://snowmonkey.000webhostapp.com/images/green.png"
var lights =[red,yellow,green]
handleClick = function(){
var light = document.getElementById("light");
switch (light.src) {
case lights[0]:
light.src = lights[1];
break;
case lights[1]:
light.src = lights[2];
break;
case lights[2]:
light.src = lights[0];
break;
}
}
#light {
float: right;
width: 50px;
}
<button id="sequence" onclick="handleClick();">sequence</button>
<br><br><br>
<img id="light" src="https://snowmonkey.000webhostapp.com/images/green.png" />
https://jsfiddle.net/x1rqwzvy/1/
You shouldn't add more than one onclick in your html code. If you do the handlers will activate simultaneously. This means you have to handle the change with JavaScript.
To determine the light you would simply increment a value in the following example:
function lightChange() {
lightChange.incrementer = lightChange.incrementer || 1;
switch (lightChange.incrementer) {
case 1:
changered();
break;
case 2:
changeyellow();
break;
case 3:
changegreen();
lightChange.incrementer = 0;
break;
}
lightChange.incrementer++;
function changered() {
var img = document.getElementById("light");
img.src = lights[0];
return false;
}
function changeyellow() {
var img = document.getElementById("light");
img.src = lights[1];
return false;
}
function changegreen() {
var img = document.getElementById("light");
img.src = lights[2];
return false;
}
}
then just change the onclick handler to lightChange instead of trying to add three consecutive handlers.
<button id="sequence" onclick="lightChange()">sequence</button>
how about
var counter = 0;
function changeColor(){
counter++;
var img = document.getElementById("light");
img.src= lights[counter % 3];
return false;
}
and your html should be:
<button id="sequence" onclick="changeColor()">sequence</button>
You can create a function array and then remove entries from it once done.
var functionArray = [changered,changeyellow,changegreen]
function sequenceClick(){
functionArray[0]();
functionArray.shift();
}
Complete Code:
var red = "https://s23.postimg.org/bo5a8hzsr/red_jpg.png"
var yellow = "https://s24.postimg.org/dodxgn305/yellow.png"
var green = "https://s29.postimg.org/5ljr1ha3r/green.png"
var lights =[red,yellow,green]
function changered()
{
var img = document.getElementById("light");
img.src= lights[0];
return false;
}
function changeyellow()
{
var img = document.getElementById("light");
img.src= lights[1];
return false;
}
function changegreen()
{
var img = document.getElementById("light");
img.src= lights[2];
return false;
}
var functionArray = [changered,changeyellow,changegreen]
function sequenceClick(){
functionArray[0]();
functionArray.shift();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="sequence" onclick="sequenceClick()">sequence</button>
<br><br><br>
<img id="light" src="https://s29.postimg.org/5ljr1ha3r/green.png" />
</body>
</html>

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

Categories