bbruman bbruman - 2 months ago 6
Javascript Question

Converting Javascript to PHP Echoes to Insert PHP Conditional Statements

I've run into some situations where I need to add conditional statements from PHP functions to javascript items.

Here's an example code:

<script type="text/javascript">
$(window).bind("load", function() {
$("div.mejs-button.mejs-playpause-button.mejs-play > button").trigger('click');
});
</script>


And I need to wrap this in a conditional statement:

if (bp_current_user_can( 'bp_moderate' ) || $loggedinuserid == $userid ) {
//conditional statement for above javascript
}


I thought about this for a while, and eventually stumbled on an 'online script converter' site that converts the javascript into php echoes. So now my code is the following:

<?php
if (bp_current_user_can( 'bp_moderate' ) || $loggedinuserid == $userid ) {
echo " <script type=\"text/javascript\">\n";
echo "$(window).bind(\"load\", function() {\n";
echo " $(\"div.mejs-button.mejs-playpause-button.mejs-play > button\").trigger('click');\n";
echo "});\n";
echo "</script>\n";
}
?>


And this works as I want it too, but it seems rather messy- especially as I try to apply this with bigger pieces of javascript code, and if I'm wanting to edit the javascript code later on. Is this my only option for wrapping PHP conditional statements in javascript?

Answer

You can do:

<?php if (bp_current_user_can( 'bp_moderate' ) || $loggedinuserid == $userid ):?>
<script type="text/javascript">
   $(window).bind("load", function() {
   $("div.mejs-button.mejs-playpause-button.mejs-play > button").trigger('click');
   });
</script>
<?php endif; ?>
Comments