Menu active current page - javascript

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

Related

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

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

Parameter from <a href></a> to javascript

I have a <ul> <li> menu. When the <a> element inside the <li> is clicked, I need to run a Javascript function and this function needs some parameters like id or name. How can I do it? How can i send/retrieve parameters?
Example Javascript:
function addTab(title, uri) {
var tabNameExists = false;
$('#tabs ul li a').each(function(i) {
if (this.text == title) {
tabNameExists = true;
}
});
Example HTML:
<ul>
<li>W to set parameters
</ul>
link
function addTab(this)
{
$(this).attr('id');
$(this).attr('name');
}
Try
<a href="url" id="someUniqueID" title="SomeTitle" onClick = "addTab(this.title, this.href,this.id);" >link</a>
Your codes are not quite related to your question, anyway, here is the way:
<li>W to set parameters</li>
More logics can be made, depends on how you write some_js_function(id,name).
Note: If you want to fetch the attribute of the <a> or <li> tag , you can go with #PSR's answer.

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