PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 8, 2022

[FIXED] when I Added .active class to menu it not working correctly

 November 08, 2022     html, javascript, menu, php     No comments   

Issue

I am trying to add .active class to menu in my php website using javascript but the problem that when I click on the link, it adds .active for very very short time and after that it remove it

      $(document).ready(function(){$(document).on('click','ul li a',function(){  $('li a').removeClass("active");
        $(this).addClass("active");
 }); });

and code for menu is

<ul class="nav ls navbar-nav ">
 <li><a href="<?php echo SITE ?>contact_us.php" class="active">İletişim</a></li>
       <li><a href="<?php echo SITE ?>gallery.php">gallery</a></li>
  </ul>

Solution

JavaScript only affects what is currently on the page. If you use jQuery "addClass", when you reload the page, then the entire HTML will reset, and the .active class will be lost.

Instead of JavaScript, you must use PHP on the back-end to detect what page the browser is currently on. The below code, keeps the jQuery you want (even though it is not necessary), but also uses PHP function "create_nav_link" to detect what page you are currently on, and adds 'class="active"' to the links.

The entire <script> section below can be removed, and the code will still work.

Try to copy & paste the following, and please feel free to ask me questions in comments:

<html>
<head>
    <style>
        a {
            color : #000;
        }

        a.active {
            color : #F00;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<ul class="nav ls navbar-nav ">
    <li><?php create_nav_link('/contact_us.php','İletişim') ; ?></li>
    <li><?php create_nav_link('/gallery.php','gallery') ; ?></li>
</ul>
<?php

    function create_nav_link($url,$label) {

        echo '<a href="' . $url . '"' ;
        if ( $_SERVER['REQUEST_URI'] == $url ) echo ' class="active"' ;
        echo '>' . $label . '</a></li>' ;

    }

?>
<script>
    $(document).ready(function () {
        $(document).on('click', 'ul li a', function () {
            $('li a').removeClass("active");
            $(this).addClass("active");
        })
    });
</script>
</body>
</html>


Answered By - sammysaglam
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing