Skip to content

Instantly share code, notes, and snippets.

@me7media
Created January 22, 2019 12:30
Show Gist options
  • Save me7media/acded5fa4948d1a214a89a5f3c86b3aa to your computer and use it in GitHub Desktop.
Save me7media/acded5fa4948d1a214a89a5f3c86b3aa to your computer and use it in GitHub Desktop.
Laravel Multilevel Menu with js
//Controller Category - ['id', 'parent_id', 'name']
$categories = Category::all();
//menu.balde.php
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Catalog
</button>
<div class="dropdown-menu mainMenu" aria-labelledby="dropdownMenu2">
</ul>
<div class="childMenu">
<ul class="childMenu__list list"></ul>
</div>
</div>
</div>
<script>
let cats_menu = JSON.parse('{!!$categories->groupBy('parent_id')->toJson()!!}'); //Групируем по паренту
$(document).ready(function () {
// Основное меню
let menuList = $('.mainMenu ul');
cats_menu[0].forEach(function (item, i) {
menuList.append(`
<li class="mainMenu__item">
<a href="/category/${item.slug}" class="mainMenu__link">${item.title_ru}</a>
<ul class="mainMenu__item__children" id="${item.id}"></ul>
</li>
`)
});
menuHover();
function menuHover() {
let thisId = $(this).children('ul').attr('id');
if ($('ul#' + thisId).children().length === 0
&& cats_menu[thisId] !== undefined
&& cats_menu[thisId].length > 0) {
cats_menu[thisId].forEach(function (item, i) {
$('ul#' + thisId).append(`
<li class="mainMenu__item">
<a href="/category/${item.slug}" class="mainMenu__link">${item.title_ru}</a>
<ul class="mainMenu__item__children" id="${item.id}"></ul>
</li>
`)
});
}
$('.mainMenu__item').unbind().mouseover(menuHover);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment