WEB DEVELOPMENT
[edit]

Nested List Menu

A super simple easily customizable nested menu written in javascript with a php/mysql api back end.


header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=utf-8");

require 'database.php';

$sql = "SELECT * FROM `menu`";
$result = $db->query($sql);
    
while($row = $result->fetch_assoc()) {
    $data[] = $row;
}
    
$itemsByReference = array();

foreach($data as $key => &$item) {
    $itemsByReference[$item['id']] = &$item;
    $itemsByReference[$item['id']]['children'] = array();
    $itemsByReference[$item['id']]['data'] = new StdClass();
}
    
foreach($data as $key => &$item) {
    if($item['parent_id'] && isset($itemsByReference[$item['parent_id']])) {
        $itemsByReference [$item['parent_id']]['children'][] = &$item;
    }
}
    
foreach($data as $key => &$item) {
    if($item['parent_id'] && isset($itemsByReference[$item['parent_id']])) {
        unset($data[$key]);
    }
}
    
http_response_code(200);  
echo json_encode($data);


<script type="text/javascript">
    
function onload()
{
    
    const api_json = 'http://api.webserver.example/page/menu.php';
        
    fetch(api_json, {
        
        method: 'POST',
        headers: {
            Accept: 'Access-Control-Allow-Origin: *',
                    'Content-Type': 'application/json',
            },
    })
        
    .then((response) => response.json())
    .then((data) => {
        
        var menu = data;
            
        menu = '";

        document.getElementById("menu").innerHTML = menu;
     }); 
 } 
</script>


<style>
.clear{
  clear:both;
}
.menu{
  background:#eee;
}
.menu ul{
  display:block;
  margin:0px;
  padding:0px;
  list-style:none;
}
.menu ul li{
  float:left;
  position:relative;
}
.menu ul li a{
  display:block;
  line-height:40px;
  padding:0px 10px;
  color:#444;
  text-decoration:none;
}
.menu ul li:hover a{
  background:#ddd;
}
.menu ul li ul{
  position:absolute;
  left:0px;
  top:40px;
  background:#ddd;
  visibility:hidden;
  opacity:0;
  filter:alpha(opacity=0);
  -moz-transition:all 0.1s ease-in;
  -webkit-transition:all 0.1s ease-in;
  transition:all 0.1s ease-in;
}
.menu ul li:hover ul{
  visibility:visible;
  opacity:1;
  filter:alpha(opacity=100);
}
.menu ul li ul li{
  float:none;
  border-top:solid 1px #bbb;
}
.menu ul li ul li:first-child{
  border-top:none;
}
.menu ul li ul li a{
  white-space:nowrap;
  line-height:normal;
  padding:10px;
}
.menu ul li ul li a:hover{
  text-decoration:underline;
}
</style>