JavaScript Breadcrumbs navigation

23 בינואר 2010

In this code listing I want to demonstrate how to implement "Breadcrumbs" in JavaScript for the pages collection, where page object have a two main key's pageId and parentPageId, and create a new collection sorted by current parents.

 

Listing 1:

 

function page(pageId, parentPageId, title) { 
return this.constructor(pageId, parentPageId, title); }
page.prototype = {

// properties
pageId: null,
parentPageId: null,
title: "",

setPageId: function(pageId) {
this.pageId = pageId;
},
getPageId: function() {
return this.pageId;
},
setParentPageId: function(parentPageId) {
this.parentPageId = parentPageId;
},
getParentPageId: function() {
return this.parentPageId;
},
setTitle: function(title) {
this.title = title;
},
getTitle: function() {
return this.title;
},

// default constructor
constructor: function(pageId, parentPageId, title) {
this.pageId = pageId;
this.parentPageId = parentPageId;
this.title = title;
}
};

var dataSource = [
[1, 0, 'Home'],
[2, 0, 'Products'],
[3, 0, 'Contact Us'],
[4, 0, 'About'],
[5, 2, 'TradeDesk'],
[6, 2, 'MT4 - (MetaTrader)'],
[7, 6, 'Download']
];

var pages = {
pagesList: [],
getByPageId: function(pageId) {
for(var i = 0; i < this.pagesList.length; i++) {
if(this.pagesList[i].getPageId() == pageId)
return this.pagesList[i];
}
}
};

var breadCrumbs = new function() {

// fill data of the page object
for(var i = 0; i < dataSource.length; i++) {

// create new page and set properties
var p = new page();
p.setPageId(dataSource[i][0]);
p.setParentPageId(dataSource[i][1]);
p.setTitle(dataSource[i][2]);

pages.pagesList[i] = p;
}

// get specific page by pageId
var p = pages.getByPageId(7);

// check if page have a parentPageId
if(p.getParentPageId() != 0) {

// fill breadCrumbs array using - recursive method
var breadCrumbs = [];
var pageToCheck = p;
var maxCheck = 6;
var checkCounter = 0;


while(pageToCheck != null && checkCounter < maxCheck) {
breadCrumbs.push(pageToCheck);
pageToCheck =
pages.getByPageId(pageToCheck.getParentPageId());
}
pageToCheck = null;

// reverse array
breadCrumbs.reverse();

for(var i = 0; i < breadCrumbs.length; i++) {
// print breadCrumbs array -
// output will be Products - > MT4 -> Overview
alert(breadCrumbs[i].getTitle());
}

}

};

 

 

Enjoy…

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

3 תגובות

  1. Yuri24 בינואר 2010 ב 10:25

    Nice post, but why you did not provide demo page?

    הגב
  2. cna training4 ביוני 2010 ב 4:17

    Great site. A lot of useful information here. I’m sending it to some friends!

    הגב
  3. wtylthvlr@gmail.com27 ביולי 2013 ב 16:32

    I constantly spent my half an hour to read this webpage's articles all the time along with a mug of coffee.

    הגב