Add Active Class for any URL match to first segment? - javascript

My Javascript is adding the active class to all links with one segment that match my path variable, but not ones with two on my nav.
I want it regardless to check the first segment of any URL that is currently in the window.location.pathname and if the first segment matches then add the active class to the nav item.
It works for home, products and gallery. But when I console.log(linkPath) it's showing for the url products/samples the text sample and not products. Thus there is no math and it will not add the active class to the current item.
How Can I get it to add the active class no matter what based off the first segment matching within any url with more than one segment?
HTML
<nav class="navbar" role="navigation">
<h2 class="markup">Main Navigation</h2>
<div class="collapse navbar-collapse main-nav-list navbar-link-background">
<ul class="nav navbar-nav">
<li>Home
</li>
<li>Products
</li>
<li>Gallery
</li>
<li>Promotions
</li>
<li>Samples
</li>
</ul>
</div>
</nav>
Javascript
var url = window.location.pathname.split( '/' ),
path = url[1];
/* Get URL For Setting Active Nav List Item */
$(".navbar-nav").children("li").each(function() {
var link = $(this).children("a").attr("href"),
linkPathIndex = link.lastIndexOf("/")+1,
linkPath = link.substring(linkPathIndex);
if (linkPath == path) {
$(this).addClass("active");
}
});

Why dont you check for the pathname directly in the link href? something like this:
$(".navbar-nav").children("li").each(function() {
var link = $(this).children("a").attr("href");
if(link.indexOf(path) > -1){
$(this).addClass("active");
return;
}
});

This is what I use:
this.win.on(events.load, function() {
var anchors = self.list.prev().find(cache.anchor),
url = document.URL;
$.each(anchors, function() {
var anchor = $(this),
href = anchor.prop('href');
if (url.indexOf(href) !== -1) {
anchor.addClass(classes.active);
}
});
});

Related

Keep active class on gallery navigation when using pagination

I have the following navigation on the gallery page of my website that allows users to filter the images by category.
<ul>
<li>All</li>
<li>Our Gym</li>
<li>Our Classes</li>
<li>Our Coaches</li>
</ul>
I've added the following snippet to add the class 'active' the category that is currently being viewed by the user.
<script>
jQuery(function($) {
var path = window.location.href;
$('.gallery_listing_wrapper li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
This works for the above gallery navigation however once I navigate using the pagination it doesn't work.
The URL for the pagination is slightly different to the gallery and its categories.
For example - instead of /gallery/our-gym/ - page/ and the page number is added to the URL i.e. /gallery/page/2/
Is it possible to adjust the above snippet to keep the active class on All when the pagination is being used?
You could always just add the class to the "All" button if none of the other buttons match the current URL.
<script>
jQuery(function($) {
var path = window.location.href;
let match = $(`.gallery_listing_wrapper li a[href="${path}"]`);
if(match.length >= 1)
match.addClass("active");
else
$(".gallery_listing_wrapper li a[href='/gallery/']").addClass("active");
});
</script>

Add active Menu or Navigation class based on URL

I've added an active class to my menu items. However my current implementation is adding the class to all list menu items as opposed to whatever the current page is.
Please let me know if there is an issue with my current code, and what I can do to achieve the desired outcome.
<ul id="menu_items">
<li class="has-sub">STORE</li>
<li>RESEARCH</li>
<li>INFO</li>
</ul>
$(function(){
var current = location.pathname;
$('#menu_items li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
.active {text-decoration:underline;}
Okay, Try this way, hope it will work
<ul id="menu_items">
<li>Index</li>
<li class="has-sub">STORE</li>
<li>RESEARCH</li>
<li>INFO</li>
</ul>
</html>
<Script>
$("#menu_items li").bind("click", function(e){
$("li").click(function() {
$(this).siblings().find("a").removeClass("active");
$(this).find("a").addClass("active")
})
})
</Script>
Please Check the URLs , All the Links are "/collections"

Set menu item active based on URL

I've been trying really hard to accomplish what I'm trying to accomplish, but I can't get it to work the way I want. I have a navigation menu with first-level menu items (duh) and second-level menu items. It looks like this:
<ul class="nav" id="side-menu">
<li>
Dashboard
</li>
<li>
Pages
</li>
<li>
Users<span class="fa arrow"></span>
<ul class="nav nav-second-level">
<li>
All users
</li>
<li>
Roles
</li>
</ul>
</li>
</ul>
I'm using the following jQuery function to add the active class to active menu items:
function setActive() {
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
// Remove active class from A element if the page isn't the dashboard.
if (location.pathname !== '/admin/' && $('[href="/admin/"]').hasClass('active')) {
$('[href="/admin/"]').removeClass('active');
}
};
This works fine for all first-level menu items and for the second-level menu item All users, but when I go to /admin/users/roles/, it makes All users and Roles active. The same thing happens when I go to /admin/users/roles/add/. I think this happens because the code makes all menu items active which look like the window.location, but I don't know how to only make Roles active when I go to /admin/users/roles/ and /admin/users/roles/add/, etc.
I really hope someone can help me with this. If you can, I'll buy you a beer.
try this..
var loc = window.location.pathname;
$('#side-menu').find('a').each(function() {
$(this).toggleClass('active', $(this).attr('href') == loc);
});
and ue full absolute path in href i.e.http://yourdomain.com//admin/users/roles/

Addclass to Menu Jquery

I am trying to add a class dynamicly to the menu I have on my website, which is build up as followed.
<nav>
<ul id="" class="mini-menu">
<li>Home</li>
<li>Over Jellyfish</li>
<li>Blog</li>
<li class="contact">Contact</li>
</ul>
<ul class="hoofd-menu">
<li class="websites"><a id="dekstop_menu" href="websites"><i class="fa fa-desktop text-center"></i>Websites</a></li>
<li class="support"><a id="support_menu" href="support"><i class="fa fa-comment-o text-center"></i>Support</a></li>
</ul>
</nav>
with Jquery I am tryint to add the class active to the mini-menu by doing the following steps.
jQuery(function() {
var str = window.location.pathname;
var page = str.split("/");
p=page[2];
var active = p=page[2];
console.log(active);
jQuery('.mini-menu a').each(function() {
if (jQuery(this).attr('href') === active) {
jQuery(this).addClass('active');
}
});
});
Yet i seem to miss something here, cause nothing shows up within the html as adding a class to the link. Am I missing the fact that the link is not a direct child of the class mini-nav? If so, how do I fix this?
Can you try this :
jQuery(function() {
var str = window.location.pathname;
var page = str.split("/");
p=page[2];
var active = p=page[2];
console.log(active);
jQuery('.mini-menu a').each(function() {
(function (self) {
if (jQuery(self).attr('href') === active) {
jQuery(self).addClass('active');
}
})(this);
});
});

Programmatically adding nav bar element in jQuery Mobile

I can create a 2 item nav bar in a jQuery mobile page with the following code snippet:
<div id="nav-bar" data-role="navbar">
<ul id="nav-list">
<li><a id="link1" href="#">Nav 1</a></li>
<li><a id="link2" href="#">Nav 2</a></li>
</ul>
</div>
I am attempting to programatically add a third nav bar element using various versions of the following code:
$("#nav-list").append("<li><a id='newElement' href='link3'>Nav 3</a></li>");
$("#nav-bar").navbar();
//$("#pageName").page();
//$("#pageName").trigger("create");
//$("#nav-list").listview("refresh");
When I execute this I see the "Nav 3" link appear but it does not take on the jQuery mobile formatting of the other links.
Any help would be greatly appreciated.
You should append your HTML in a pagebeforecreate handler before JQM's enhancement starts.
I had lost my mind because of this problem. .navbar() used to work in previous versions, for some reason not any more.
I have made a function whose job is to add a new element and then rebuild navbar. One part of it is taken from someone else so I cant take full responsibility for this code (mathod used for style stripping).
Here's working example: http://jsfiddle.net/Gajotres/V6nHp/
And here's a method used:
var navbarHandler = {
addNewNavBarElement:function(navBarID, newElementID, newElementText) {
var navbar = $("#" + navBarID);
var li = $("<li></li>");
var a = $("<a></a>");
a.attr("id", newElementID).text(newElementText);
li.append(a);
navbar = navbarHandler.clearNavBarStyle(navbar);
navbar.navbar("destroy");
li.appendTo($("#" + navBarID + " ul"));
navbar.navbar();
},
clearNavBarStyle:function(navbar){
navbar.find("*").andSelf().each(function(){
$(this).removeClass(function(i, cn){
var matches = cn.match (/ui-[\w\-]+/g) || [];
return (matches.join (' '));
});
if ($(this).attr("class") == "") {
$(this).removeAttr("class");
}
});
return navbar;
}
}

Categories

Resources