javascript - update class based on url - javascript

! Latest I've tried. I put it in my head.php which I just include. I'll send over my files if you'd want to see them personally.
Directory of my folder
Main_Folder
-Main_files
-- JS_Folder
---- Js Files
-- Includes_Folder
---- Head.php is here
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
//alert($('ul a').length);
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
}
//alert(this.href);
});
});
</script>
Whole sidebar:
<div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<ul class="sidebar-menu">
<li class="sub-menu">
<a class="" href="panel-admin.php">
<i class="icon-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-briefcase"></i>
<span>Employees</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-book"></i>
<span>Students</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-calendar"></i>
<span>Scheduling</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="admin-foreign.php">Foreign Languages</a></li>
<li><a class="" href="admin-esl.php">ESL Local</a></li>
<li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" class="">
<i class="icon-pencil"></i>
<span>Enroll</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="general.html">Foreign Languages</a></li>
<li><a class="" href="button.html">ESL Local</a></li>
<li><a class="" href="slider.html">Summer Workshops</a></li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
class="sub-menu" is needed to make it dropdown menus drop. So the active version is class="sub-menu active". In case of a 2 level dropdown menu, both the main bar and sub bar are to be set to active.
This is my side bar.
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li>
<i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li>
<i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
I've tried the following below but none works on my case:
Update class attribute based on page URL
https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/
First sample code
$('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu
var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename)
if($(this).prop("href") == pagename){
$('.menu li').removeClass("active"); // remove all active class
$(this).parent("li").addClass("active"); //put active in parent of <a> which is <li>
}
});
In the first one, I've changed the menu to collapse navbar-collapse navbar-ex1-collapse and collapse only but neither works.
In the second sample code, I've tried doing the following:
$(function() {
$('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
});
I put [2] since I'm currently in the localhost. So it would be localhost/folder_name/index.php.
I also tried putting "/index.php"/ but when I click that it directs me to localhost/index.php instead of localhost/folder_here/index.php.
Third sample code
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
Still doesn't work. I've change $('ul a) to $('div ul a) and $('div li ul a).
EDIT: Just to be sure, the script created is just included by include('js/js_file.js');. This line should be before or after the html is loaded?
As suggested by David Thomas I've tried the following below. But it doesn't work.
var url = 'window.location.pathname';
$('.nav a').each(function() {
// get the absolute URL from the <a> element:
var href = this.href,
// get the current page and file-type:
pageAndFile = href.split('/').pop();
// if the location ends with the pageAndFile found in
// the current <a> element (using String.prototype.endsWith())
// we add the 'active' class-name:
if (url.endsWith(pageAndFile)) {
$(this).closest('li').addClass('sub-menu active');
}
});

One approach:
// obviously, use 'document.location'/'window.location' in the real thing:
var fakeLocation = 'http://www.example.com/index.php';
$('.nav a').each(function() {
// get the absolute URL from the <a> element:
var href = this.href,
// get the current page and file-type:
pageAndFile = href.split('/').pop();
// if the location ends with the pageAndFile found in
// the current <a> element (using String.prototype.endsWith())
// we add the 'active' class-name:
if (fakeLocation.endsWith(pageAndFile)) {
$(this).closest('li').addClass('active');
}
});
.active {
border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li> <i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li> <i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
JS Fiddle demo.
For those browsers that don't implement String.prototype.endsWith():
// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
// creates a regular expression from the passed-in string, followed by the '$'
// character which signifies that the passed-in string must be followed by the
// end-of-string:
var reg = new RegExp(testString + '$');
// using RegExp.prototype.test() to test that the String we're testing,
// the 'this,' is matched by the created regular expression:
return reg.test(this);
};
var fakeLocation = 'http://www.example.com/index.php';
$('.nav a').each(function() {
// get the absolute URL from the <a> element:
var href = this.href,
// get the current page and file-type:
pageAndFile = href.split('/').pop();
// if the location ends with the pageAndFile found in
// the current <a> element (using String.prototype.endsWith())
// we add the 'active' class-name:
if (fakeLocation.endsWith(pageAndFile)) {
$(this).closest('li').addClass('active');
}
});
.active {
border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li> <i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li> <i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
JS Fiddle demo.
And, without jQuery, you could do much the same:
// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
var reg = new RegExp(testString + '$');
return reg.test(this);
};
// again, in real-world non-demo use you should use 'document.location':
var fakeLocation = 'http://www.example.com/index.php',
// finding the last portion of the fakeLocation variable:
currentPage = fakeLocation.split('/').pop(),
// getting all the a elements with an href attribute that ends
// with the currentPage string (after escaping the special
// characters with the (ugly) regular expression) and the
// attribute-ends-with ('attribute$=value') selector:
activeAElements = document.querySelectorAll('.nav a[href$=' + currentPage.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + ']');
// using Array.prototype.forEach to iterate over the array-like
// activeAElements NodeList:
Array.prototype.forEach.call(activeAElements, function(a) {
// the first argument of the function is the array-element,
// here an <a> element node;
// we're adding the 'active' class-name to the parentNode of any <a>
// element that was found by the above selector:
a.parentNode.classList.add('active');
});
.active {
border: 1px solid red;
}
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li> <i class="fa fa-fw fa-dashboard"></i> Overview
</li>
<li> <i class="fa fa-fw fa-dashboard"></i> Employees
</li>
</ul>
</div>
JS Fiddle demo.
As to why your own attempts failed:
$('.menu li a').each(function(){
var pagename= location.pathname.split('/').pop();
// the HTMLAnchorElement.href is the absolute URL formed
// by the href attribute; to find the actual string from
// an <a> element, you'd need to use either JavaScript:
// - this.getAttribute('href');
// or jQuery's:
// - $(this).attr('href');
if($(this).prop("href") == pagename){
$('.menu li').removeClass("active");
$(this).parent("li").addClass("active");
}
});
Your second attempt:
$(function() {
// this won't work because your JavaScript will return 'index.php',
// and pass that into the attribute selector; unfortunately this
// includes the period ('.'), which is a special character in CSS
// and has to be double escaped, first for the JavaScript and then
// the CSS
$('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
// with that in mind, you'd need to do (something like) the following,
// which - as in my own code - replaces all special characters with
// a double-escaped version of that character (so '.' becomes '\\.'):
$('nav a[href^="/' + location.pathname.split("/")[2].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '"]').addClass('active');
});
Your third attempt:
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
Looks like it should work, albeit you're adding (or should be adding) the 'active' class-name to the <a> element, rather than the ancestor <li> element.
References:
JavaScript:
Array.prototype.forEach().
Array.prototype.pop().
document.querySelectorAll().
Element.classList API.
Element.getAttribute().
Function.prototype.call().
Guide to regular expressions in JavaScript.
Node.parentNode.
String.prototype.endsWith().
new RegExp() Regular Expression constructor.
RegExp.prototype.test().
String.prototype.split().
jQuery:
addClass().
attr().
each().
prop().

Assuming location.pathname.split("/")[2] returns the expected parameter, the problem is
$('nav a[href^="/'
should be
$('.nav a[href^="'
.nav is a class, not an element, in your example

problem in your script......
$(function() {
$('.nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');t
});

Related

How To Change Color of Current Page Link - HTML / CSS / JavaScript

I'm trying to follow this example.
I've loaded this script:
<script>
// current page highlight
$(document).ready(function() {
$("[href]").each(function() {
if (this.href == window.location.href) {
$(this).addClass("active");
}
});
});
</script>
Into the <head> section for these files: index.html (the home page), about.html, and store.html
For this site. Services won't ever need to be highlighted, and Blog and My Account are currently dead links.
Then I added the corresponding class to my CSS:
.active {
color:#337ab7;
}
So when we're on Home (index.html), the Home link should be #337ab7, when we're on About (about.html), the About link should be #337ab7, and when we're on Store (store.html), the store link should be #337ab7.
But right now, still no result. What do I need to change about the JavaScript, CSS, or HTML to make this function apply?
Here's the HTML for the Nav Menu in question:
EDIT: Added active class to the links in question:
<nav class="navbar navbar-default">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div>
<a class="navbar-brand" href="http://nowordpress.gatewaywebdesign.com/">
<img src="assets/images/gatewaylogo.png">
</a>
</div>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="http://nowordpress.gatewaywebdesign.com/index.html" class="active">Home <span
class="sr-only">(current)</span></a></li>
<li>About</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">
Services
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>Website Design</li>
<li>Graphic Design</li>
<li>Promotional Products</li>
<li>Search Engine Marketing</li>
<li>WordPress Conversion</li>
</ul>
</li>
<li>Store</li>
<li>Blog</li>
<li>My Account</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
And again here is the link for the live site. Thank you.
SOLUTION
For example, the store page:
HTML:
<li><a class="active" href="/store.html">Store</a></li>
CSS: (.navbar-default .navbar-nav > li > a was overriding the .active class, as mentioned by doutriforce)
.navbar-default .navbar-nav > li > a.active {
color: #337ab7;
}
.navbar-button:hover, a.active {
color: #337ab7;
transition: ease-in-out 0.3s;
}
JavaScript:
// current page highlight
// link color code starts
$(document).ready(function () {
console.log("current page", window.location.href);
$("[href]").each(function () {
$('a[href]:not([href=#])').each(function () {
if (window.location.href.indexOf($(this).attr('href')) > -1) {
console.log($(this).attr('href') +" is active ");
$(this).addClass('active');
}
else {
console.log($(this).attr('href') + "is not active ");
}
});
});
});
// link color code ends
Then be sure to change which <a> link gets the active class based on which page is the active page in your file - i.e. if you're editing login.html, then your HTML will look like this:
<li>Store</li>
<li>Blog</li>
<li><a class="active" href="/login.html">Login</a></li>
If you're editing blog.php, then your HTML will look like this:
<li>Store</li>
<li><a class="active" href="/blog.php">Blog</a></li>
<li>Login</li>
And so on.
Finally, in index.html (the home page), be sure to add a span with class sr-only after the link text, like this:
<li><a href="http://nowordpress.gatewaywebdesign.com/index.html">
Home <span class="sr-only">(current)</span></a></li>
To hide the (current) label with Bootstrap.
Your .active class style is being overwritten by the class .navbar-default .navbar-nav > li > a.
You need to change the CSS selector, being more specific, from just .active to .navbar-default .navbar-nav > li > a .active.
About adding class active only to current accessed href. Try this:
$('ul.nav > li > a').each(function(){
var url = window.location.href; //if comparing with full URL
//var url = window.location.href.pathname; //if comparing with page name (ex. /about.html)
var href = $(this).prop('href');
if (url == href) {
$(this).addClass('active');
}
});
Or, as #Mohamed-Yousef answered, you can just write:
$("a[href*='"+ window.location.href +"']").addClass('active');
If you're always comparing full URL to full Href URL.
No need to use .each() you can just use a selector for this
<script>
// current page highlight
$(document).ready(function() {
$("a[href*='"+ window.location.href +"']").addClass('active');
});
</script>
And if you need to know how a[href*='"+ window.location.href +"'] selector work it simply mean find a tag with href contains window.location.href if you change your href a to something like <a href="/website-design.html"> this selctor won't work .. if this is the case you need to use .each() and .indexOf()
<script>
// current page highlight
$(document).ready(function() {
$('a[href]:not([href=#])').each(function(){
if(window.location.href.indexOf($(this).attr('href')) > -1){
$(this).addClass('active');
}
});
});
</script>
about.html:19 Uncaught SyntaxError: Invalid or unexpected token
there is some weird unicode in line 19 that is throwing a parser error. You can see it in chrome's inspector in the "foreach".
Cleaning that up might fix it.

Add/Remove class based on active URL

My HTML code looks like this:
<div id="sidebar-menu" class="main_menu_side hidden-print main_menu">
<div class="menu_section">
<ul class="nav side-menu">
<li>
<a>
<i class="fa fa-home"></i>home
<span class="fa fa-chevron-down"></span>
</a>
<ul class="nav child_menu" style="display: none">
<li>
Dashboard
</li>
<li>
dashbord2
</li>
</ul>
</li>
<li>
<a>
<i class="fa fa-edit"></i>form
<span class="fa fa-chevron-down"></span>
</a>
<ul class="nav child_menu" style="display: none">
<li>
general form
</li>
<li>
form validation
</li>
</ul>
</li>
</ul>
</div>
</div>
to add/remove class based on current url, i am using this:
$(function () {
var url = window.location.href;
$('#sidebar-menu a[href="' + url + '"]').parent('li').addClass('current-page');
$('#sidebar-menu a').filter(function () {
return this.href == url;
}).parent('li').addClass('current-page').parent('ul').slideDown().parent().addClass('active');
});
It works, but when i click this link
dashbord2
the class="current-page" doesn't change to current path url
How i fix this?
Your issue arises from the page not being reloaded when you click on the link with hash in it, while your code only executes on page load, or dom ready to be exact. The solution is to whether use window's hashchange event (not supported in < IE8) or, like #sirrocco mentioned, use click event with setTimeout to detect the change of hash:
function setCurrentMenuPage() {
var url = window.location.href;
var anchors = $('#sidebar-menu a');
anchors.parent('li').removeClass('current-page');
anchors.filter(function () {
return this.href == url;
}).parent('li').addClass('current-page').parent('ul').slideDown().parent().addClass('active');
}
$(function () {
setCurrentMenuPage();
$('#sidebar-menu a').on('click', function (e) {
if ($(this).attr('href').indexOf("#") >= 0) {
setTimeout(function () {
setCurrentMenuPage();
}, 100);
}
});
});
Hope that helps.

jQuery - using the same function (ToggleNav/Dropdown) on multiple ID's

I'm trying to make multiple dropdown menu's on my website and I am using this jQuery for this:
$(function() {
var pull = $('#pull');
menu = $('#nav');
menuHeight = menu.height();
$(pull).on('click', function(e) {
e.preventDefault();
menu.slideToggle();
});
});
Here's the html part:
<nav class="container">
<a href="#" id="pull" style="display:block;">
<h3>Menu</h3>
</a>
<ul id="nav" style="display:none;">
<li>Pizza</li>
<li>Pasta</li>
<li>Burger</li>
<li>Specials</li>
<li>Drinks</li>
</ul>
</nav>
It works wonderful if I only have one drop down menu but as soon as I add another one, only one of them (doesn't matter if it's two, three or more then) is actually dropping down.
I gave every Menu it's own ID and copied the code every time and replaced the ID's but this doesn't work.
Already looked into this (using the same function of different events ) or this (Jquery - use the same function for multiple requests) and other threads but i can't figure out how to apply this on my code...
Here's my Jsfiddle on what I'm trying to do: https://jsfiddle.net/thwdyccr/2/
Use classes instead of ids, and then you can make the same code work for all cases (fiddle):
$(function () {
var pull = $('.pull');
$(pull).on('click', function (e) {
e.preventDefault();
var menu = $(this).next();
menu.slideToggle();
});
});
<nav class="container"> <a href="#" class="pull" style="display:block;">
<h3>Menu1</h3>
</a>
<ul class="nav" style="display:none;">
<li>Pizza
</li>
<li>Pasta
</li>
<li>Burger
</li>
<li>Specials
</li>
<li>Drinks
</li>
</ul>
</nav>
<nav class="container"> <a href="#" class="pull" style="display:block;">
<h3>Menu2</h3>
</a>
<ul class="nav" style="display:none;">
<li>Pizza
</li>
<li>Pasta
</li>
<li>Burger
</li>
<li>Specials
</li>
<li>Drinks
</li>
</ul>
</nav>
Try this:
https://jsfiddle.net/thwdyccr/5/
Rather than using IDs - consider using a class instead - this'll save you lots of duplication in your code (as essentially it's all doing the same thing).
You can specify the target selector (e.g. the element you want to show) by traversing your structure with .parent() .children() or .find()
If you're wondering why I am storing $(this) in var element - it is because the browser has to figure out what $(this) is each time you use it - so it's good practice to store it in a variable.
HTML
<nav class="container">
<a href="#" class="pull" style="display:block;">
<h3>Menu1</h3>
</a>
<ul class="nav" style="display:none;">
<li>Bear</li>
<li>Pasta</li>
<li>Burger</li>
<li>Specials</li>
<li>Drinks</li>
</ul>
</nav>
<nav class="container">
<a href="#" class="pull" style="display:block;">
<h3>Menu2</h3>
</a>
<ul class="nav" style="display:none;">
<li>Fish</li>
<li>Pasta</li>
<li>Burger</li>
<li>Specials</li>
<li>Drinks</li>
</ul>
</nav>
JS
$(function() {
$(".pull").click(function(e) {
e.preventDefault();
var element = $(this);
element.parent('nav.container').children("ul.nav").slideToggle();
});
});
You shouldn't use id's for pull. Here's an updated fiddle https://jsfiddle.net/thwdyccr/2/.
Try utilizing Attribute Starts With Selector [name^="value"] [id^=pull] , e.target.parentElement.nextElementSibling to select next ul to call .slideToggle() on
$(function() {
var pull = $("[id^=pull]")
, menu = $("[id^=nav]")
, menuHeight = menu.height();
pull.on("click", function(e) {
e.preventDefault();
$(e.target.parentElement.nextElementSibling).slideToggle();
});
});
jsfiddle https://jsfiddle.net/wpvok7gy/1/

Clickable li but another li not clickable

I'm trying to figure this out, but for the life of me I'm confused. I have this:
<!-- Sidebar Menu -->
<ul class="sidebar-menu">
<li class="header">HEADER</li>
<!-- Optionally, you can add icons to the links -->
<li class="active"><a href="res/link.php"><i class='fa fa-link'></i>
<span>Links</span></a></li>
<li><i class='fa fa-link'></i> <span>Another Link</span></li>
<li class="treeview">
<a href="#"><i class='fa fa-link'></i>
<span>Multilevel</span> <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>Link in level 2</li>
<li>Link in level 2</li>
</ul>
</li>
</ul><!-- /.sidebar-menu -->
and my javascript:
var hash = window.location.hash.substr(1);
var href = $('.sidebar-menu li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-10)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
$('.sidebar-menu li a > .treeview li a').click(function(){
and I'm having trouble with this line:
$('.sidebar-menu li a > .treeview li a').click(function(){
I want the sidebar-menu menu clickable for all li's with a tags however when I click on the treeview menu, it fires up as an href link. I don't want that clickable.
Am I using the greater than less than symbols correctly in my JavaScript?
use this to prevent default href action
$(your selector).click(function(e) {
e.preventDefault();
// e for event
// preventDefault will stop default href action
});
edit: or you can handle all # links with this selector and preventDefault
$('.sidebar-menu a[href="#"]').click(function(e){
e.preventDefault();
});
selector a[href="#"] will select only A-tags with param href == "#", then just use preventDefault() on them to stop default href action
If you want only elements directly under your selector, use >.
This will select only a tags directly in the li tags that are directly in the sidebar-menu:
$('.sidebar-menu > li > a')
Your first onclick can look like this:
var href = $('.sidebar-menu > li > a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-10)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
Your second one can just look like this:
$('.treeview li a').click(function(){
// do stuff.
});
It depends on how much nesting you'll do, but this will apply to all a tags in your treeview, regardless of nesting level.
EDIT:
I see you didn't want the tree clickable at all. In that case, you shouldn't use the a tag at all. Use something like a span with styling that makes it look like a link. Links (a) go somewhere. If you aren't going somewhere, don't use the a.
fiddle: https://jsfiddle.net/6njj7L9g/2/
snippet:
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('.sidebar-menu li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-10)){
var toLoad = hash+'.php #content';
$('#content').load(toLoad)
}
});
$('.sidebar-menu > li > a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
.treeLink{
text-decoration: underline;
color: blue;
cursor: pointer;
}
<!-- Sidebar Menu -->
<section>
<ul class="sidebar-menu">
<li class="header">HEADER</li>
<!-- Optionally, you can add icons to the links -->
<li class="active"><a href="res/link.php"><i class='fa fa-link'></i>
<span>Links</span></a></li>
<li><i class='fa fa-link'></i> <span>Another Link</span></li>
<li class="treeview">
<a href="#"><i class='fa fa-link'></i>
<span>Multilevel</span> <i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li><span class="treeLink">Link in level 2</span></li>
<li><span class="treeLink">Link in level 2</span></li>
</ul>
</li>
</ul><!-- /.sidebar-menu -->
Make href="" and not href="#" if you don't want it to be click-able.

Why does this work? window.location.href

Example link: http://localhost/test/page.php?success
I'm curious about this. And I'm also new to JavaScript so it's not really a surprise but I understand the code below, I just do not know why it works away with what I seem to understand. See this question for more reference.
I have this JavaScript:
<script type="text/javascript">
jQuery(function($) {
var path = window.location.href.split( '?' )[0];
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('sub-menu active');
$(this).parent().closest("li").addClass('active');
$(this).parent().parent().closest("li").addClass('active');
}
});
});
</script>
The Sidebar:
<li class="sub-menu"> // Sidebar with no submenu
<a class="" href="page1.php">
<i class="icon-calendar"></i>
<span>This is page 1</span>
</a>
</li>
<li class="sub-menu"> // Sidebar with a submenu
<a href="javascript:;" class="">
<i class="icon-group"></i>
<span>This has sub pages</span>
<span class="arrow"></span>
</a>
<ul class="sub">
<li><a class="" href="page2.php">This is page 2</a></li>
<li><a class="" href="page3.php">This is page 3</a></li>
</ul>
</li>
The code puts an active class to the menu on the sidebar which href is equals to the current url. But window.location.href returns the whole url but what is inside the href's are just the page.php. So why does this.href === path work? When window.location.href.split( '?' )[0] returns http://localhost/test/page.php and the href is just page.php.
The href property of an anchor is normalized to an absolute value.
See this example:
HTML:
Test
JS:
var a = document.querySelector('a');
console.log(a.href);
In this instance the relative URL is being resolved to the location of the document containing the a element. You can use the base element to control the resolution of relative URLs.

Categories

Resources