Skip to content

Instantly share code, notes, and snippets.

@krabello
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krabello/a1daf04159428fb45415 to your computer and use it in GitHub Desktop.
Save krabello/a1daf04159428fb45415 to your computer and use it in GitHub Desktop.
Dropdown categories
function Categories(outputElement, outputID) {
this.outputElement = outputElement;
this.outputID = outputID;
}
Categories.prototype.getOptionLinks = function() {
var catListEl = document.getElementsByClassName(this.outputElement)[0];
var items = catListEl.childNodes[1].children;
var html = '';
for (var i = 0; i < items.length; ++i) {
var link = items[i].childNodes[0].href;
var catName = items[i].textContent;
this.html += '<option value="' + link + '">' + catName + '</option>\n';
}
return this.html;
};
Categories.prototype.createDropDown = function() {
return '<select onChange="window.location.href=this.value">' + this.getOptionLinks() + '</select>';
};
Categories.prototype.generate = function() {
if (document.getElementById(this.outputID)) {
document.getElementById(this.outputID).innerHTML = this.createDropDown();
}
};
a = new Categories('cats', 'catDropdown');
a.generate();

Usage

Since we have no control over the PHP code that generates the HTML and we sometimes need the links in a dropdown format this js gist was created.

This takes 2 parameters the first one should stay "cats" for now as this is what the PHP code generates but I left it as an option just in case it changes. The second parameter is the id of the element that the drop down should be placed in.

Categories Wrapper Example

Note: the "class" name here

<div class="cats">
    <?php echo getCategoriesForStore($store, true);?>
</div>

Categories Dropdown Container Example

Note: the "id" name here

<div id="catDropdown"></div>

Change this in js page

a = new Categories('cats', 'catDropdown');

to something like

a = new Categories('class name from Categories Wrapper', 'id from Categories Dropdown Container');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment