Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I managed to make it but got some minor hiccup. Currently, the active class been added to current URL including the All Watches link (maybe because the URL is the homepage URL).

May I know what I need to author for the script to work exactly as what the current URL looks like.

This is the HTML codes.

<div class="tagcloud">
<ul class="tag-widget">
    <li>
    <a href="http://effectiveadvisory.com/wingwah-may/">All Watches</a>
    </li>
    <li>
    <a href="http://effectiveadvisory.com/wingwah-may/product-tag/military/">Military</a>
    </li>
    <li>
    <a href="http://effectiveadvisory.com/wingwah-may/product-tag/diver/">Diver</a>
    </li>
    <li>
    <a href="http://effectiveadvisory.com/wingwah-may/product-tag/pilots/">Pilots</a>
    </li>
    <li>
    <a href="http://effectiveadvisory.com/wingwah-may/product-tag/racing/">Racing</a>
    </li>

</ul>

</div>


This is the JQuery codes.

jQuery(document).ready(function($){
$("#custom_html-2 a")
.filter(function(){ 
return location.href.match($(this).attr("href"))
})
.addClass("tag-active");
});


What I have tried:

Some googling and posted help at stackoverflow. But no response.

I think the problem lies in the filter function. I think I need to make the current URL match exactly as the href link. But I've no idea how.
Posted
Updated 26-Jun-18 7:35am

1 solution

The match method[^] takes a regular expression as its argument, and either returns an array containing the matches, or null.

Your href is not a regular expression, but since it doesn't contain any special characters, it will act like one. It doesn't contain any anchoring clauses, so your match call will return a match if the URL contains the specified value.

Since all of the URLs you've shown contain the "All watches" URL, that one will always be marked as active.

To compare the full URL, use the equality operator:
JavaScript
$(function(){
    $("#custom_html-2 a").filter(function(){ return location.href === this.href; }).addClass("tag-active");
});
 
Share this answer
 
Comments
Member 13884629 26-Jun-18 22:14pm    
Thanx it works.

Im wondering how you guys know what the syntax means?
Is there any cheat sheet or you guys just know it from experience?
Richard Deeming 27-Jun-18 7:23am    
Mainly experience. Lots and lots of experience! :)

MDN is a pretty good reference:
JavaScript reference - JavaScript | MDN[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900