Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery generate breadcrumbs from url?

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

like image 275
Evanss Avatar asked Jun 22 '11 19:06

Evanss


3 Answers

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!

like image 80
Bill Criswell Avatar answered Oct 11 '22 17:10

Bill Criswell


var url = 'mysite.com/sec1/sec2/page'; // = location.href
var parts = url.split('/');
parts[0] = 'Home';
var breadcrumb = parts.join(' &gt; ');
$('#breadcrumb').html(breadcrumb);
like image 35
Sjoerd Avatar answered Oct 11 '22 17:10

Sjoerd


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();
like image 44
C.Wainaina Avatar answered Oct 11 '22 18:10

C.Wainaina