-4

I need to display the URLs in a list of search results in a breadcrumb style (i.e. such as Google does - Google Breadcrumbs), and have limited knowledge of JavaScript (and haven't touched it in nearly two years). Can you help me please? I can apply the code if it's provided with clear instruction, and am very comfortable with HTML and CSS, but have not attempted to create breadcrumbs without lists before.

Where do I start?

Input would be page's URL (class is .slimBreadcrumbLink) - e.g. https://www.example.com/level1/level2/level3/level4 - and output would be as below:

Level 2 > Level 3 > Level 4

I haven't tried anything of significance yet, I'm starting here. I've read through the other breadcrumb questions posed, but it's not helped so far. I found the below but don't know how to implement it.

var path = location.pathname;

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
  });
}

Thank you.

  • Please provide input and expected output, and if possible some code you already tried. – nicovank Dec 13 '16 at 00:22
  • Are you looking for help with Java, or javascript? they're two completely different technologies. How do you get the first link? The `example.com/level1/level2/level3` one? How do you end up with that? If this is javascript/HTML, this is probably just parsing the current URL and split it by `/` – junkfoodjunkie Dec 13 '16 at 00:31
  • @junkfoodjunkie The URL is displayed as one of three fields inside a list item in a data list of results for a search term. Unless I can do this with HTML/CSS, it will need to be JavaScript. How do I split the URL with ' > ' instead of '/', and hide protocol and host? – Lively Dev Dec 13 '16 at 00:43

2 Answers2

0

Here is a function that will create the HTML structure for the breadcrumbs:

const getLevels = url => url.replace(/http(s.):\/\//, "").split("/");
const createBreadcrumb = function(url, elem) {
    const ol = document.createElement("ol");
        getLevels(url).forEach((e, i) => {
            if(i > 2) {
                const li = document.createElement("li");
                const a  = document.createElement("a");

                a.href = url.substring(0, url.indexOf(e) + e.length);
                a.innerText = e;

                li.appendChild(a)        
                ol.appendChild(li);
            }   
        }
    });
    elem.appendChild(ol);
};

Because it is ES6, you will have to use a transpiler like babel to make it compatible with older browsers. Also, because you are parsing the URL, you cannot customize the title of the links.

You can then use the function like this, to parse the url and create the ol list in the element with the id.

createBreadcrumb(url, document.getElementById("id"));
nicovank
  • 3,157
  • 1
  • 21
  • 42
  • Thank you @nicovank - how do insert that result into the HTML using an ID or class name please? – Lively Dev Dec 13 '16 at 00:52
  • `createBreadcrumb(url, document.getElementById("id"));` for an id or `createBreadcrumb(url, document.getElementsByClassName("class")[0]);` for a class. – nicovank Dec 13 '16 at 00:54
0

I rolled my own demo snippet. The code is quite a bit to explain, but if anything doesn't appear self-explanatory feel free to let me know and I'll elaborate more here.

// Utility functions
function createBreadcrumbs (origin, path) {
    var levels = path.slice(1).split('/')
    
    return levels.map(function (e, i, levels) {
      var text = e.replace(/-+/g, ' ').replace(/\s*\b\S/g, function (e) {
          return e.toUpperCase()
      })
      return anchor(origin + '/' + levels.slice(0, i+1).join('/'), text)
    })
}

function anchor (href, text) {
    var a = document.createElement('a')
    a.href = href
    a.textContent = text
    return a
}

function render (breadcrumbs) {
  var ol = document.createElement('ol')
  ol.className = 'breadcrumbs'
  breadcrumbs.forEach(function (anchor) {
      var li = document.createElement('li')
      anchor.className = 'breadcrumbs__link'
      li.className = 'breadcrumbs__crumb'
      li.appendChild(anchor)
      ol.appendChild(li)
  })
  return ol
}


// How to use
var breadcrumbs = createBreadcrumbs('//example.com', '/example-thing/location-stuff/level-2'),
    list = render(breadcrumbs)

console.log(breadcrumbs)
document.body.appendChild(list)
<p>Breadcrumbs for <a href="//example.com/example-thing/location-stuff/level-2">//example.com/example-thing/location-stuff/level-2</a></p>
gyre
  • 16,369
  • 3
  • 37
  • 47