Is there a way of getting jQuery to generate breadcrumbs on a page from the url?
So if the site url was: mysite.com/sec1/sec2/page
The breadcrumbs would be something like: Home > Sec1 > Sec2 > Page
Thanks
This will create an array you can use to generate breadcrumbs.
var here = location.href.split('/').slice(3);
var parts = [{ "text": 'Home', "link": '/' }];
for( var i = 0; i < here.length; i++ ) {
var part = here[i];
var text = part.toUpperCase();
var link = '/' + here.slice( 0, i + 1 ).join('/');
parts.push({ "text": text, "link": link });
}
Though, I really think you should be handling this at the server side!
var url = 'mysite.com/sec1/sec2/page'; // = location.href
var parts = url.split('/');
parts[0] = 'Home';
var breadcrumb = parts.join(' > ');
$('#breadcrumb').html(breadcrumb);
Full Javascript function to display breadcrumbs from page url based on Bill Criswell's answer
function getBreadcrumbs() {
const here = location.href.split('/').slice(3);
// console.log(here)
const parts = [{"text": 'Home', "link": '/'}];
// console.log(parts)
for (let i = 0; i < here.length; i++) {
const part = here[i];
// console.log(part)
const text = decodeURIComponent(part).toUpperCase().split('.')[0];
// console.log(text)
const link = '/' + here.slice(0, i + 1).join('/');
console.log(link)
parts.push({"text": text, "link": link});
// console.log(parts)
}
return parts.map((part) => {
return "<a href=\"" + part.link + "\">" + part.text + "</a>"
}).join('<span style="padding: 5px">/</span>')
}
document.getElementById("demo").innerHTML = getBreadcrumbs();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With