Search code examples
javascriptcssjoomlamenuitemresponsive

Change width of menu items depending on amount of menu items


Using Joomla I have got 4 menu items. One of them is optional. If I want to unpublish this menu item, the other menu items width should be increased, but only at viewport min-width 980px. The menu has the id #menu, the elements width I want to change is #menu li. The menu item which is optional has .optMenuitem as its classname. For four menu items the width should be 25%, for three 33.33% than. I thought of sth like:

function changeWidth (){
	var four = document.getElementsByClassName('optMenuitem');
	var opt = document.getElementByID('menu');
	if (four==true){
		opt.li.style.width = "25%";
	} else {
		opt.li.style.width = "33.33%";
	}
}

Does not work. I'm a newbie. Any suggestions?


Solution

  • If you want to target #menu li you should do something like this:

    function changeWidth() {
      var four = document.getElementsByClassName('optMenuitem');
      // You select all the menu items
      var opt = document.querySelectorAll('#menu li');
      if (four == true) {
        // You loop on all of them and you set the width
        for (var i = 0; i < opt.length; i++)
          opt[i].style.width = "25%";
      } else {
        for (var i = 0; i < opt.length; i++)
          opt[i].style.width = "33%";
      }
    }