How to assemble dynamic menu?

Asked

Viewed 655 times

1

How to build this menu dynamically using json? That it was mounted according to the order that came. It is possible?

  • 1

    From what I’ve seen, you have functions ready for each menu item, correct?

  • @Rafael This, has yes!

  • @Rafaelaugusto is possible?

  • @Rafaelaugusto this menu may or may not have all these items, and could change the order of li, it is possible to be dynamic like this?

  • 1

    Which items are fixed from this menu? Items that would not come from json, but are always fixed in the menu? Another thing, you have a json ready or I can assemble one myself to elaborate the answer?

  • @Isa I posted an answer, see if that’s what you want.

  • @Leandrosimões the only fixed is the button "exit" You can mount yes :))

  • Ready @Isa created the answer, take a look to see if it attracts you. Any doubt I’m available. Hug!

Show 3 more comments

2 answers

1

One way to do this would be like this (I can’t say it’s the best way).

let json = [
  {
    title: "Função Teste",
    funcName: "teste()"
  },
  {
    title: "Função Exibir nome",
    funcName: "exibirNome()"
  },
  {
    title: "Função comida favorita",
    funcName: "comidaFavorita()"
  },
  {
    title: "Função melhor serie",
    funcName: "melhorSerie()"
  }
]

function menu(){
  for(let i = 0; i < json.length; i++){
    $('nav ul').append('<li><a href="#" data-func="'+json[i].funcName+'" onclick="'+json[i].funcName+'">'+json[i].title+'</a></li>')
  }
}

menu()


function teste(){
  alert('f')
}

function exibirNome(){
  alert('meu nome é Rafael')
}

function comidaFavorita(){
  alert('Minha comida favoria é X-Bacon')
}

function melhorSerie(){
  alert('Game Of Thrones')
}
  <nav>
    <ul>
    
    </ul>
  </nav>
  
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>

As you can see in the example, from a json I assemble the menu with the respective funções.

1


You can do yes Isa, follow the code:

https://jsfiddle.net/leandrosimoes/0vt1tvc8/3/

// Objeto JSON retornado do servidor
var jsonObject = {
	items: [
  	{
    	onclickFunctions: ['displayPracaRamos', 'displayPracaCidadeMilao'],
      icon: 'glyphicon-tree-deciduous',
      title: 'Praças'
    },    
  	{
    	onclickFunctions: ['displayCameraCasteloBranco1', 'displayCameraCasteloBranco2'],
      icon: 'glyphicon-camera',
      title: 'Cameras'
    },    
  	{
    	onclickFunctions: ['displayAlarmsMarker'],
      icon: 'glyphicon-alert',
      title: 'Ocorrências'
    },    
  	{
    	onclickFunctions: ['showPois'],
      icon: 'glyphicon-map-marker',
      title: 'POIS'
    },    
  	{
    	onclickFunctions: [],
      icon: 'glyphicon-pushpin',
      title: 'Minha Localização'
    },    
  	{
    	onclickFunctions: ['toggleFullScreen'],
      icon: 'glyphicon-fullscreen',
      title: 'Tela Inteira'
    }
  ]
};

// Funções que serão atribuídas aos itens do menu
var menuFunctions = {
	'displayPracaRamos': function(data) {  
    console.log('displayPracaRamos:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'displayPracaCidadeMilao': function(data) {  
    console.log('displayPracaCidadeMilao:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'displayCameraCasteloBranco1': function(data) {  
    console.log('displayCameraCasteloBranco1:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'displayCameraCasteloBranco2': function(data) {  
    console.log('displayCameraCasteloBranco2:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'displayAlarmsMarker': function(data) {  
    console.log('displayAlarmsMarker:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'displayAlarmsMarker': function(data) {  
    console.log('displayAlarmsMarker:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'showPois': function(data) {  
    console.log('showPois:');
    console.log(data); // Aqui vc faz o que quiser com o item
  },
	'toggleFullScreen': function(data) {  
    console.log('toggleFullScreen:');
    console.log(data); // Aqui vc faz o que quiser com o item
  }

};

// Função que monta o menu
function montaMenu(data) {
	data.items.reverse().forEach(function(item) {
  	var ul = document.querySelector('nav.navbar ul');
    var li = document.createElement('li');
    var a = document.createElement('a');
    var spanTitle = document.createElement('span');    
    var spanIcon = document.createElement('span');
    
    spanTitle.classList.add('desc');
    spanTitle.classList.add('animate');
    spanTitle.innerText = item.title;
    
    spanIcon.classList.add('glyphicon');
    spanIcon.classList.add(item.icon);
    
    a.classList.add('animate');
    
    a.appendChild(spanTitle);
    a.appendChild(spanIcon);
    li.appendChild(a);
    
    item.onclickFunctions.forEach(function(func) {
    	var menuFunc = menuFunctions[func];
    	li.addEventListener('click', function() {
      	menuFunc(item);
      });
    });
    
    ul.insertBefore(li, ul.childNodes[0]);
  });
};

montaMenu(jsonObject); // Aqui você chama a função que monta o menu
<nav class="navbar navbar-fixed-left navbar-minimal animate" role="navigation">
  <div class="navbar-toggler animate">
    <span class="menu-icon"></span>
  </div>
  <ul class="navbar-menu animate">

    <li>
      <a href="/PracaInteligente/login" class="animate"> <span class="desc animate"> Sair </span> <span class="glyphicon glyphicon glyphicon-log-out"></span>
      </a>
    </li>
  </ul>
</nav>

It is very dynamic even you use the item itself as a function parameter if you need to pass some parameter to the function. Another detail is that it does not use any external library like Jquery for example.

I hope I helped! Any questions just ask me.

Hug!

  • was very good!! Just one thing, I used the json and the function to mount the menu, only I did not use the functions assigned to the menu, because they already exist in another file. I imported in my html, first the json and below the function that creates the menu. And in the body I put the html snippet you put (in case the Nav part) but it did not mount the rest of mine, just appears the fixed button (exit) know what can be?

  • it gives this error on the console:Uncaught Typeerror: Cannot read Property 'insertBefore' of null at menuDinamico.js:103 at Array.foreach (<Anonymous>) at montaMenu (menuDinamico.js:76) at menuDinamico.js:107

  • From the bug you gave me, it seems that ul is null, that is, Document.querySelector is not finding the list.

  • 1

    Make sure that this code will only run after the other js and also html files have already been loaded.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.