Setting active link dynamically on static navigation - javascript

I have "navigation.html" (static coded navigtaion ) file loaded on multiple pages, using jQuery .load()
Now I need to dynamically set active <li> for each page user clicking on. I can not use body id for specific reasons.
Any other ways to do this?

If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation.
changeActiveLink is defined in JS (ex:init.js) file which you include to each page
function changeActiveLink() {
var currentLocation = window.location.href;
currentLocation = currentLocation.replace('//', '/').split('/');
var page = currentLocation[currentLocation.length - 1];
if (page == "") { page = 'index.html'; }
$('#leftNav1 a[href*="'+ page +'"]').addClass('active');
}
This line is called from each file when "init.js" is included.
$('#leftNav1').load('navigation.html', changeActiveLink);

Or you can use any HTML or even HTML5 tag to specify li item.
<li class="some">
or
<li title="some">
or
<li attr-specify="some-specific-in-url">
and jQuery with window.location object
$('li[title="' + window.location.path + '"]').addClass("active");

You could set up some jquery script to get the url and then find the href of the li that matches that. This will allow you to addClass() to that li of active.
This of course will only work if your href matches the url

Related

Dynamically change href and link to a url fragment

Hope someone can help.
I'm trying to dynamically change hrefs on a page and then point the user to a url which includes a fragment as:
$(document).ready(function(){
if (document.location.pathname.indexOf('cab2') > -1){
document.getElementsByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab2/#linkResources');
} else {
document.getElementByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab/#linkResources');
};
});
In the HTML I'm using several links like this:
<a class="resourceLink" href="" title="Link to Resources section" target="_blank">Resources</a>
What I was hoping for was the script would check what url the visitor had used to arrive at the site, either
http://www.myserver.net/cab/ or,
http://www.myserver.net/cab2/ and then set the appropriate hrefs to either:
http://www.myserver.net/cab/#linkResources or,
http://www.myserver.net/cab2/#linkResources
What happens though is the link opens up the base page (www.myserver.net/cab or cab2) and not the #fragment page.
What am I doing wrong?
My thanks for your interest.
.getElementsByClassName() returns an HTMLCollection, not a single element. You can use .each() to iterate all .resourceLink elements, .attr() to set href attribute value
$(document).ready(function(){
var link = document.location.pathname.indexOf('cab2') > -1 ? "cab2" : "cab";
$('.resourceLink')
.each(function() {
$(this)
.attr('href','http://www.myserver.net/'+ link +'#linkResources')
});
});

Active class added to a wrong document object in a menu

Here is my JS code which add an active class to the parent of all <a> objects which contain a href path who match with my current URL.
aObj = document.getElementById('menuG').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
alert("Button n°"+i+" - Value : "+document.location.href.indexOf(aObj[i].href));
aObj[i].parentElement.className='active';
}
}
My problem is that the first button which have href="/" is always active.
The code document.location.href.indexOf(aObj[i].href) always return 0 for the first button and i don't understand why.
Here is my html code :
<ul class="nav navbar-nav" id="menuG">
<li>Mes Fichiers</li>
<li>Historique</li>
<li>Profil</li>
</ul>
Thanks for your time.
Any URL will most likely contain the / of that first link tag. If you use indexOf(), it will find the / in any page of your website. Hence, that first link's parent will always get styled.
You can test it for yourself in the console of your browser. In an HTTPS website, the first match of / is in position 6 (7th character in a URL). indexOf just returns the position of the first match, and the / that's the href of your first link will always get a match.
You could replace the href of the first link with something like index.html, and then force a redirect from http://example.com to http://example.com/index.html. Your other bet is to change the way you check if this is the current page, by, for example, checking if window.location.href is strictly equal (===) to the href of a link tag: window.location.href === aObj[i].href.

Converting CSS template to asp.net with masterpages

I bought an css template.
which implements navigation such that.
<li class="current">Services</li>
<li>News</li>
<li>Portfolio</li>
<li>Elements</li>
<li>Contact</li>
It contains navigation tag in every html file and mark the list item class as current for the current page.
Now i am converting this into master page layout.
How can i detect current page and add class to the list item with JavaScript.
Or any other solution to this problem.
This is one simple way to do this (using jQuery):
function syncMenu () {
var url = window.location.href, pageStart, pageEnd, pageName;
pageStart = url.lastIndexOf("/") + 1;
pageEnd = url.lastIndexOf(".");
pageName = url.substring(pageStart, pageEnd);
$('#Menu').find('li').removeClass('selected');
$('#Menu').find('a[href^="' + pageName + '"]').parent().addClass('current');
}
Call this function as the first thing when your page loads i.e. first thing in document.ready.
The idea is that you have the name of the page as the anchor href. We retrieve the page name from the current url and use that to search the a in all lis which contains that page name as its href. Add a class (current in your case) to that li.

jQuery Make a Link in Active Status

I am working on a HTML template, but I cannot touch the HTML code, I can only work on CSS and JS files. So I cannot in any way edit the HTML code.
What I am trying to achieve is to put some links in active status when jQuery or Javascript recognizes that the current page URL is the same one of the link I want to put in active status, without editing the HTML code.
Is there a way to do it? I tried in many ways but with no luck.
Here is the HTML code ( Remember I cannot edit it ).
<span class="Tag_Nav_Aux">
Create Account
|
Login
|
My Cart
</span>
The jQuery or Javascript code should work on different links, other than the ones I reported above, since the HTML changes when the user is logged in or logged out.
So the jQuery should point the class Tag_Nav_Aux and add the Active class to any a tag it will find that has the link the same of the current URL.
You can do something like this. Your file name from the URL
var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
After that get the anchor from the navigation and apply some class.
$("span.Tag_Nav_Aux a[href*="+filename+"]").addClass('active');
Here you have to write a CSS active class which will make that link to appear like an active link.
Try this script
jQuery(function($){
$('.Tag_Nav_Aux a').filter(function(){
return $(this).attr('href').toLowerCase() === window.location.pathname.toLowerCase();
}).addClass('active');
});
and create a CSS rule for
.Tag_Nav_Aux a.active{
// style you want the active link to have
}
$(document).ready(function() {
var url = window.location.href.toLowerCase();
$(".Tag_Nav_Aux a").each(function() {
var $this = $(this);
var href = $this.attr("href").toLowerCase();
if(url.indexOf(href) > -1) {
$this.addClass("active");
}
});
});​
I think you need to check the current page url and assign a class to the item like to active.
I usually do putting class="active" based on current URL match with help of server side code.
But if you dont want server code you can do with help of JavaScript
var currentPage=window.location.href;
if(currentPage=="")
{
//logic to find and add a Class for the proper anchor tag
}

Highlighting current link

Hi I have to use only html and javascript. I have created one single page which contains a top navigation links the url for those links are something like:
domain.com,
domain.com/b1,
domain.com/b2
how do I highlight the current link.
If I understend question you may try html-attribute style for link tag:
<a style="color: red">link</a>
OR edit CSS-file for that link.
You can set class with serverside and define this class into CSS.
If coding only JS see for JS-object window.location.
You'll need to use a simple JS script to check the href of the link and compare it to the window.location.href (the current URL).
Here's a simple example using JQuery:
var currentUrl = window.location.href;
$('a').each(function(index) {
var url = $(this).attr("href");
if (url === currentUrl) {
$(this).addClass("current");
} else {
$(this).removeClass("current");
}
});
Here it adds a class current to the link if it is the current link. I have a demo here on JSFiddle.
Using jquery
$('a[href="' + window.location.pathname + '"]').addClass('highlight');
replace pathname by one property (or a combination of properties) of the location object if it's not the good one.
the snippet add 'highlight' class to the link with the specified href, then you can write some css to highlight your link.

Categories