Dynamic breadcrumb based on current page using Javascript/jQuery
23,087
You can try following code in the document ready event of the page.
var url = "level3.html"; <-- following line shows how to get this from url
//location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
var currentItem = $(".items").find("[href$='" + url + "']");
var path = "home";
$(currentItem.parents("li").get().reverse()).each(function () {
path += "/" + $(this).children("a").text();
});
$(".bredcrumb").html(path);
Incase if you want breadcrumb with navigation links try this Demo
Author by
baron5
Educated as a Computer Engineer, working as an adviser and programmer. I work primarily with Java: Web Services, EJB's and Web applications.
Updated on February 02, 2020Comments
-
baron5 about 4 years
I've looked at the question here and the answer looked good enough if one doesn't have to actually navigate too.
I need a Javascript/jQuery script that, based on the URL of the current page, can create breadcrumbs with the parents of that page, IE:
<nav class="items"> <ul> <li><a href="test.html">Test 1</a></li> <li><a href="test2.html">Test 2</a> <ul> <li><a href="level1.html">Level 1</a></li> <li><a href="test/level2.html">Level 2</a> <ul> <li><a href="test/level2/level3.html">Level 3</a></li> <li><a href="test/level2/level32.html">Also at level 3</a></li> </ul> </li> </ul> </li> <li><a href="test3.html">Test 3</a></li> </ul> </nav>
If the user navigates to Level 3, based on current page, show:
Home >> Test 2 >> Level 2 >> Level 3
This script will be included in every page, so it works onload.
-
baron5 over 9 yearsThe javascript I'm thinking about will be working on every load, no ajax will be used.
-
Azadrum over 9 yearsAre you building an html site or using any serverside programming that you may pass the current page's info to create the breadcrumb?
-
baron5 over 9 yearsTrying to create an independent top-html that will be included both on applications with serverside programming backend and in a wordpress instance. That's why I'd like it to be javascript. I know one can get the current page with $(location).attr('href'); . So It would be iterating through the ul to find the similar url as the one I'm currently viewing.
-
Azadrum over 9 yearscheck this fiddle jsfiddle.net/rpyxcbok/2 if i got you right this will do.
-
baron5 over 9 yearsThanks, nice fiddle :) One step closer, but it would not work with the filestructure at hand.
-
baron5 over 9 yearsSuper, this was spot on! I got an extra / after Home, but it's probably just my html, and hence I can work around that. Thank you!
-
Joel Hernandez almost 9 yearsThis is great. I am working on bootstrap breadcrumbs style with this recursive function.