javascriptphpwebinclusion

Changing the CSS of a file included with PHP using JavaScript


I've recently made a site where I have a navigation bar, which is included to the pages using PHP.

<?php include "Assets/Inclusions/NavigationBar.php" ?>

I wanted the active page list item to have bold text, so I used JavaScript to fetch the current path and make the relative element bold with a lot of if statements.

<script>
if(location.pathname == 'location.php')
document.getElementById("location").style.fontWeight="800";
    } ...and so on
</script>

Is there a better way I should have done this?


Solution

  • This seems like something that should be done on the server-side of things. Please feel free to correct this if I have made a syntax error, it's been a while since I've written PHP, but here's the gist of it:

    NavigationBar.php

    <?php
        function isActive($page){
          $currentPage = $_GET['page']; // mypage.com?page='something'
    
          if ( !isset($currentPage) ) $currentPage = 'home';
    
          return $currentPage == $path;
        }
    ?>
    
    <ul class="navigation">
      <li><a href="?page=home" 
              <?php if ( isActive('home') ) echo('class="active"'); ?> >Home</a></li>
      <li><a href="?page=About" 
              <?php if ( isActive('about') ) echo('class="active"'); ?>>About Us<a/></li>
    </ul>
    

    style.css

    a.active{
        font-weight: 800;
    }