0

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')
1
  • You are using a class but selecting the element using id method so either you need to declare an id to the button or you need to use getElementsByClassName() Commented Jan 31, 2015 at 3:46

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When i do that i get SyntaxError: Function statements must have a name. and if i format it i get the error UNEXPECTED EOF
Yes, you do not have an element with an ID of "U1". As I stated in my answer above, you need to change your HTML.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.