Skip to content

Instantly share code, notes, and snippets.

@alfonsodguez
Last active January 12, 2024 21:57
Show Gist options
  • Save alfonsodguez/52add11e79e168bbd2902c11ae12b92e to your computer and use it in GitHub Desktop.
Save alfonsodguez/52add11e79e168bbd2902c11ae12b92e to your computer and use it in GitHub Desktop.
JavaScript treeview
const treeview = $('#treeviewCategories')
const categories = JSON.parse(serializeCategories.replace(/"/g, `"`))
const separatorCategory = "-"
const urlProducts = "http://localhost:3000/Shop/Products/"
const initTag = '<ul class="nested">'
const closeTag = '</ul>'
function expandSubcategories() {
const subCategories = _getSubcategories()
if (subCategories.length > 0) {
const tags = _buildSubcategories(subCategories)
$(this).parent().append(tags)
$(".caret").click(expandSubcategories)
} else {
// get products by idCategory
window.location = `${urlProducts}${idCategory}`
}
$(this).parent().children("ul.nested").toggleClass("active")
$(this).toggleClass("caret-down")
}
function _getSubcategories() {
const idCategory = $(this).parent().attr('id')
const regexCategory = new RegExp("^" + idCategory + "-[0-9]+$")
return categories.filter(category => category.path.search(regexCategory) !== -1)
}
function _buildSubcategories(subCategories) {
return subCategories.reduce((acc, subCategory, index) => {
if (subCategories.length === index++) {
return acc + closeTag
}
return acc + `<li id="${subCategory.path}"><span class="caret">${subCategory.name}</span></li>`
}, initTag)
}
// initial state collapsed tags
categories.forEach(category => {
const paths = category.path.split(separatorCategory)
if (paths.length === 1) {
treeview.append(`<li id="${category.path}"><span class="caret">${category.name}</span></li>`)
}
})
$(".caret").click(expandSubcategories)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment