Reputation: 21988
I am generating a JS navigation using PHP. Script is included like so
<script type='text/javascript' src='/topNav.js.php'></script>
I would like to use PHP rather than JavaScript to assign the class for the current page's link but all of the $_SERVER vars see the topNav.js.php location.
I know I could use JS something like
if(window.location.href == 'myurl') {
document.getElementById('itemx').className += 'active';
}
but I wanted to know if there was a good way to do this via PHP.
Upvotes: 1
Views: 146
Reputation: 21988
I have a PHP footer include I had not considered. Just added
<script type="text/javascript">
<? $pg = preg_replace('/\//', '', $_SERVER['REQUEST_URI']); ?>
document.getElementById('nav_<?=$pg?>').className += ' qmactive ';
</script>
Lazy and functional.
Upvotes: 0
Reputation: 21105
You could write the current page into Javascript with PHP before calling your "external" script file.
Something like...
<script type="text/javascript">
<?php
echo "var CurrentPage = '" . $_SERVER["REQUEST_URI"] . "';";
?>
</script>
<script type='text/javascript' src='/topNav.js.php'></script>
This variable will be usable in your external script. You can set something in your external script to make sure it has a value if you do not manually set it outside. That would be a good practice for error handling.
Upvotes: 1