How do I change an HTML element with incrementing values? - javascript

When I go on the page, I have 0 cookies to start with. I made an if statement saying if there are less than 10 cookies, hide the upgrade button. I'm clicking and incrementing the value by 1. Once I reach 10 cookies, how do I get the upgrade button to show? Would it be with an event listener or what?
var cookies = 0;
var cookieClick = 1;
function getCookie() {
cookies += cookieClick;
document.getElementById('cookieCount').innerHTML = cookies;
document.getElementById('img').style.visibility = 'visible';
}
if (cookies < 10) {
document.getElementById('up').style.visibility = 'hidden';
}
function upgrade() {
cookieClick *= 2;
document.getElementById('up').style.visibility = 'hidden';
alert('You have x2 the clicks!')
}

Your if (cookies < 10) { isn't part of any function, so it'll only run once on page load. You probably want to include it in your getCookie() function instead, with an else to show the upgrade button when needed.
function getCookie() {
cookies += cookieClick;
document.getElementById('cookieCount').innerHTML = cookies;
document.getElementById('img').style.visibility = 'visible';
if (cookies < 10) {
document.getElementById('up').style.visibility = 'hidden';
} else {
document.getElementById('up').style.visibility = 'visible';
}
}
(But if the cookie value never decreases, you could simplify this a bit by just loading the page with the element hidden initially and only check for cookies > 10 to reveal it.)

Yes, an onClick event listener could check your current cookie count and toggle your upgrade button for visibility.

<button onclick="incrementCount()"> b1 </button>
<button id="b2" style="visibility:hidden" onclick="something()">b2</button>
<script>
var cookies = 0;
var cookieClick = 0;
function incrementCount(){
cookieClick = cookieClick + 1;
console.log(cookieClick)
if(cookieClick == 10){
document.getElementById('b2').style.visibility = "visible"
}
}
function something(){
alert('i work')
}
</script>
You can try this simple piece of code.

Related

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

How to use jquery and javascript in same document

So I am trying to use jQuery, (in the heading) and javascript (normally) in the same document, but it seems that because of the script source thing, it conflicts with the JavaScript and doesn't word as I need it too
<head>
<title> Panel </title>
<link type="text/css" rel="stylesheet" href="clicker.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(function( $ ){
$(document).ready(function(){
$("#buckhead").click(function(){
$("#buckpanel").slideToggle(750);
});
});
})( jQuery );
</script>
</head>
Then later on in the document I put:
<script type="text/javascript">
var bcost = 1;
var clickmulti = 1;
var clicks = 0;
var bcost = 1000;
var mcost = 100;
var y = 0;
var x = 0;
document.getElementById("clicks").innerHTML = clicks;
document.getElementById("mcost").innerHTML = mcost;
document.getElementById("bcost").innerHTML = bcost;
function clickFunc() {
clicks += cps * clickmulti;
document.getElementById("clicks").innerHTML = clicks;
return true;
}
function clickMulti() {
if(clicks >= mcost && y < 50) {
clicks -= mcost;
mcost *= 1.25;
mcost = math.ceil(mcost * 1) / 1;
clickmulti += 1;
document.getElementById("clicks").innerHTML = clicks;
document.getElementById("mcost").innerHTML = mcost;
y += 1;
return true;
} else if(y == 50) {
alert("This upgrade is maxed!");
return false;
} else {
alert("You do not have enough fish to purchase this!");
return false;
}
}
function clickBase() {
if(clicks >= bcost && x < 100) {
clicks -= bcost;
bcost *= 1.25;
bcost = math.ceil(bcost * 1) / 1;
x += 1;
cps += 1;
document.getElementById("clicks").innerHTML = clicks;
document.getElementById("bcost").innerHTML = bcost;
return true;
} else if(x == 100) {
alert("This upgrade is maxed!");
return false;
} else {
alert("You do not have enough fish to purchase this!");
return false;
}
}
</script>
And it seems like the code is conflicting, because the jQuery is working just fine, as it is simple code, but the buttons to activate the JavaScript, which should be working as buttons are really easy, seems so when I click it, the functions aren't working, although almost every function is working, (ALMOST) except for
function clickFunc()
If you have the answer it would be greatly appreciated!
edit: here is the button calls, which by the way the buttons are before the second script.
<div class="fish"
<h2>Click for fish</h2><br>
<button onclick="clickFunc()" type="button">Click for fish</button><br>
<p> You have <span id="clicks"></span> fish</p>
<button type="button" onclick="clickMulti()"> Upgrade your click multiplier! (Cost:<span id="mcost"></span>)</button>
<button type="button" onclick="clickBase()">Upgrade base clicks!<br>
(Cost:<span id="bcost"></span>)</button>
</div><br><br>
Resolved, simply my problem of forgetting to make a global variable instead of a local variable. I forgot to make the global variable "cps"

javascript loading a file after a condition

When I use window.open("file") then it'll open the file as a new tab. I already tried .load but it doesn't work either. You may know how to solve my problem that the html file loads directly in the running window ?
function progress() {
var prg = document.getElementById('progress');
var percent = document.getElementById('percentCount');
var counter = 5;
var progress = 25;
var id = setInterval(frame, 64);
function frame() {
if (counter == 100) {
clearInterval(id);
window.open("welcome.html")
}
else {
progress += 5;
counter += 1;
prg.style.width = progress + 'px';
percent.innerHTML = counter + '%';
}
}
}
progress();
You can open the file in the current tab but adding the _self argument to the name parameter:
window.open("welcome.html","_self");
▲
You can also achieve the same by using window.location.href:
window.location.href = "welcome.html";
you can use
window.location.href = "welcome.html";
It will open file in same tab.
You can use window.location.assign("welcome.html"); instead of window.open("welcome.html");
See this article

Why wont my text update? (HTML + JS)

I am trying to make text on my site update. The variable in JS does, but the text on screen doesn't. (Yes I know the code is sloppy, I get it to work and then go through and make it pretty.)
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var moneyText = String(moneyTotal); //Variable for text
var OD2Clicked = 0;
</script>
<script>document.write("<h1 class='money'>Total: $"+ moneyText + "</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked & OD2Clicked==0) {
OD2Clicked = 1;
Adding(20);
console.log("Adding");
}else if(document.getElementById('OD').checked & OD2Clicked>0){
OD2Clicked = 0;
Adding(-20);
console.log("Subtracting");
}
setTimeout(function() {Check()}, 5000);
}
function Adding(m1){ //Function for adding
moneyTotal += m1;
moneyText = String(moneyTotal);
console.log(moneyTotal);
console.log(moneyText+" Text");
}
</script>
Just like I mentioned above in the comment:
Your screen write happens only once when Browser will parse all tags. You need to update your text on the screen every time you modify the value.
Would this work for you?
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var OD2Clicked = false;
var timeoutPeriod = 5000;
</script>
<script>document.write("<h1 class='money'>Total: $0</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked) {
if (!OD2Clicked) {
OD2Clicked = true;
moneyTotal += 20;
console.log('Adding');
} else if (OD2Clicked) {
OD2Clicked = false;
moneyTotal -= 20;
console.log('Subtracting');
}
// Find DOM element we need to update
document
.querySelectorAll('.money')[0]
.textContent = 'Total: $' + moneyTotal;
}
setTimeout(Check, timeoutPeriod);
}
</script>

Creating a counter

I'm creating a counter and I'm having a hard time making it.
The goal of the counter is that for ever second passed a number will increase by 170.
As you can see below the number does not add up and is made on a new line, mostly because I dont know how to make it add up. Some thing like this clock from The Economist
<!DOCTYPE html>
<html>
<body>
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
<script>
function counterFunction() {
setTimeout(function () {
var text = "";
var i = 170;
while (i < 3500) {
text += "<br>The number is " + i;
i+=170;
}, 1000) }
document.getElementById("counter").innerHTML = text;
}
</script>
</body>
</html>
Any ideas on how I can make this and what is wrong with my code?
Don't use inline JavaScript (JavaScript inside HTML element attributes), it is horrible for maintainability and readability.
You seem to have a misconception about how timeouts, intervals and while loops work, what you want is an interval.
Define a count variable outside of the event listener function, then on each iteration of the interval increment the count variable by one and multiply that number by 170.
I added a little bit in there to hide the button once it has been clicked, just to stop the user from restarting the counter.
var clicker = document.getElementById('clicker');
var counter = document.getElementById('counter');
var count = 0;
clicker.onclick = function() {
setInterval(function () {
counter.textContent = "The number is " + ++count * 170;
}, 1000);
clicker.style.display = 'none';
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button id="clicker">See it now</button>
<p id="counter"></p>
http://jsfiddle.net/mblenton/Le4vxzrn/2/
function counterFunction() {
var text = ""; var i = 170; var delay = 0; var k = 1;
while (i < 3500) {
text = "The number is " + i;
i += 170;
delay = k * 1000;
doSetTimeout(text, delay);
k++;
}
}
function doSetTimeout(text, delay) {
setTimeout(function () {
document.getElementById("counter").textContent = text;
}, delay);
}
You need to use setInterval, not setTimeout`. Note that if you click the button, it will reset your timer.
You also need to declare var i and var text outside the scope of the Interval, or they will also be reset each iteration.
There were a few things wrong with your code. Among other things:
your i variable was declared in the wrong place to be reused
your closing braces were in the wrong place for the callback function
you were using a while loop, which runs synchronously, whereas you really want to just use a setInterval call.
This should work:
function counterFunction() {
var i = 170;
var text = "";
var interval = setInterval(function () {
text += "<br>The number is " + i;
i+=170;
document.getElementById("counter").innerHTML = text;
if (i >= 3500) {
clearInterval(interval);
}
}, 1000);
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
Ok so the adder variable should be declared outside of the timeout function, because if not you are replacing the value. and you should use setInterval
var p =0;
function counterFunction(){
setInterval(function(){ p+=170;
console.log('value of p '+p);
}, 3000);
}
if you dont want to roll your own here is a nice counter
http://keith-wood.name/countdown.html

Categories