sameer manek
sameer manek

Reputation: 763

false statement not executed by ternary operator

In the following code, the ternary operator isn't assigning the value if condition returns false!

<script>
                function lgn() {
                    document.getElementById('overlay').style.display = 'none' ? 'block':'none';
                    document.getElementById('lgn').style.display = 'none' ? 'block':'none';
                }
</script>

I am actually trying to make a overlay over my webpage, following is the Twig:

<div class="nvg">
                <ul>
                    {% block links %}
                    <li class="n.link"><span class="fa fa-times close" onclick="lgn()"></span></li>
                    {% endblock %}
                </ul>
</div>

AND

{% block overlay %}
        {{ form_start(form, {'attr':{'id':'lgn'}}) }}
        <span class="fa fa-times close" onclick="lgn()"></span><br />
        <span>Login:</span>
        {{ form_widget(form.email, {'attr':{'placeholder':'email'}}) }}
        {{ form_widget(form.pass, {'attr':{'placeholder':'password','class':'pass'}}) }}
        {{ form_end(form) }}
{% endblock %}

Please help...

Upvotes: 1

Views: 1124

Answers (3)

Daniel
Daniel

Reputation: 1253

Your ternary doesn't make sense.

document.getElementById('overlay').style.display = 'none' ? 'block':'none';

There's no logical evaluation to make, and the string will (mostly) always be evaluated to true. Do something like this:

document.getElementById('overlay').style.display = (document.getElementById('overlay').style.display == 'none') ? 'block' : 'none';

Your best solution (in terms of cleanliness) is to make the selectors into variables.

function lgn() {
    element1 = document.getElementById('overlay');
    element1.style.display = (element1.style.display == 'none') ? 'block' : 'none';

    element2 = document.getElementById('lgn');
    element2.style.display = (element2.style.display == 'none') ? 'block' : 'none';
}

Upvotes: 1

isvforall
isvforall

Reputation: 8926

You always assign the display to 'block' because the 'none' is a non-empty string and it is always true

document.getElementById('overlay').style.display = 'none' ? 'block':'none';

Use this statement

var display = document.getElementById('overlay').style.display
document.getElementById('overlay').style.display = display == 'none' ? 'block':'none';

Upvotes: 1

Marc B
Marc B

Reputation: 360862

The ternary makes a boolean decisions, and you've written yours to always evaluate to true:

'none' ? 'block':'none';

is basically the same as

if ('none' is true) { 
   'block'
} else {
   'none';
}

Since none as a string is a truthy (evaluates to the same as boolean true in most cases), you always pick the "true" path in the ternary.

Upvotes: 3

Related Questions