How to change the argument of an onclick function dynamically - javascript

I’ve got this button here:
<button onclick="cookieClick(1)">Click Me!</button>
which gives me 1 cookie when I click on it.
function cookieClick(number){
cookies = cookies + number;
document.getElementById("cookies").innerHTML = cookies;
}
This here is the function I use to get it to work.
Now here is my problem: When I want to increase the number of cookie I would get per click I can’t figure out how to do it. This is what I think is the closest to what it should be:
function upgrade(){
if(cookies >= 100){
document.getElementById("cookieClicker(1)").innerHTML * 2 = cookieClicker();
}
}
But I’m guessing that isn’t quite right since it doesn’t work.

Try this:
<button id="cookie-clicker" type="button">Click Me!</button>
var numCookies = 0,
cookiesPerClick = 1,
clicker = document.getElementById("cookie-clicker"),
cookies = document.getElementById("cookies");
clicker.addEventListener('click', cookieClick);
function cookieClick(){
numCookies += cookiesPerClick;
cookies.textContent = numCookies;
}
function upgrade(){
cookiesPerClick *= 2;
}

Related

How do I make a countdown feature in a button in HTML5

I am creating a clicker-like game in HTML5+Javascript and for the clicking part, there is a timeout... I tried it my self but for some reason it does not work.
HTML:
function pursuit() {
var btn = document.getElementById("pursuit");
setInterval(function(){
timeOnPursuit -= 1;
}, 1000)
while(timeOnPursuit > 0){
btn.value = "In Pursuit: " + timeOnPursuit;
}
}
<div class="button">
<button id="pursuit" class="pursuit" onClick="pursuit()"> Go on a Pursuit </button>
</div>
A few things to consider here...
First, the code is producing an error in the browser console. You never defined the timeOnPursuit variable, so you aren't really controlling its scope. Simply declare that variable with an initial value (whatever value you like) before trying to use it:
var timeOnPursuit = 10;
Aside from that, your loop is going to block the thread. Because the variable is initially greater than 0, and because nothing in that loop modifies that value, it's going to run forever and never let the interval get a chance to modify the value.
Get rid of the loop entirely and rely on the interval instead. Within the interval you can update the UI. (Which, incidentally, should probably be innerText instead of value in this case.) Then within that interval you can also check when to stop the interval, which is what I suspect you were trying to do with the loop.
For a bonus, you might also want to disable the button so the user can't click it again, which would create another counter.
Overall, maybe something like this:
function pursuit() {
var btn = document.getElementById("pursuit");
// Start the "pursuit"
var timeOnPursuit = 10;
btn.innerText = "In Pursuit: " + timeOnPursuit;
btn.disabled = true;
// Repeat every second
var interval = setInterval(function(){
// Update the "pursuit"
timeOnPursuit -= 1;
btn.innerText = "In Pursuit: " + timeOnPursuit;
// Stop the interval at 0
if (timeOnPursuit <= 0) {
clearInterval(interval);
}
}, 1000)
}
<div class="button">
<button id="pursuit" class="pursuit" onClick="pursuit()"> Go on a Pursuit </button>
</div>
function pursuit() {
let timeOnPursuit = 10 // define time
var btn = document.getElementById("pursuit");
const timer = setInterval(function() {
console.log(timeOnPursuit)
if (timeOnPursuit > 0) {
btn.innerHTML = "In Pursuit: " + timeOnPursuit;
timeOnPursuit -= 1; // reduce time
} else {
btn.innerHTML = "Pursuit";
clearInterval(timer) // stop the timer
}
}, 1000)
}
<div class="button">
<button id="pursuit" class="pursuit" onClick="pursuit()"> Go on a Pursuit </button>
</div>
I was going to write a lot of what David wrote so it seems a little redundant now. Instead here's an alternative approach that uses setTimeout instead of setInterval.
// Cache the element and add a click listener to it
// (no need for inline JS)
const btn = document.querySelector(".pursuit");
btn.addEventListener('click', pursuit, false);
function pursuit() {
// Initialise timeOnPursuit
function loop(timeOnPursuit = 10) {
// Display the button text, and disable the button
btn.innerText = `In Pursuit: ${timeOnPursuit}`;
btn.disabled = true;
// If timeOnPursuit is greater than zero
// call loop again with a a decremented timeOnPursuit
if (timeOnPursuit > 0) {
setTimeout(loop, 1000, --timeOnPursuit);
}
}
// Call the loop function
loop();
}
<div class="button">
<button class="pursuit"> Go on a Pursuit </button>
</div>

Show changed localStorage without refreshing page?

I am working on something. But everytime I take away from the value, I have to refresh the page to show the new value.
localStorage.setItem("money", money - 20);
How do I make the value "money" refresh on the page without actually refreshing the page itself? Can it be done with pure JavaScript?
First things first, storing money in localStorage is not desirable. Users can easily change its value using developer tools. If you're using that value for caching, never trust that value in Backend.
Second, you have to update the value with custom function whenever you change the money and store it to localStorage. Like the following:
localStorage.setItem("money", money - 20);
document.getElementById("balance").innerText = localStorage.getItem("money") || 0;
localStorage is not supported in SO code snippet, so I'm going to post a full html here. You can just cut&paste and try to understand its logic.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Balance Example</title>
</head>
<body>
<div>Balance: $<span id="balance">0</span></div>
<button id="btnWithdraw" onClick="withdraw(20)">Withdraw 20$</button>
<button id="btnDeposit" onClick="deposit(100)">Deposit 100$</button>
</body>
<script>
function getBalance() {
let money = parseFloat(localStorage.getItem("money") || 0);
return isNaN(money) ? 0 : money;
}
function setBalance(amount) {
localStorage.setItem("money", parseFloat(amount));
}
function withdraw(amount) {
let balance = getBalance();
if(balance < amount) {
return alert("Not enough balance!");
} else {
balance = balance - parseFloat(amount);
}
if (isNaN(balance)) balance = 0;
setBalance(balance);
renderBalance();
}
function deposit(amount) {
amount = parseFloat(amount);
if (isNaN(amount) || amount < 0) {
return alert("Invalid amount!");
}
let balance = getBalance();
balance += amount;
setBalance(balance);
renderBalance();
}
function renderBalance() {
document.getElementById("balance").innerText = getBalance().toFixed(2);
}
window.onload = function() {
renderBalance();
}
</script>
</html>
After updating localStorage, use document.getElementById() to select the element on your page that displays the value of your money variable and update its content with .innerHTML:
localStorage.setItem("money", money - 20);
document.getElementById("money").innerHTML = money - 20;
The following Pen shows a working example of how to implement this.
Show changed variable without reloading page on CodePen.

How to Change a Value of a Variable and Print It

Sorry, I'm totally new to javascript and need help with something you think is probably really stupid.
I'm trying to make it so that when you start the program, it prints 0, then when you press a button, it changes 0 to 1. This is what I have so far -
<!DOCTYPE html>
<html>
<p id="print"></p>
<script>
var x = 0
document.getElementById('button').onclick = function() {
x++;
};
document.getElementById("print").innerHTML = x;
</script>
<button id = "button">Change Variable x</button>
</body>
</html>
Although, it doesn't print anything when I run the code. Please Help! (By the way, you are probably thinking that this is a stupid question.)
Thanks!
I hope this will work:
var x = 0
document.getElementById('button').onclick = function() {
x++;
document.getElementById("print").innerHTML = x;
};
Not sure if this is what you are looking for, but all I did was make a function name and then whenever you click the button it adds 1 to the
<p id="print">hello</p>
<button id = "button" onclick="myFunction()">Change Variable x</button>
<script>
var x = 0
function myFunction(){
document.getElementById('print').innerHTML = x+=1;
}
</script>
Here is a working snippet of what you are looking for, using javascript. When the user clicks the button, it changes the value to 1, and then when you click the alert button it alerts 1 instead of 0.
var changeMe = 0;
function changeVar() {
changeMe = 1;
}
function alertVar() {
alert(changeMe);
}
<button onclick="changeVar();">Change</button>
<button onclick="alertVar();">Alert</button>

Issue with setTimeOut and non-response script in IE8

I am getting an issue with a large amount of processing causing the non-responsive script error in IE8 (and no, I cannot make the users use a better browser).
I then read that it should be possible to split up the tasks and cede control back to the browser in between different parts of the validation. So I decided to make a simple example based on some code I found to figure out where the breaking points are. The real code is doing lots of jquery validationengine processing.
I tried to use jsFiddle but I can't get jsFiddle to run in IE8. Bummer. So, I'll have to share inline here.
When I first load it, it seems to work just fine. I push the button and both functions finish without a problem. However, subsequent pushes causes an unresponsive script error. I've played around with the number of loops in my simulated work function. Much more than 1.25 million loops and it dies with unresponsive script.
Shouldn't separate calls to the onClick start the non-responsive counter anew? What am I missing here?
<html>
<head>
<script>
var progress = null;
var goButton = null;
window.onload = function() {
progress = document.getElementById("progress");
goButton = document.getElementById("goButton");
}
function runLongScript(){
// clear status
progress.value = "";
goButton.disabled=true;
var tasks = [function1, function2];
multistep(tasks,null,function() {goButton.disabled=false;});
}
function function1() {
var result = 0;
var i = 1250000;
for (;i>0; i--) {
result = result + 1;
}
progress.value = progress.value + "f1 end ";
}
function function2() {
var result = 0;
var i = 1250000;
for (;i>0; i--) {
result = result + 1;
}
progress.value = progress.value + "f2 end";
}
function multistep(tasks, args, callback){
var tasksClone = tasks.slice(0); //clone the array
setTimeout(function(){
//execute the next task
var task = tasksClone.shift();
task.apply(null, args || []);
//determine if there's more
if (tasksClone.length > 0){
setTimeout(function () {
multistep(tasksClone, args, callback);
}, 100);
} else {
callback();
}
}, 100);
}
</script>
</head>
<body>
<p><input type="button" id="goButton" onClick="runLongScript();" value="Run Long Script" /></p>
<input type="text" id="progress" />
</body>
</html>
You're never calling clearTimeout() to remove the one currently running when the button has been pressed already. Add an if statement before you start another setTimeout and check to see if one is already running, clear it if it is, and then continue. Here's a link that should help you if you have any questions: https://developer.mozilla.org/en-US/docs/Web/API/window.clearTimeout

How to change the function called by a dynamically created button?

I was making a little game in JavaScript when I ran into a problem. In this game I create a hundred buttons using a for() loop. Eventually I want every button to call a function called 'click' and send it an int so it knows what button is pressed. So for instance when button four is pressed click(4) is called. First I tried this:
object.onclick = "click(4)";
That obviously didn't work so i searched the interwebs and fount an answer to this question on your site.
object.onclick = function() {click("4");}
I tried that (with and without the ';' at the end) but it doesn't seem work.
A more complete overview of the dummy code:
<script type="text/javascript">
document.getElementById('myContainer').innerHTML += '<input id="tmp" type="button" value="button">';
documengetElementById('tmp').onclick = function() {tmpFunc("bla");}
function tmpFunc(vari){
alert(vari);
}
</script>
The element myContainer is 100% empty!
Remember, this is just dummy code to try it out. I could do this waaaaay easier but I tried to simplify it first so you don't have to look at my messy code.
So what is the best way to call a function from a button you have created in a for loop? If you know a way to do it totally different from the one I use just post it, I don't care how it gets solved! Although I'd also like somebody to explain why this isn't working.
Hope I didn't ask a question already answered, as far as I know I'm using the solution given for this problem in another post.
------------UPDATE-------------
Changed it a bit after getting an answer from somebody. This is the current code, select() isn't executed when a button is pressed. Here's the complete JavaScript code so you can copy-paste it if you want to play around with it.
<script type="text/javascript">
function addButtons(){
var disabled = false;
for(var i = 1; i <= 100; i++){
currentButton = '<input id="tmp" type="button" onclick="select(\''+i+'\')">'
document.getElementById('myContainer').innerHTML += currentButton;
document.getElementById('tmp').id = 'btn'+i;
gb(i).disabled = disabled;
gb(i).style.width = "60px";
gb(i).style.height = "60px";
gb(i).style.fontSize = "25pt";
function alerts(nr){
alert("test");
}
if(i%10 == 0){
document.getElementById('myContainer').innerHTML = document.getElementById('myContainer').innerHTML + '<br />';
}else{
if(disabled){
disabled = false;
}else{
disabled = true;
}
}
if(i == 60){
gb(i).value = 'O';
gb(i).style.color = "blue";
}
if(((i-1)%10 == 0) && !(gb(i).disabled)){
gb(i).value = 'X';
gb(i).style.color = "red";
}
}
}
function select(nr){
alert("Bla!"+nr);
gb(nr).style.height = "100px";
}
function gb(ButtonNrVanHetButton){
return document.getElementById('btn'+ButtonNrVanHetButton);
}
addButtons();
</script>
Most parts aren't very interesting for solving the problem (style etc) It's supposed to look like a checkerboard.
------------UPDATE-------------
Solved! Don't use functions the javascript library already uses for other stuff like: 'select()'. Thx to everybody who tried to help!
If you are looping to create the buttons, why don't you add an onclick to the button?
for instance
<script>
// your function
function tmpFunc(vari)
{
alert(vari);
}
// end your function
// define xBUTTONS
xBUTTONS = '';
for (i=0; i<100; i++)
{
// loop buttons
xBUTTONS += '<input id="tmp" type="button" value="button" onclick="tmpFunc(\''+i+'\')">';
}
// insert buttons into myContainer
document.getElementById('myContainer').innerHTML = xBUTTONS;
</script>
first off, always attach events by using addEventListener. second, if you add an id to the button you dynamicly generate you can do something like this;
function click(){
alert(this.id+" clicked");
}
var but;
for (var i=0,e=100,i<e;++i){
but=document.createElement("input");
but.id=i;
...//make it into your button
but.addEventListener("click", click, false);
document.body.appendChild(but);
}

Categories