简体   繁体   中英

Add active CSS class to menu item

I have this category menu. When I click on a category menu item, it opens the category page and what I need it to add the 'active' Bootstrap class on the menu item that was selected (clicked).

How can I do it?

<?php      
 $cat = "SELECT * FROM category WHERE cat_parent_id = :value ORDER BY cat_id ASC"; 
   $stmt = $con->prepare($cat);
   $stmt->bindValue(':value', 1, PDO::PARAM_STR);
      $stmt->execute(); 
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
          extract($row);
             $name_cat = str_replace("-"," ", $cat_name);
             $name_under = str_replace(" ","-", $cat_name);
             ?>     
               <li><a class="dropdown-item" href="<?php echo $home_url . 
                $cat_id."/".strtolower($name_under);?>.html"><?php echo strtoupper($name_cat); ?></a> 
                 </li>
<?php } ?>  

Going an extra step on the comment above from @El_Vanja:

Figure out the current url with the following code:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Then add that condition when you're forming the link:

<li<?php if($home_url == $actual_link echo ' class="active"';?>><a class="dropdown-item" href="<?php echo $home_url . 
            $cat_id."/".strtolower($name_under);?>.html">
            <?php echo strtoupper($name_cat); ?></a></li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM