Search code examples
javascriptjqueryurlhref

Jquery / Javascript Solution for URL matches Href then add a Class


So, i got a basic page where i need to highlight where my user is. Got a Nav with ul > li > a

my ideia is to get the URL of the current page, and match with one specific href of one "a".

The structure :

   <header>

<a href="#" id="toggle-nav"><span class="trigger"></span></a>

<nav>
    <ul id="nav-top">
        <li><a href="../Index/Index.html" title="Home">Home</a></li>
        <li><a href="#" title="#">Aluno</a>
            <ul class="sub-menu">
                <li><a href="../Index/areadoaluno.html" title="Area do Aluno">Area Do Aluno</a></li>
                <li><a>sub-item</a></li>
                <li><a>sub-item</a></li>
            </ul>
        </li>
        <li><a href="#">Json</a>
            <ul class="sub-menu">
                <li><a href="Json.html" title="Teste Json">Json Teste</a></li>
                <li><a>sub-item</a></li>
                <li><a>sub-item</a></li>
            </ul>
        </li>
    </ul>
</nav>
</header>

and the jquery with javascript (Its ok to mix this two guys ? ):

var url = window.location.pathname.split( '/' );
var i;
var location = "";

for(i = 0; i < url.length; i++)
    {
        location += url[i];     
    }


    $('#nav-top a').each(function(){

    var href = $(this).attr('href'); 

        if( location.indexOf(href) > -1 ) 

        {
            alert("Yes!");

        } 

    });
});

Im studing Jquery and jscript yet, so im kind of new, im working with a solution that can find and match one part of my url with an specific href, idependent of the size of the url, and for where i go.


Solution

  • Working jsfiddle

    I think you could just do as is shown. No need to loop through url and no need for extra variable location.

    var url = window.location.pathname.split('/');
    
    $('#nav-top a').each(function() {
        var href = $(this).attr('href'); 
        if (url.indexOf(href) > -1) {
            alert("Yes!");
        } 
    });
    

    And yes, it's perfectly okay to mix jQuery and JS. jQuery is a JS library so that's what it's made for