Set menu item active based on URL - javascript

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/

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>

Active class nav item based on retrieved url portion

I would like to add a css class (.active) on the appropriate navigation link.
My navigation:
<nav>
<ul>
<li id="Thuispagina">Thuispagina</li>
<li id="Nieuws">Nieuws</li>
<li id="Skirms">Skirms</li>
<li id="Reservatie">Reservatie</li>
<li id="Fotogalerij">Fotogalerij</li>
<li id="Contact">Contact</li>
<li id="Forum">Forum</li>
</ul>
</nav>
If I would be on one of the following pages: domain.com/airsoft-contact/index.php, domain.com/airsoft-contact/edit.php or domain.com/airsoft-contact/delete.php it should add the active class to the li item with id Contact
If I would be on one of the following pages: domain.com/airsoft-fotogalerij/index.php, domain.com/airsoft-fotogalerij/edit.php or domain.com/airsoft-fotogalerij/delete.php it should add the active class to the li item with id Fotogalerij
On the other hand there is one exception: the index.php page is not in any submap so the logic should make an exception there.
Well the better or simple way is using jquery but u can do it with php too using a condition example class="<?php if ($_SERVER['PHP_SELF']=="ur script name"){ echo "active";}?>" or u can use ternary operator for better views so this is a way, u can find others
The easiest way to implement this (if you aren't an expert user) is to add in the navigation element a js like this for every link
if(window.location.href == "yourlink"){
document.getElementById("elementid").class = "active";
}
Another way can be something like:
var links = [ new Link("yoururl1", "yourelement1"), new Link("yoururl2", "yourelement2"), new Link("yoururl3", "yourelement3")];
for(link in links){
if(link.url == window.location.href){
document.getElementById(link.elementid).class = "active";
}
}
function Link (url, elementid){
this.url = url;
this.elementid = elementid;
}

Menu active current page

I'm using Bootstrap (AdminLTE) and I want to make the current page's menu item active.
Problem is, I don't know how to do it.
I do have a few solutions in mind (besides changing it in every php file), like putting an IF statement for every link, which would be a terrible solution (I think).
<ul class="sidebar-menu">
<li class="header">HOOFD MENU</li>
<li class='treeview'>
<a href='#'>
<i class='fa fa-dashboard'></i> <span>Dashboard</span>
<span class='pull-right-container'>
<i class='fa fa-angle-left pull-right'></i>
</span>
</a>
<ul class='treeview-menu'>
<li><a href='account.php'><i class='fa fa-circle-o'></i>Account</a></li>
</ul>
</li>
</ul>
The above is part of the menu.
So the menu item (in this case Dashboard) and sub-menu item both have to become active.
Thanks in advance!
Try this. This was copied from other bootstrap admin template and modified for AdminLTE
<script>
$(document).ready(function() {
var url = window.location;
var element = $('ul.sidebar-menu a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0; }).parent().addClass('active');
if (element.is('li')) {
element.addClass('active').parent().parent('li').addClass('active')
}
});
</script>
This solution work with sublevel menu. Need JQuery
<script type="text/javascript">
$(document).ready(function () {
var url = window.location;
var element = $('ul.sidebar-menu a').filter(function () {
return this.href == url || url.href.indexOf(this.href) == 0;
});
$(element).parentsUntil('ul.sidebar-menu', 'li').addClass('active');
});
</script>
In one simple line:
$("ul.sidebar-menu li a[href='"+document.location.pathname+"']").parents('li').addClass('active');
So you should always check to make sure the element exists so you don't get any errors and you can user jQuery's data attribute selector to easily target the correct links.
var href = window.location.pathname;
if( $(".sidebar-menu a[href='"+href+"']").length ) {
$(".sidebar-menu a[href='"+href+"']").parent('li').addClass('active');
}
If you are using absolute urls you may need to switch from .pathname to .href in the var

Sometimes on click executed twice

I'm having a very strange problem. Basically I have created a menu in wordpress that has parent, childs, subchilds and inside some posts.
I wrote a jquery script that adds a highlight class on the <li> in order to expand the <ul> which is inside the <li>. the format of the list is the following
<li class"menu-item-has-children"><a>Parent</a>
<ul>
<li class="menu-item-has-children"><a>Child</a>
<ul>
<li class="menu-item-has-children"><a>Sub Child</a>
<ul>
<li><a> post</a></li>
<li><a> post 2 </a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
So I wrote the following script to add highlight class to expand the sub child of the clicked <li>. When I'm clicking on any <li> of parent,child, sub child is working fine but when I click on the posts it removes the highlight class from the parent <ul> instead of taking me to the page of the clicked post.
I did a console log of $(this) and when click on any parent, child,sub child it shows me <ul> that has, but when I click on any posts it shows me first the <a> tag that it has followed by the parent <ul>. Does anyone know why?
Here is my jquery code
$(document).unbind("click").on('click',".sidebar-right li",function(e){
var found = false;
var tmp = String($(this).val());
if (tmp.indexOf("ul") != -1){
found = true;
}
if (($(this).hasClass("menu-item-has-children")) && (!$(this).children('ul').hasClass("highlight")))
{
$(this).children("a").addClass("highlight_icon");
$(this).children('ul').addClass("highlight");
return false;
}
else if (($(this).has("a") && ($(this).has("ul"))) && (!$(this).children('ul').hasClass("highlight")))
{
return true;
}
else if ($(this).children('ul').hasClass("highlight"))
{
$(this).children('a').removeClass("highlight_icon");
$(this).children('ul').removeClass("highlight");
return false;
}
else
{
return true;
}
});
Here is the console log data
Child Parent etc
Post click
SOLUTION: event.stopPropagation() as #mohamed-yousef said
try
$(".sidebar-right").on('click',".sidebar-right li", function(){
....});

Add Active Class for any URL match to first segment?

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);
}
});
});

Categories

Resources