pfych
pfych

Reputation: 928

Change a buttons css using JS

I have a hidden button i want to show when the user has 5 coffee this is my code but it just doesn't seem to work

JS

window.setInterval(function(){

                   if (coffee == 5) {
                   document.getElementById("U1").style.visibility = "visible";
                   console.log()
                   }

                   }, 500);

HTML

<button class="U1" onclick="SuperPlant()"> Super Beans</button><br>

CSS

.U1 {
visibility: hidden;
}

ERROR IN CONSOLE

TypeError: null is not an object (evaluating 'document.getElementById("U1").style')

Upvotes: 0

Views: 81

Answers (3)

Vijay
Vijay

Reputation: 3023

Change your HTML :

<button id="U1" onclick="SuperPlant()"> Super Beans</button><br>

AND CSS:

#U1 {
   visibility: hidden;
}

This is because you are using getElementById(); and your button where only named by class, and not ID.

Upvotes: 0

MattSizzle
MattSizzle

Reputation: 3175

I personally would do it as follows:

FIDDLE

HTML

<button id="U1" onclick="SuperPlant()" style="visibility: hidden">Super Beans</button>

JAVASCRIPT

var coffee = 5;

function showButton() {

    if (coffee == 5) {
        document.getElementById("U1").style.visibility = "visible";
        console.log()
    }

}

window.setInterval(showButton, 500);

I would recommend against the anonymous function in the setInterval as it can be hard to troubleshoot.

Hope this Helps.

Upvotes: 0

Ian Hazzard
Ian Hazzard

Reputation: 7771

You need to put quotes around your setInterval() command, and it doesn't need to be inside of a function. Like this:

window.setInterval("if (coffee == 5) { document.getElementById('U1').style.visibility = 'visible'; console.log() }", 500);

NOT THIS:

window.setInterval(function() {if (coffee == 5) { document.getElementById("U1").style.visibility = "visible"; console.log() } }, 500);

Also your button should have id="U1" NOT class="U1". Which means change CSS selector to #U1.

Upvotes: 1

Related Questions