Reputation: 575
I have three separate links for same page.
Based on current page URL considering HASH(#) also, I want to add class in LI and Anchor tag using jQuery code.
Used below code but not working.
<ul class="menu">
<li><a href="https://example.com/faq">faqs</a></li>
<li><a href="https://example.com/assistance#pay_navi_method">payment methods</a></li>
<li><a href="https://example.com/assistance#service_center">service centre</a></li>
<li><a href="https://example.com/assistance#cust_delight">hotline</a></li>
<li><a href="https://example.com/assistance">assistance</a></li>
</ul>
Try 1:
jQuery(window).on('hashchange', function() {
var hash = window.location.hash;
jQuery('a').closest('li').removeClass('called');
jQuery('a[href="' + hash + '"]').closest('li').addClass('called');
});
Try 2:
jQuery(function() {
jQuery('ul.menu li a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('called');
});
Upvotes: 1
Views: 1504
Reputation: 871
You can do this with out jQuery and just use a CSS selector like so:
a[href$="#cust_delight"] { color: red; }
Using the a[href$=""]
selector you can match elements based on the end of the anchors href
value.
In your examples you where using ^
which is begins with, and the other you missed it out - so the selectors wouldn't match
Upvotes: 2
Reputation: 6568
You can do it like this:
<div id="foo">
<a href="#foo">Foo</a>
</div>
<script>
jQuery(document).ready(function()
{
$(window).on('hashchange', function()
{
var hash = window.location.hash.substr(1);
$('a[href="#'+ hash +'"]').closest('div').css('background', 'red')
});
})
</script>
This is an example of the functionality - adjust to suit your code.
Essentially what happens is, on page load - your url most likely won't contain a hash value (unless user is already on page.php#location).
Your first try was extremely close, I just think how you were getting the hash was your fault.
Upvotes: 3
Reputation: 640
You can add class with url as follows
// Fetch current URL
var current_location = window.location.href;
// iterate each <a> of li to add class 'active' to matched element.
$(".menu li").each(function() {
if ($(this).children("a").attr("href") == current_location) {
$(this).addClass("active");
$(this).children("a").addClass("active");
}
})
Upvotes: 1