sameer manek sameer manek - 7 months ago 15
PHP Question

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

Answer

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';
}
Comments