alexanderfeazell
alexanderfeazell

Reputation: 3

How do I change an HTML element with incrementing values?

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!')
}

Upvotes: 0

Views: 70

Answers (3)

Ashish Yadav
Ashish Yadav

Reputation: 3196

<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.

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21475

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.)

Upvotes: 1

DKB
DKB

Reputation: 1

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

Upvotes: 0

Related Questions