Page named index.php contains 1 menu with 3 options. Menu links lead to URL:index.php?id_product=xy. Then PHP reads id_product with GET and prints details from database. Now I want to highlight(change color of text) of the last clicked menu item. How to do this? Is it possible to read the value of id_product form URL with jQuery and then to add text effect to clicked menu item? Any ideas?
<ul>
<li><a href='index.php?id_product=1'>1</a></li>
<li><a href='index.php?id_product=2'>2</a></li>
<li><a href='index.php?id_product=3'>3</a></li>
</ul>
First, add some id tags to your elements:
<ul>
<li><a id="1" href='index.php?id_product=1'>1</a></li>
<li><a id="2" href='index.php?id_product=2'>2</a></li>
<li><a id="3" href='index.php?id_product=3'>3</a></li>
</ul>
Then add class "highlight" to the proper $_GET variable using javascript/jquery and a sprinkle of php:
<script>
jQuery(document).ready(function($) {
var selected_product = "<?php echo $_GET['id_product']; ?>";
if(selected_product !== "")
$("#"+selected_product).addClass("highlight");
});
</script>
Finally create the highlight class with css:
<style>
a.highlight { color: red; }
</style>
<?php
$menu_items = array(1, 2, 3);
$product_id = $_GET['id_product'];
echo "<ul>";
foreach($menu_items as $menu_item){
echo "<li><a href='index.php?id_product=" . $menu_item . "'" . (isset($product_id) && $product_id == $menu_item ? " class='active'" : "") . ">" . $menu_item . "</a></li>";
}
echo "</ul>";
?>
This will add an active class to the menu item based on id_product
This should be work.
$(function()){
var file_url = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1)
$("ul > li > a[href="+file_url+"]").addClass("selected");
}
another way should be
$(function(){
$("ul > li > a[href$='"+window.location.search+"']").addClass("selected");
})
anyway it is easier only with php :)
foreach ($products as $p) {
$selected = ($_GET["id_product"]==$p->id)?" class='selected'":"";
echo "<a href='?id_product=".$p->id."'".$selected.">".$p->id."</a>";
}
or
<style>
a[href*='id_product=<?=$_GET["id_product"]?>']{ color:red; }
</style>
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.