Jeffrey Edbauer
Jeffrey Edbauer

Reputation: 49

Error when Making a Div Visible in a Function

Here is the HTML:

<div class="div1" id ="div1" onclick="onStepClicked()" style ="text-align:center">Step 1</div>

Here is the Script:

 function onStepClicked() {
        var elem = document.getElementById('div2');
        if (Visible = true) {
            elem.style.visibility = 'hidden';
            Visible = false;
        }
        if (Visible = false) {
            elem.style.visibility = 'visible';
            Visible = true;
        }
    }

When I click the Div the first time, the Div is hidden which is correct. When I Click it again however, I won't become visible again. It is probably a simple error that I am overlooking.

Upvotes: 1

Views: 76

Answers (3)

Pabs123
Pabs123

Reputation: 3435

 function onStepClicked() {
        var elem = document.getElementById('div2');
        if (Visible === true) {
            elem.style.visibility = 'hidden';
            Visible = false;
        } else if (Visible === false) {
            elem.style.visibility = 'visible';
            Visible = true;
        }
    }

you're assigning a value to Visible by doing a single =. you need to check equality using === or ==

Additionally, unless you need Visible somewhere else, you can just do:

 function onStepClicked() {
        var elem = document.getElementById('div2');
        if (elem.style.visibility === 'visible') {
            elem.style.visibility = 'hidden';
        }
        else {
            elem.style.visibility = 'visible';
        }
    }

Upvotes: 2

dpdragnev
dpdragnev

Reputation: 2111

I see couple of things: - you are searching for div2 while your div has an id of div1 - the if statement should be == or === not =

Upvotes: 0

Andy Arndt
Andy Arndt

Reputation: 395

 function onStepClicked() {
    var elem = document.getElementById('div2');
    if (elem.style.visibility == 'visible')
        elem.style.visibility = 'hidden';
    else
        elem.style.visibility = 'visible';
}

Your mistake is setting Visible equal to true in your first if statement. The difference being Visible = true vs Visible == true. The first example sets a value to Visible (= is an assignment operator), the second compares a value with Visible (== is a comparison operator).

For this small snippet, you don't need an extra Visible variable, but if you need it in other parts of your code, you're free to add it back in.

Upvotes: 1

Related Questions