Why does JavaScript sometimes function not work when button is clicked? - javascript

I have a JavaScript voting system that has three buttons:
Vote Up, clear, and Vote Down
When I clicked the Vote Up button, it stays in zero. I have to press the Vote Up button several times to get it to vote up. Same with Vote down. When I pressed Clear, it does nothing.
Here is what I've done:
Assign function to Vote Up, and Vote Down and clear:
<button onclick="voteup()">
Vote Up
</button>
<button onclick="votedown()">
Vote Down
</button>
<button onclick="clear()">
Clear
</button>
Making a paragraph to display the result:
<p Id="vote">
You have 0 votes
</p>
Creating a global variable so I can access the variable on future functions:
var a = 0;
Creating the vote up functions:
function voteup() {
var b = a++;
Display the result in voteup() function:
document.getElementById('vote').innerHTML = "You have" + ' ' + b + "votes";
}
Making the second function (votedown):
function votedown(){
var b = a --;
document.getElementById('vote').innerHTML = "You have" + ' ' + b + "votes";
}
Create the function for clear:
function clear() {
document.getElementById('vote').innerHTML = "Your votes has been cleared";
}
I set the variable out of the function so voteup and votedown functions can access the a variable. I can't understand this.

var a = 0;
function voteup() {
a++;
document.getElementById('vote').innerHTML = "You have " + a + " votes";
}
function votedown() {
a--;
document.getElementById('vote').innerHTML = "You have " + a + " votes";
}
function clearVotes() {
document.getElementById('vote').innerHTML = "You have 0 votes";
var div = document.createElement("div");
div.innerText = "Your votes has been cleared."
div.style.color = "red";
div.style.transition = "opacity 0.25s ease-out"
document.body.appendChild(div)
setTimeout(function() {
div.style.opacity = "0";
setTimeout(function() {
div.remove()
}, 1000)
}, 3000)
a = 0
}
<button onclick="voteup()">
Vote Up
</button>
<button onclick="votedown()">
Vote Down
</button>
<button onclick="clearVotes()">
Clear
</button>
<p id="vote">
You have 0 votes
</p>
Also, you forgot a dot between document and getElementById in one of them.

Your code should be:
PS: it seems that clear is a reserved word that we cannot use as a function name
var a = 0;
const pVote = document.getElementById('vote');
function voteup() {
pVote.textContent = "You have " + ++a + " votes";
}
function votedown(){
pVote.textContent = "You have " + --a + " votes";
}
function doClear() {
a = 0
pVote.textContent = "Your votes has been cleared";
}
<button onclick="voteup()"> Vote Up </button>
<button onclick="votedown()"> Vote Down </button>
<button onclick="doClear()"> Clear </button>
<p id="vote"> You have 0 votes </p>
my way...
const p_vote = document.getElementById('vote')
, btVote = document.getElementById('bt-vote')
var voteCount = 0
btVote.onclick = e =>
{
if (!e.target.matches('button[data-op]')) return
voteCount = eval(`${voteCount} ${e.target.dataset.op}`)
p_vote.textContent = voteCount ? `You have ${voteCount} votes` : 'Your votes has been cleared'
}
#VoteBtns button { width : 10em; }
<div id="bt-vote">
<button data-op="+ 1" > Vote Up </button>
<button data-op="- 1" > Vote Down </button>
<button data-op="* 0" > Clear </button>
</div>
<p Id="vote" > You have 0 votes </p>

When using a-- the value of a is returned before the subtraction operation is executed. Thus, b is set only to the current value of a.
If you’d like this subtraction operation to occur prior to when the value is returned into b, use the decrement operator as a prefix (--a) instead.
The difference in prefix vs postfix of the decrement shorthand operator is clearly documented on its MDN page.

Related

How to toggle "View replies" button into "Hide replies" on click?

I used bootstrap button("View x replies") to toggle the visibility of the replies in the comments.It works fine to toggle the content.But I want that if someone click on "View x replies" button the content of the button will be changed into "Hide x replies".After that when user will on "Hide replies" it will change into "View replies" as like as first it is.I used javascript to achieve this.
Here is my code:
<button class="btn btn-primary d-block" id ="show-{{comment.id}}" type="button"
data-toggle="collapse" data-target="#{{comment.id}}"
aria-expanded="false" aria-controls="collapseExample"
onClick = "myFunction1({{ comment.id }}, {{ comment.get_children.count }} );">
View {{ comment.get_children.count }} replies
</button>
<script>
function myFunction1(comment_id, comment_get_children_count) {
var id = comment_id;
var count = comment_get_children_count;
var x = document.getElementById("show-" + id );
var y = "View " + count + " replies";
var z = "Hide " + count + " replies";
if (x.innerHTML = y){
x.innerHTML = z;
}
// else part is not working
else {
x.innerHTML = y;
}
}
</script>
It works fine when I click "View x replies" it changes into "Hide x replies".But next when I click on "Hide x replies", it is not changing into "View x replies" what I want.
So how can I solve this problem? Any suggetion?
Thanks in advance.
You are not checking the condition properly in your IF statement.
= is assignment operator VS == comparison operator
= is an assignment operator and to check whether to change innerHTML. You need to use != (Inequality operator) this to change the innerHTML of your button.
MDN Operators
Live Demo:
function myFunction1(comment_id, comment_get_children_count) {
var id = comment_id;
var count = comment_get_children_count;
var x = document.getElementById("show-" + id);
var y = "View " + count + " replies";
var z = "Hide " + count + " replies";
if (x.innerHTML.trim() != z) {
x.innerHTML = z;
} else {
x.innerHTML = y;
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<button class="btn btn-primary d-block" id="show-12" type="button" data-toggle="collapse" data-target="#12" aria-expanded="false" aria-controls="collapseExample" onClick="myFunction1(12, 12 );">
View 12 replies
</button>

Button response issues for a Simon Says game

Ive been developing a Simon says game recently that adds to the score if you click the correct button which there are 3,
1) green 1
2) red 2
3) trick
I've noticed that when I run the game and click the appropriate buttons only one will add to the score whilst the other two subtract from it (Regardless of what the statement says). Im unsure why this is the case and was wondering if anyone had any insights). My thought is that the if functions don't seem to correlate to the new statement that is generated.
Any suggestions are appreciated,
var answers = [
"Simon says click red !",
"Simon says click green !",
"Simon says click 1 !",
"Simon says click 2 !",
"Click green",
"Click red",
"Click 1",
"Click 2!"
];
var score = 0;
var total = document.getElementById("score");
var statement = document.getElementById("instruct");
var randomStatement = answers[Math.floor(Math.random() * answers.length)];
function refresh(){
var randomStatement = answers[Math.floor(Math.random() * answers.length)];
statement.innerHTML = randomStatement;
}
function pressTrick(){
if(randomStatement === "Click green" || randomStatement === "Click red" || randomStatement === "Click 1" || randomStatement === "Click2!"){
score++;
total.style.color = "green";
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
} else {
total.style.color = "red";
score--;
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
}
}
function pressRed(){
if(randomStatement === "Simon says click red !" || randomStatement === "Simon says click 2 !"){
score++;
total.style.color = "green";
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
} else {
total.style.color = "red";
score--;
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
}}
function pressGreen(){
if(randomStatement === "Simon says click 1 !" || randomStatement === "Simon says click green !"){
score++;
total.style.color = "green";
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
} else {
total.style.color = "red";
score--;
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
}}
function start(){
var i = 60;
var count = setInterval(timer,1000);
refresh();
function timer() {
var display = document.getElementById("timer");
var finished = document.getElementById("heading");
if(i < 1){
clearInterval(count);
finished.innerHTML = "Game Over! Your final Score is : " + score;
display.style.color = "red";
display.style.fontWeight = "bold";
document.body.style.backgroundColor = "black";
} else if(i <= 10) {
i--;
display.style.color = " red";
display.style.fontWeight = "bold";
display.innerHTML = i + " Seconds Left";
} else {
i--;
display.style.color = "green";
display.style.fontWeight = "bold";
display.innerHTML = i + " Seconds Left";
}}}
<html>
<head>
<title> Simon Says! </title>
<link rel = "stylesheet" href = "simonsays.css"/>
</head>
<body>
</br>
<h1> Test Your Reflexes! </h1>
<div id = "heading"; class = "h2"> Click on Simon to Begin! </div>
</br>
<img src = "boy.jpg" onclick = "start()"; onclick = "timer()"; onclick = "returnStatement";/>
</br>
<div id = "instruct" class="statement"></div>
</br>
<div class = "align">
<input type = "button" class = "button2" id = "button2" value = "1" onclick = "pressGreen()"; ></input>
<input type = "button" class = "button" id = "button" value = "2" onclick = "pressRed()"; ></input>
<input type = "button" class = "button3" id = "button3 " value = "Trick" onclick = "pressTrick()";></input>
</div>
</br>
<div id = "score" class = "score"><b> Score: </b></div>
<div id = "timer" class = "timer"><b> Time left: </b></div>
<script src = "simonsays.js"></script>
</body>
</html>
Thank you!
There's just one word too much: var. In
function refresh(){
var randomStatement = answers[Math.floor(Math.random() * answers.length)];
statement.innerHTML = randomStatement;
}
the var causes a new, local variable randomStatement to be defined, and the global randomStatement remains unchanged, so all comparisons in the rest of the program use the initial rather than the refreshed value of randomStatement. Drop the var here, and it works as expected.

How to update and save the variable after it has been changed?

I want to update the value of the counting variable after the words have been clicked, so they can be sorted from the highest clicked value from an array.
The variable value doesn't carry over to the next button.
I made the two variables as global variables in order to use it in other functions, but it doesn't seem to work and I also want the submit button to get updates after the user clicks the words after they have submitted once.
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed=0 ;
var countArbitrated=0;
var mostChosen = [
{word:"addressed:", selectedTimes:countAddressed},
{word:"arbitrated:", selectedTimes:countArbitrated}];
//set every buttons for action words
function addressed() {
countAddressed += 1;
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
//count how many individual action words there are.
document.getElementById("demo1").innerHTML ="arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen.sort(function(a, b){return b.selectedTimes - a. selectedTimes});
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
----I want this :
Communication
addressed(button) , arbitrated (button),
addressed: 3
arbitrated: 5
Sort(button)
addressed: 5
arbitrated: 3
----but I am getting this:
Communication
addressed , arbitrated ,
addressed: 3
arbitrated: 5
Sort
addressed: 0
arbitrated: 0
As I have mentioned in the comment, you are not updating mostChosen array when buttons are clicked.
// Update addressed count in addressed() function
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
// Similar update is done in arbitrated() function
Here is the running code (your code, modified slightly) that modifies the array mostChosen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prescriptions</title>
</head>
<body>
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed = 0;
var countArbitrated = 0;
var mostChosen = [
{ word: "addressed:", selectedTimes: countAddressed },
{ word: "arbitrated:", selectedTimes: countArbitrated }];
//set every buttons for action words
function addressed() {
countAddressed += 1;
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
mostChosen.forEach(token => {
if (token.word == 'arbitrated:') {
token.selectedTimes = countArbitrated;
}
});
//count how many individual action words there are.
document.getElementById("demo1").innerHTML = "arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen = mostChosen.sort(function (a, b) { return b.selectedTimes - a.selectedTimes });
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
</script>
</body>

Javascript calculator-emptying the field before typing input

I am trying to build a calculator using JavaScript
var btn5 = document.getElementById('btn5');
var btn2 = document.getElementById('btn2');
var btn5multiply = document.getElementById('btn5multiply');
var result = document.getElementById('result');
var calInput = document.getElementById('calInput');
var backSpace = document.getElementById('backSpace');
var C = document.getElementById('C');
var blank = "Please enter a number";
btn5.addEventListener('click', runFunction5);
btn2.addEventListener('click', runFunction2);
multiply.addEventListener('click', multiplyFunction);
result.addEventListener('click', resultFunction);
backSpace.addEventListener('click', backSpaceFunction);
C.addEventListener('click', clearFunction);
function runFunction5() {
if(calInput.value == blank) {
calInput.value = "";
calInput.value += btn5.value;
} else {
calInput.value += btn5.value;
}
}
function runFunction2() {
calInput.value += btn2.value;
}
function multiplyFunction() {
calInput.value += multiply.value;
}
function resultFunction() {
if(calInput.value == "") {
calInput.value = blank;
} else {
var storeVal = calInput.value;
var cal = eval(storeVal);
calInput.value = cal;
}
}
function backSpaceFunction() {
var storeVal = calInput.value;
calInput.value = storeVal.substr(0, storeVal.length - 1);
}
function clearFunction() {
calInput.value = "";
}
<body>
<input id="calInput" type="text" disabled="true" value=""><br><br>
<button id="backSpace"><-</button>
<button id="btn5" value="5">5</button>
<button id="btn2" value="2">2</button>
<button id="multiply" value="*">X</button>
<button id="result">=</button>
<button id="C">C</button>
</body>
. In my code if someone presses the =key, it displays the message that says Please enter a number. Now I figured out the way to clear the field first when pressing the number key after pressing =key and appending every key pressed afterwards to the input field but there is too much typing of code as I have to assigned that condition to every numeric key, so is there a better way to achieve that ? Right now I have added that condition to only when 5 is pressed.
All you need to do is assign a common function to each of the buttons for their click event and within that handler, you can determine which button was actually clicked using the event.target.
Now, there's no need for an input field here at all. You aren't getting any input directly from it, you are actually using it as an output mechanism. Since you want it placed on its own line, a regular div is the better UI choice.
Next, instead of getting the value of your buttons, just work with the text that is the content of the buttons via the .textContent property of the element. This will make the HTML much simpler as well.
Now, you have eval() in your code as a way of taking the string you've built up and running it as an expression. eval() should be avoided all the time. There is hardly a use-case that requires it. It opens up security and performance problems in an application. This is a topic of some debate, but in my opinion, anyone that advocates for it is under-informed about eval() or JavaScript. It will take a little more code, but you can do the math without it.
This example answers your question and demonstrates my suggestions. I've even extended your scenario to include all the basic math operators, but there is still more that would need to be flushed on on this before it was ready for production deployment.
// Get both number buttons in an array:
var btns = Array.prototype.slice.call(document.querySelectorAll(".number"));
// Get all operator buttons in an array:
var operators = Array.prototype.slice.call(document.querySelectorAll(".operator"));
var operator = null; // Will store the last operator pressed
var result = document.getElementById('result');
var output = document.getElementById('output');
var back = document.getElementById('backspace');
var clear = document.getElementById('clear');
var blank = "Please enter a number";
// Loop over the buttons in the numbers array
btns.forEach(function(btn){
// Assign an event handler to the button
btn.addEventListener("click", btnFunction);
});
// Loop over the buttons in the operators array
operators.forEach(function(op){
// Assign an event handler to the button
op.addEventListener("click", function (evt) {
operator = evt.target.textContent; // Get the operator and store it
output.textContent += operator; // Display the operator in the expression
});
});
// Set up event handlers:
result.addEventListener("click", doMath);
clear.addEventListener("click", function() { output.textContent = ""; });
back.addEventListener("click", function(){
output.textContent = output.textContent.substring(0, output.textContent.length - 1);
});
// All event handling functions are automatically passed
// a reference to the event that triggered the function
function btnFunction(evt) {
// And that event object exposes the actual DOM object
// that triggered the event via the target property
if(output.textContent == blank) {
output.textContent = evt.target.textContent;
} else {
output.textContent += evt.target.textContent;
}
}
function doMath() {
// Check for no math to do yet
if(output.textContent === ""){
output.textContent = blank;
}
// Break up the expression into an array with the operands serving to delimit the parts
var operands = output.textContent.split(/[+-/*]/);
// Do the math:
switch (operator){
case "+" :
// Operands is an array, so we want to do the math with the two items in the array which
// we get by passing indexes of 0 and 1 to the array.
output.textContent += " = " + (parseInt(operands[0], 10) + parseInt(parseInt(operands[1], 10)));
break;
case "-" :
output.textContent += " = " + (parseInt(operands[0], 10) - parseInt(parseInt(operands[1], 10)));
break;
case "*" :
output.textContent += " = " + parseInt(operands[0], 10) * parseInt(parseInt(operands[1], 10));
break;
case "/" :
output.textContent += " = " + parseInt(operands[0], 10) / parseInt(parseInt(operands[1], 10));
break;
}
}
#output { height:1em; padding:3px; }
<body>
<!-- No need for an input element here. -->
<div id="output"></div>
<button id="backspace">←</button>
<button class="number">5</button>
<button class="number">2</button>
<button class="operator">+</button>
<button class="operator">-</button>
<button class="operator">*</button>
<button class="operator">/</button>
<button id="result">=</button>
<button id="clear">C</button>
</body>
You could determine the value of the currently clicked button, like this:
function numberClickHandler() {
calInput.value += this.value;
}
Now we only need to assign this to all buttons, e.g.:
["btn2", "btn3"].forEach(id =>
document
.getElementById(id)
.onclick = numberClickHandler
);
A little modification in the HTML will solve your issue. I suggest you add a placeholder attribute in the input. Placeholder will disappear once there is a value in input and will reappear when there is none.
More about placeholder: https://www.w3schools.com/tags/att_input_placeholder.asp
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/2194/
HTML:
<input id="calInput" type="text" disabled="true" value="" placeholder="Please enter a number">
<br>
<br>
<button id="backSpace">>
</button>
<button id="btn5" value="5">5</button>
<button id="btn2" value="2">2</button>
<button id="multiply" value="*">X</button>
<button id="result">=</button>
<button id="C">C</button>
JS:
var btn5 = document.getElementById('btn5');
var btn2 = document.getElementById('btn2');
var btn5multiply = document.getElementById('btn5multiply');
var result = document.getElementById('result');
var calInput = document.getElementById('calInput');
var backSpace = document.getElementById('backSpace');
var C = document.getElementById('C');
var blank = "Please enter a number";
btn5.addEventListener('click', runFunction5);
btn2.addEventListener('click', runFunction2);
multiply.addEventListener('click', multiplyFunction);
result.addEventListener('click', resultFunction);
backSpace.addEventListener('click', backSpaceFunction);
C.addEventListener('click', clearFunction);
function runFunction5() {
calInput.value += btn5.value;
}
function runFunction2() {
calInput.value += btn2.value;
}
function multiplyFunction() {
calInput.value += multiply.value;
}
function resultFunction() {
var storeVal = calInput.value;
var cal = eval(storeVal);
calInput.value = cal;
}
function backSpaceFunction() {
var storeVal = calInput.value;
calInput.value = storeVal.substr(0, storeVal.length - 1);
}
function clearFunction() {
calInput.value = "";
}
Once, you do that you will not have to add that condition in each case.
var numericValues = document.getElementById('numericValue');
var result = document.getElementById('result');
var calInput = document.getElementById('calInput');
var backSpace = document.getElementById('backSpace');
var C = document.getElementById('C');
var blank = "Please enter a number";
numericValues.addEventListener('click', pushNumericValue);
multiply.addEventListener('click', multiplyFunction);
result.addEventListener('click', resultFunction);
backSpace.addEventListener('click', backSpaceFunction);
C.addEventListener('click', clearFunction);
function pushNumericValue(event) {
var btnTarget = event.target
if(calInput.value == blank) {
calInput.value = "";
calInput.value += btnTarget.value;
} else {
calInput.value += btnTarget.value;
}
}
function multiplyFunction() {
calInput.value += multiply.value;
}
function resultFunction() {
if(calInput.value == "") {
calInput.value = blank;
} else {
var storeVal = calInput.value;
var cal = eval(storeVal);
calInput.value = cal;
}
}
function backSpaceFunction() {
var storeVal = calInput.value;
calInput.value = storeVal.substr(0, storeVal.length - 1);
}
function clearFunction() {
calInput.value = "";
}
<body>
<input id="calInput" type="text" disabled="true" value=""><br><br>
<button id="backSpace"><-</button>
<div id="numericValue">
<button id="btn5" value="1">1</button>
<button id="btn5" value="2">2</button>
<button id="btn5" value="3">3</button>
<button id="btn2" value="4">4</button>
</div>
<button id="multiply" value="*">X</button>
<button id="result">=</button>
<button id="C">C</button>
</body>
One way to do it
Is using event delegation instead of listening all numeric values and doing an specific action. Define a parent div that have as children all numeric values and listen to it thanks to the event.target attribute you can get its value of the clicked button

setTimeout callback function not working

I am calling a function using onClick inside button. The called function is inside an object and it is getting called each second using setTimeout. But callback function is not getting called by setTimeout and works for just first call.
if i do not use object and use a encapsulating function that returns startPomadoro function, then its working.
###HTML Code ##########
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
### JS COde
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText:'',
startPomodoro: function(){
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if(this.countPomadoro<pomadoroTimeInMinutes){
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
this.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
this.countPomadoro++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
if(this.countBreak<breakInMnutes){
var minutesLeftBreak = this.breakInMinutes - this.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
this.countBreak++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
this.currentTimerText=" Break Time is UP. ";
this.displayPomadoro();
}
}
},
displayPomadoro: function(){
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent=this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
You had a problem with this not being what you think, when function was called from setTimeout. Try something like this:
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText: '',
startPomodoro: function() {
var that = this;
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if (this.countPomadoro < pomadoroTimeInMinutes) {
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
that.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
that.countPomadoro++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
if (that.countBreak < breakInMinutes) {
var minutesLeftBreak = that.breakInMinutes - that.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
that.countBreak++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
that.currentTimerText = " Break Time is UP. ";
that.displayPomadoro();
}
}
},
displayPomadoro: function() {
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent = this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
PS. You also had a typo breakInMnutes instead of breakInMinutes.
I have solved this problem by moving away from jquery , and simply
setting event handler on divs by wrapping each image inside one div using
JavaScript. Below is the sample code.
//code
handler.divs.forEach(function(div){
var img = document.getElementById(div);
img.onclick = function(){
var id = parseInt(img.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" div clicked " + id + " u p " + userPattern);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" if ");
handleWrongInput();
} else if(userPattern.length === simonGame.PATTERN.length){
setTimeout(function(){simonGame.patternGen({result:"success"})},1200);
}
}
});
console.log(" up " + userPattern + " SGP " + simonGame.PATTERN);

Categories