onclick function in JavaScript function is not working. We need onclick page to add active class and remove previous active class.
All my pages come from database, they have not been manually added. Pages are added only from admin panel. We use 2 javascript code but they are not working the same way !!!!
//javascript
1. $(document).ready(function() {
$("#header-page li a").on("click", function() {
$("#header-page li a").removeClass('active');
$(this).toggleClass("active");
});
});
2. // Header Pages Active
$('#header-page li a').on('click', function () {
$("#header-page li a").removeClass('active');
$(this).toggleClass('active');
});
//code
<div class="collapse navbar-collapse" id="navbarCollapse">
<div class="navbar-nav ms-auto p-4 p-lg-0">
<div class="header" id="header-page">
<li> <a class="active" href="index.php"></a> </li>
<?php
$id=$_GET['id'];
$qry="SELECT * FROM tbl_menu where visibility_status=0 order by position_order ASC ";
$result=mysqli_query($connectiondb,$qry);
while($row=mysqli_fetch_array($result))
{
?>
<li><a class="mx-2 nav-item nav-link" href="<?php if($page_status=='true')?> <?php echo $row['page_link'];?>?id=<?php echo $row['id']; ?>"><?php echo $row['page_name'];?></a></li>
<?php } ?>
</div>
</div>
</div>
///css
/*** Headers Active Pags***/
#header-page li {
display: inline-block;
font-weight: 500;
color: var(--dark);
cursor: pointer;
transition: .5s;
border-bottom: 5px solid transparent;
}
#header-page li:hover,
#header-page li a.active {
color: var(--primary);
border-color: var(--primary);
}
I think there is something wrong the way you target the HTML elements, I'll suggest you to use classes for your anchors and all is good then:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>test2</title>
<script type="text/javascript" src="/jquery-3.2.1.min.js"></script>
<style type="text/css">
#header-page li {
display: inline-block;
font-weight: 500;
color: #444;
cursor: pointer;
transition: .5s;
border-bottom: 5px solid transparent;
}
#header-page li:hover,
#header-page li a.active {
color: #00ff00;
border-color: #00ff00;
}
</style>
</head>
<body>
<div class="collapse navbar-collapse" id="navbarCollapse">
<div class="navbar-nav ms-auto p-4 p-lg-0">
<div class="header" id="header-page">
<li> <a class="active nav-link" href="#">index</a> </li>
<li><a class="mx-2 nav-item nav-link" href="#">test 1</a></li>
<li><a class="mx-2 nav-item nav-link" href="#">test 2</a></li>
<li><a class="mx-2 nav-item nav-link" href="#">test 3</a></li>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".nav-link").on('click', function () {
$(".nav-link").removeClass('active');
$(this).addClass("active");
});
})
</script>
</body>
</html>