I want to show and hide a div based on a condition. This time I am not using any function since I thought it would be better as simple as possible.
I am trying to show and hide 2 DIVs based on a "status" of the user ($new). I don't know if it's possible to assign a PHP value to a JavaScript variable and the best way to do it ...
"var" is supposed to get the value of "$new".
Javascript:
<script>
var var = $new;
if (var != 1) {
document.getElementById("subjectr").style.display = "block";
} else {
document.getElementById("subjectr").style.display = "none";
}
</script>
HTML:
<center>
<div id="subjectr" value="<?php echo "$new"?>" style="display: none">
<a href="" id="ifYes" style="background-color: green; border: 2px solid #44db2c; display: none;" method=POST; class="btn btn-info">COORDINADOR</a>
</div>
</center>
If you know a better way to do it, I would appreciate your help.
You don't need JS, simply echo or wrap the desired HTML into an if $new is true right on the server-side
<?php if ($new) { ?>
<div>Content for new users</div>
<?php } ?>
<div class="<?= $new ? '' : 'isHidden' ?>">Content for new users</div>
.isHidden { display: none; } /* Add this class to CSS file */
The above might come handy if at some point, by using JavaScript you want to toggle the visibility of such element using .classList.toggle('isHidden') or jQuery's .toggleClass('isHidden')
If you really want to pass your PHP variable to JavaScript:
<div id="subjectr">Content for new users</div>
<script>
var isNew = <?php echo json_encode($new); ?>;
document.getElementById("subjectr").style.display = isNew ? "block" : "none";
</script>
<!-- The above goes right before the closing </body> tag. -->
PS:
<center> tag might work in some browsers but it's long time obsolete. Use CSS instead. value is an invalid HTML5 attribute for div Element. Use data-value instead.method=POST; on an <a> tag?var var is a syntax Error in JavaScript, var being a reserved word. Use a more descriptive var isNew instead.Instead of using javascript, you could use PHP to influence the display style of your div by using a ternary to decide whether it is none or block:
<center>
<div id="subjectr" value="<?=$new?>" style="display: <?=$new != 1 ? 'block' : 'none'?>">
<a href="" id="ifYes" style="background-color: green; border: 2px solid #44db2c; display: none;" method="POST" class="btn btn-info">COORDINADOR</a>
</div>
</center>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With