Select active link

How can I highlight the active link when I click, but keep the link of the main page until another link is clicked?

I use PHP if this helps.

Here is my (x) HTML code.

<div id="nav">
    <ul>
        <li><a href="http://localhost/link-1/" class="active">Link 1</a></li>
        <li><a href="http://localhost/link-2/">Link 2</a></li>
        <li><a href="http://localhost/link-3/">Link 3</a></li>
        <li><a href="http://localhost/link-4/">Link 4</a></li>
    </ul>
</div>
+3
source share
3 answers

I'm out of place to check this out right now, let me know if this works for you.

var menuArray = new Array();

$(function() {


    $('div#nav ul li').each(function(i) {
        menuArray[i] = this;
        $(this).click(function() {
            for (var x in menuArray)
                if (x == this)
                    $(x).attr('class','active');
                else
                    $(x).attr('class','inactive');
        });
    });
});

EDIT is fine, I was able to verify this and it works for me. Keep in mind that this should be after your HTML declaration.

$("li a").each(function(i) {
        $(this).click(function() {
             $(this).attr('class','selected');
             $("li a").not(this).attr('class','notselected');
        });
});
+2
source

You can make a method in php, here is an example:

<div id="nav">
    <ul>
        <li><a href="http://localhost/link-1/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-1')?>>Link 1</a></li>
        <li><a href="http://localhost/link-2/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-2')?>>Link 2</a></li>
        <li><a href="http://localhost/link-3/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-3')?>>Link 3</a></li>
        <li><a href="http://localhost/link-4/" <?=$activateLink($_SERVER['REQUEST_URI'],'/link-4')?>>Link 4</a></li>
    </ul>
</div>
<?php
function activateLink($uri,$var) 
{
    if($uri==$var) {
        return 'class="active"';
    }
}
?>

On each page, type $ _SERVER ['REQUEST_URI'] and pass the second parameter to the method.

+2
source

PHP, PHP. , HTML/CSS.

CSS/HTML ( ):

<style>
       .active {
             color:#336699;
       }

       div#nav ul li a {
             color:#121212;
       }

       div#nav ul li a:visited {
             color:#336699;
       }
</style>

This should color all links blue if they have been visited, and if they will not, it will be dark gray. However, if you want to select only one link, it is best to use jQuery, since it has many functions to select only the one that is selected.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1759370/


All Articles