Skip to content

Instantly share code, notes, and snippets.

@ambercouch
Created March 21, 2018 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ambercouch/0b09bff5c5d01c207d22105253260edc to your computer and use it in GitHub Desktop.
Save ambercouch/0b09bff5c5d01c207d22105253260edc to your computer and use it in GitHub Desktop.
Added breadcrumbs from the url path with javascript
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(' ');
}
var bcElements = document.querySelectorAll('[data-breadcrumbs]');
var currentPath = window.location.pathname;
//currentPath = currentPath.replace(/-/g, ' ');
var currentPathClean = currentPath.substring(1, currentPath.length - 1);
var crumbsArray = currentPathClean.split('/');
var linkLabel = '';
var linkSlug = '';
for (var i = 0; i < crumbsArray.length; i++) {
linkSlug = linkSlug + '/' + crumbsArray[i];
linkLabel = crumbsArray[i].replace(/-/g, ' ')
linkLabel = titleCase(linkLabel);
for (var c = 0; c < bcElements.length; c++) {
if(i + 1 === crumbsArray.length){
bcElements[c].insertAdjacentHTML('beforeend', '<li>'+linkLabel+'</li>');
}else{
bcElements[c].insertAdjacentHTML('beforeend', '<li><a href="'+linkSlug+'" >'+linkLabel+'</a></li>');
}
}
}
<ul class="breadcrumbs" data-breadcrumbs >
<li><a href="/">Start</a></li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment