Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Nov 2009
    Posts
    200
    Thanks
    23
    Thanked 0 Times in 0 Posts

    Highlight the active link in a navigation menu

    I wonder if the script is all right. Please review my code:

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Menu</title>
    <style>
    ul {list-style-type:none; margin:0; padding:0;}
    li {display:inline;}
    a.active {background:red;}
    </style>
    </head>
    <body>
    <ul>
    <li><a href="http://www.example.com/home">Home</a></li>
    <li><a href="http://www.example.com/news">News</a></li>
    <li><a href="http://www.example.com/contact">Contact</a></li>
    <li><a href="http://www.example.com/about">About</a></li>
    </ul>
    <script>
    for (var i = 0; i < document.links.length; i++) {
        if (document.links[i].href == document.URL) {
            document.links[i].className = 'active';
        }
    }
    </script>
    </body>
    </html>
    It should highlight the current page link in the navigation bar.

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,875
    Thanks
    6
    Thanked 1,034 Times in 1,007 Posts
    Don’t use JS for that. Why would you do that anyway? If you have static HTML pages every page has the menu and you would just add the class in the HTML. If you have dynamic pages compiled by a server side script (e. g. PHP) then use PHP to add the class.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •