Reputation: 35
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 -->
Upvotes: 0
Views: 1082
Reputation: 3603
Change the document.getEle... to the following:
$(document).ready(function() {
$("#header").show();
});
or
$(document).ready(function() {
$("#header").show();
});
Upvotes: -1
Reputation: 1740
change code chunk order:html first
<div id="header">
Hello You Are a Fan
</div><!-- #header -->
<?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>';
}
?>
because when js runing,the #header dom is not exit.
Upvotes: 1
Reputation: 17573
It's not working because at the time the JS code runs, #header
does not yet exist on the page. If you move the PHP (and therefore the JS) down below the #header div, it will work.
The better way to do it is to wrap the JS in a $(document).ready()
call as pimvdb suggests.
HOWEVER, I don't think that will give you a good result because #header
will actually be visible briefly, and then disappear. The best way to solve this specific case is to do something like:
<?php
if ($sr_data->page->liked==1) {
$display = 'block';
} else {
$display = 'none';
}
?>
<div id="header" style="display:<?php echo $display ?>">
Hello You Are a Fan
</div>
By embedding the correct style inline with the div, it will never show up when it shouldn't.
Upvotes: 3
Reputation: 154918
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 .hide
and .show
so you don't need getElementById
and style.display
:
echo '<script language="javascript">
alert("Hello You Are a Fan");
$(document).ready(function() { // only run when all elements are available
$("#header").show();
});
</script>';
Upvotes: 5