SImon Says Javascript - javascript

So I want to make a simon says game with a functionality like this.
I have the following code :
HTML
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
<div id="yellow"></div>
<div id="count"></div>
<div id="buttons">
<button id="1" type="button" class="btn btn-default"onclick="add_sequence()">Simple </button>
<button id="2" type="button" class="btn btn-default">Strict </button>
<button id="3" type="button" class="btn btn-default">Restart</button>
</div>
JAVASCRIPT
var sequence = ["#red", "#blue", "#yellow", "#green","#red"]; //etc.
var human = [];
var i = 0;
function add_sequence() {
human.push(sequence[i])
animate(human);
$("" + human[i] + "").click(function() {
human.push(sequence[i])
animate(human);
i++;
}
function animate(s) {
var i = 0;
var interval = setInterval(function() {
anim(s[i]);
i++;
if (i >= s[i].length) {
clearInterval(interval);
}
}, 500);
}
function anim(id) {
$("" + id + "").delay(500)
.animate({
opacity: 1
}, 300)
.animate({
opacity: 0.5
}, 300)
}
My way of thinking is that every time I click on a button or series of buttons, (etc...), to add one element to the human array from the sequence array. In this way the next round will have an addition of one more lighting button.
BUT I can't do this with this code because the increment of the lighting buttons is done only when I click the first button(#red), not when I click the correct sequence of buttons.

Related

Multiply a variable and store that value/output to screen

I have tried a bunch of ways to get this to work. I'm not a coder, and I have a frankensteined abomination of a counter program I put together as a replacement for our expensive counters that kept breaking on us (basically you input a value at the start of the day, and based on that value a calculation is done for the GOAL for the day).
I now want to add a GOAL BY LUNCH field/display that - however simply doing something like
var lunchgoal = goal * 0.69;
And then putting it on the page like I have with the goal field, does not seem to work.
I can either get it to display 0 - which seems like its displaying just the basic 0 value of goal before it is being incremented, or NaN - not a number.
So I thought I need to convert it to a number before multiplying it, but I nothing has worked for me for that. Right now I'm guessing it may be a matter of where they are contained on the page? I find that part of this confusing honestly. Any help is much appreciated, I would have thought this would be fairly simple!
Thank you!
HTML
<html>
<style>
body {background-color: Black;}
p {color: white;}
</style>
<div class="container">
<p> SAMS VALUE: <span id="output"> </span>
</p>
<p style="font-size:110px"> GOAL: <span id="output2"> </span>
</p>
<button style="background-color:white;width:20%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:110px">Actual Count: <span id="clicks">0</span>
</p>
<div class="row">
<div class="col-sm-4"/>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"/>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"/>
</div>
</div>
</div>
</html>
Script
<script type="text/javascript">
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
}
}, SAMSINPUT * 1000);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false,
t;
</script>
You have to do it in loop where goal is changing & you want this to change as well.otherwise it just stays on 0. i shortened the timer for demo purpose
document.addEventListener("keyup", function(event) {
if (event.keyCode === 109) {
event.preventDefault();
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
});
document.addEventListener("keyup", function(event) {
if (event.keyCode === 107) {
event.preventDefault();
document.getElementById("stop").click();
}
});
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
const input = parseInt(prompt("Enter a SAMS number: "));
var SAMSINPUT = input;
// console.log(SAMSINPUT);
document.getElementById('output').innerHTML = SAMSINPUT;
var goal = 0;
var output2 = document.getElementById('output2');
//set interval for GOAL calculation
var samsInterval = setInterval(function doIncrement() {
if (clear == false) {
goal += 1;
output2.innerHTML = goal.toString();
var lunchGoalNumber = goal * 0.69;
var output3 = document.getElementById("output3")
output3.innerHTML = lunchGoalNumber;
}
}, SAMSINPUT * 25);
var timerDiv = document.getElementById('timerValue'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
clear = false;
<div class="container">
<p> SAMS VALUE: <span id="output"> </span></p>
<p style="font-size:50px"> GOAL: <span id="output2"> </span></p>
<p style="font-size:50px"> Lunch/GOAL: <span id="output3"> </span></p>
<button style="background-color:white;width:35%;height:15%;font-size: 60px" type="button" onClick="onClick()">ACTUAL</button>
<p style="font-size:50px">Actual Count: <span id="clicks">0</span></p>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div id="timeContainer" class="well well-sm">
<time id="timerValue"></time>
</div>
<div id="timerButtons">
<button id="start" class="btn btn-success" disabled="disabled">START</button>
<button id="stop" class="btn btn-danger">STOP</button>
<button id="reset" class="btn btn-default">RESET</button>
</div>
<div class="col-sm-4 col-sm-4 col-md-4"></div>
</div>
</div>
</div>
</body>

Javascript increase and decrease button to be multiple of 2, 5 and 10

My Javascript doesn't seem to work properly. My increase and decrease buttons don't work and I want to know how to make some of them to only work with multiples of 2, 5 or 10. (Example multiple of 5: I can only order 5, 10, 15.. so the increase and decrease buttons must only add accordingly.)
I have 7 products, all similar to this one, just the name, price, and image that differs.
$('.like-btn').on('click', function() {
$(this).toggleClass('is-active');
});
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value > 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value = 100;
}
$input.val(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-3.png" alt="" />
</div>
<div class="description">
<span>Super Star Destroyer</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus.svg" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus.svg" alt="" />
</button>
</div>
<div class="total-price">$4570000</div>
</div>
First, fix the syntax error:
(value & amp; lt; 100) should probably be (value < 100) and
(value & amp; gt; 1) should probably be (value >= 1).
Keep in mind for the future that if you copy a code snippet from somewhere, you should try to understand what it does (every line!) before using it.
You could use <input name="myName" type="number" step="5"> in your HTML, as one solution. This might help you solve the immediate problem in a concise manner.
Alternatively, in the lines that say value = value + 1; and value = value - 1; you could change the 1 to a 5 (or a constant called STEP_SIZE defined once at the top of the file). This strategy might help you learn more about Javascript and improve your programming skills.
Either way, good luck!

More efficient way to bind variables with buttons? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have 3 different buttons that when clicked on will increment specific variable by 1.
Instead of writing 3 different on clicks, is there more efficient way to do this?
I know i can use data attributes to bind button with correct element, but i don't know how to do that with variables.
var x1 = 0;
var x2 = 0;
var x3 = 0;
$('.btn1').on('click', function() {
x1 += 1;
$('#panel1').html(x1);
});
$('.btn2').on('click', function() {
x2 += 1;
$('#panel2').html(x2);
});
$('.btn3').on('click', function() {
x3 += 1;
$('#panel3').html(x3);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1">#btn1</button>
<button class="btn2">#btn2</button>
<button class="btn3">#btn3</button>
An approach using id's or whatever attribute and arrays:
var x = [];
x[1] = 0;
x[2] = 0;
x[3] = 0;
$('.btn').on('click', function() {
var pos = $(this).attr("id");
x[+pos] += 1;
$('#panel'+pos).html(x[pos]);
});
in HTML:
<button class="btn" id="1">#btn1</button>
<button class="btn" id="2">#btn2</button>
<button class="btn" id="3">#btn3</button>
Give them the same class and make it one click listener and put a data attr on each button with the variable name and the panel name. something like this, put all the variables in one object so you can access them also if they are global variables you can access them like this window[variableName]
As always, use a function to abstract over duplicated code.
function counter(buttonSelector, outputSelector) {
var x = 0;
$(buttonSelector).on('click', function() {
x += 1;
$(outputSelector).text(x); // btw, don't use `html`
});
}
counter('.btn1', '#panel1');
counter('.btn2', '#panel2');
counter('.btn3', '#panel3');
You can further remove repetition by putting those calls (or just the function body) in a loop, and/or adjust your selectors appropriately, but for three calls it's not yet worth it.
you can use an array instead of multi variables.
now give all buttons a specific class like btn.
then :
var ar=[0,0,0];
$('.btn').on('click',function(){
var x=$(this).html(); //if text of buttons is #btn1,#btn2 , ....
var num=parseInt(x.substr(x.length - 1));
ar[num]++;
});
Store the count in data attributes instead of a variable.
$('button[data-out]').on('click', function() { // bind on every button
// $(document).on('click, 'button[data-out]', function() { // or use event delegation with one click event
var btn = $(this) // reference the element
var cnt = (btn.data('count') || 0) + 1 // read count or default to zero and increment
btn.data('count', cnt) // update the count data attribute
$(btn.data('out')).text(cnt) // update your text output
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1" data-out="#panel1">#btn1</button>
<button class="btn2" data-out="#panel2">#btn2</button>
<button class="btn3" data-out="#panel3">#btn3</button>
I would either give your buttons a common class, or you could just bind your click event to the button element if you don't have others you need to worry about. Then use the index of the button being clicked to match it to the div you want to change. Essentially a one-liner:
$('button').on('click', function() {
$('div').eq($(this).index('button')).html(+$('div').eq($(this).index('button')).text() + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn1">#btn1</button>
<button class="btn2">#btn2</button>
<button class="btn3">#btn3</button>
Parts explained:
$(this).index('button') gets the index of the button among the button elements. See .index().
$('div').eq($(this).index('button')).text() select the div using the index above. See .eq()
+ converts the string content of the div to a number. Also could have used parseInt()
Store the variables as properties of an object.
Use a data-* attribute on each button to store what variable it is
supposed to match.
Bind all buttons to one handler.
In the handler, check the clicked button's data- attribute and
update the associated Object property as needed.
let variableObject = {
x1:0,
x2:0,
x3:0
}
$('.btn').on('click', function() {
variableObject[this.dataset.key]++;
$('#panel' + this.dataset.key.charAt(1)).text(variableObject[this.dataset.key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button class="btn" data-key="x1">#btn1</button>
<button class="btn" data-key="x2">#btn2</button>
<button class="btn" data-key="x3">#btn3</button>
Having said that, do you really need the variables in the first place? Why can't you just adjust the HTML content directly and anytime you may need that data, simply extract it.
$('.btn').on('click', function() {
// Get current value of associated panel
let current = $("#" + $(this).data("key")).text();
// Set text of associated panel to old value plus one
$("#" + $(this).data("key")).text(++current);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button class="btn" data-key="panel1">#btn1</button>
<button class="btn" data-key="panel2">#btn2</button>
<button class="btn" data-key="panel3">#btn3</button>
Here is a version that generates the initial variables too, so it should be scalable.
bindVars = {}
$('[data-bind-id]').each(function() {
var xi = "x" + $(this).data('bind-id');
var pi = "#panel" + $(this).data('bind-id');
bindVars[xi] = 0;
$(this).on('click', function() {
bindVars[xi] += 1;
$(pi).text(bindVars[xi]);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">0</div>
<div id="panel2">0</div>
<div id="panel3">0</div>
<button data-bind-id='1'>#btn1</button>
<button data-bind-id='2'>#btn2</button>
<button data-bind-id='3'>#btn3</button>
Something like this
vars = {
'x1':0,
'x2':0,
'x3':0
}
$('.btn').on('click', function(){
var vn = $(this).data('varname');
var ps = $(this).data('panel-selector');
vars[vn] += 1;
$(ps).text(vars[vn]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn" data-varname='x1' data-panel-selector='#panel1'>#btn1</button>
<button class="btn" data-varname='x2' data-panel-selector='#panel2'>#btn2</button>
<button class="btn" data-varname='x3' data-panel-selector='#panel3'>#btn3</button>
UPD:
For variables can use eval, but this not secure and useless. Do not use this, it's just for demonstration.
var x1 = 0;
var x2 = 0;
var x3 = 0;
$('.btn').on('click', function(){
var vn = $(this).data('varname');
var ps = $(this).data('panel-selector');
eval(vn + '+=1');
$(ps).text(eval(vn));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="panel1">
0
</div>
<div id="panel2">
0
</div>
<div id="panel3">
0
</div>
<button class="btn" data-varname='x1' data-panel-selector='#panel1'>#btn1</button>
<button class="btn" data-varname='x2' data-panel-selector='#panel2'>#btn2</button>
<button class="btn" data-varname='x3' data-panel-selector='#panel3'>#btn3</button>
You can add every button HTML onclick event and create one function.
function add() {
this.innerHTML(parseInt(this.innerHTML()) + 1);
}
<button onclick=add()>1</button>
<button onclick=add()>1</button>
<button onclick=add()>1</button>

Need to find out how to make a button go out

currently, I have a countdown script that counts down to 15.
<div id="skip" style="margin-top: 4px;">
<p> Please wait for <span id="timer" style="font-weight:bold;">15</span> seconds</p>
</div>
<div id="button">
<form action="http://website.com">
<input type="submit" style="display: none;" value="Go to website"/>
<script>
var count = 15;
function countDown(){
var timer = document.getElementById("timer");
if(count > 0){
count--;
timer.innerHTML = count;
setTimeout("countDown()", 1000);
}else{
document.getElementById("button");
}
}
countDown();
</script>
It does it's job and counts down to fifteen. What I actually want to happen is that when the 15 seconds is up, it will instead show a button that says "Go to website".
Basically it's like other shortener but it's not.
I don't think document.getElementByID doesnt work. I've been looking for a way to make the button appear but it's not working.
Start with the button hidden, and remove that condition when the timer expires. A common way to do that is to use a "hidden" utility class, as shown below.
Note: Count in this snippet is 3, because I get bored waiting for 15 seconds each iteration. :)
var count = 3;
function countDown(){
var timer = document.getElementById("timer");
var button;
var skipContainer;
if(count > 0){
count--;
timer.innerHTML = count;
setTimeout("countDown()", 1000);
}else{
skipContainer = document.getElementById("skip");
button = document.getElementById("button");
skipContainer.classList.add("hidden");
button.classList.remove("hidden");
}
}
countDown();
.hidden {
display: none;
}
<div id="skip" style="margin-top: 4px;">
<p> Please wait for <span id="timer" style="font-weight:bold;">15</span> seconds</p>
</div>
<div id="button" class="hidden">
<form action="http://website.com">
<input type="submit" value="Go to website"/>
</form>
</div>
You could use setInterval() function that I think is more natural for the count down process. I reuse most code from #Palpatim answer.
var count = 3;
var myVar = setInterval(function(){ countDown() }, 1000);
function countDown() {
var timer = document.getElementById("timer");
var button;
var skipContainer;
if(count > 0){
count--;
timer.innerHTML = count;
}else{
myStopFunction();
skipContainer = document.getElementById("skip");
button = document.getElementById("button");
skipContainer.classList.add("hidden");
button.classList.remove("hidden");
}
}
function myStopFunction() {
clearInterval(myVar);
}
.hidden {
display: none;
}
<div id="skip" style="margin-top: 4px;">
<p> Please wait for <span id="timer" style="font-weight:bold;">15</span> seconds</p>
</div>
<div id="button" class="hidden">
<form action="http://website.com">
<input type="submit" value="Go to website"/>
</form>
</div>

How to build a click counter with multiple click values and combine them into a total click value?

I am a newbie and I built this click counter with jquery and it is working great but it seems clunky to me and I want to make my code cleaner. So my question is how can I combine the two click functions into one function and then use the total of the two variables "click1" and "click2" as the value for the variable "sum"? I am assuming one would loop through the separate elements and add their clicks to an array and then add the values stored in the array and assign that as the total, but I am not sure where to start or if that is even possible. I am learning jquery and plain javascript so I can understand suggestions in either syntax. Thank you all!
CODEPEN: http://codepen.io/chasereckling/pen/KgArLG?editors=1010
<div class="clickButton">
<button id="updateClick1" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div class="clickButton">
<button id="updateClick2" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div>Total Clicks: <span id="sumClicks">0</span></div>
<script>
var count1 = 0;
var count2 = 0;
var sum = 0;
$('#updateClick1').click(function() {
count1++;
sum++;
$(this).siblings().children('.clickNumber').html(count1);
$('#sumClicks').html(sum);
});
$('#updateClick2').click(function() {
count2++;
sum++;
$(this).siblings().children('.clickNumber').html(count2);
$('#sumClicks').html(sum);
});
</script>
You can do something like this:
var sum = 0;
function clickHandler () {
var $target = $(this),
$span = $target.siblings("span").children(".clickNumber"),
$sum = $("#sumClicks");
$span.text(parseInt($span.text()) + 1);
sum += 1;
$sum.text(sum);
}
$('button[type="button"]').click(clickHandler);
Here is codepen:
sum of clicks
Check the following code snippet
var count=0;
var sum = 0;
var $sumElement=$('#sumClicks');
sum=parseInt($sumElement.html());
$(document).ready(function(){
$('button').click(function() {
var element=$(this);
var $clickCount=$(this).siblings().children('.clickNumber');
var clickCountVal=parseInt($clickCount.html());
clickCountVal++;
sum++;
$clickCount.html(clickCountVal);
$sumElement.html(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickButton">
<button id="updateClick1" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div class="clickButton">
<button id="updateClick2" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber">0</span></span>
</div>
<div>Total Clicks: <span id="sumClicks">0</span></div>
Hope this helps
You could try something like this, it'll be a bit cleaner:
<div class="clickButton">
<button id="updateClick1" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber1">0</span></span>
</div>
<div class="clickButton">
<button id="updateClick2" type="button">click me</button>
<span>Number of Clicks: <span class="clickNumber2">0</span></span>
</div>
<div>Total Clicks: <span id="sumClicks">0</span></div>
var count = [0,0];
$('#updateClick1').click(function() {
count[0]++;
$('.clickNumber1').html(count[0]);
$('#sumClicks').html(count[0] + count[1]);
});
$('#updateClick2').click(function() {
count[1]++;
$('.clickNumber2').html(count[1]);
$('#sumClicks').html(count[0] + count[1]);
});
JSFIDDLE: https://jsfiddle.net/s7pw5oqs/1/

Categories

Resources