I am trying to show and hide a div based on a condition (for facebook in this example).
Here is the code I am using, but for some reason, the alert works, but it still shows the div.
Can someone help debug this. thanks.
<?php
// call the function to parse the signed request
$sr_data = mySignedRequest();
// check like status
if ($sr_data->page->liked==1) {
echo '<script language="javascript">
alert("Hello You Are a Fan");
document.getElementById("header").style.display = "block";
</script>';
} else {
echo '<script language="javascript">
alert("You are not a fan");
document.getElementById("header").style.display = "none";
</script>';
}
?>
<div id="header">
Hello You Are a Fan
</div><!-- #header -->
This is a typical example of code trying to access elements while they don’t exist yet. You’re namely fetching an element with
getElementById, but the element is only defined after all JavaScript code.You should use
$(document).ready. Moreover, jQuery has.hideand.showso you don’t needgetElementByIdandstyle.display: