Reputation: 1
I copied the code from one topic. I completely analyzed and understood it. That topic was about assigning the class of the current page (and the html name was searched in links and compared with the current page).
function getCurrentLinkFrom(links){
var curPage = document.URL;
curPage = curPage.substr(curPage.lastIndexOf("/ ")) ;
links.each(function(){
var linkPage = $(this).attr("href");
linkPage = linkPage.substr(linkPage.lastIndexOf("/"));
if (curPage == linkPage){
return $(this);
}
});
};
$(document).ready(function(){
var currentLink = getCurrentLinkFrom($('navbar a'));
currentLink.addClass('current_link');
});
Upvotes: 0
Views: 1199
Reputation: 197
Looks to me like your lastIndexOf call differs between the two values you're comparing. The curPage one has a space after the slash and the other doesn't.
With that said, you should take a look at jQuery's filter function which would simplify your logic a bit here and follow a better pattern as you'd be calling addClass on a jQuery object with (potentially) no matched elements instead of an undefined variable.
Upvotes: 0
Reputation: 250882
This will help you get to an answer, but will arm you with an important skill at the same time... I have added two logging statements that will show you whether you are getting a match and why.
You only return a value if you find a match, so the error is because you have executed your function without finding a match.
function getCurrentLinkFrom(links){
var curPage = document.URL;
curPage = curPage.substr(curPage.lastIndexOf("/ ")) ;
links.each(function(){
var linkPage = $(this).attr("href");
linkPage = linkPage.substr(linkPage.lastIndexOf("/"));
// This will help you see if any match
console.log(curPage, linkPage);
if (curPage == linkPage){
return $(this);
}
});
// This will help you to see when there is no match
console.log('Not found!', curPage);
};
Upvotes: 1