Bootstrap dropdown-menus + sub-menus won’t close on link click


I’ve put together a multi-level menu based on Bootstraps dropdown-menus (with sub-menus), but I’m having a struggle figuring out how to make the sub-menus close when a link is clicked.

The code structure is as follows:

$('.dropdown-submenu').click(function() {
  var val = $(this).children('.dropdown-menu').css('display');

  if (val == 'block') {
    $(this).find('.dropdown-menu').css('display', 'none');
  } else {
    $(this).parent().find('.dropdown-menu').css('display', 'none');
    $(this).children('.dropdown-menu').css('display', 'block');

    var menu = $(this).parent().find("ul");
    var menupos = menu.offset();

    if ((menupos.left + menu.width()) + 30 > $(window).width()) {
      var newpos = -menu.width();
    } else {
      var newpos = $(this).parent().width();
      left: newpos

  return false;

It works as it is supposed to for the links in the first level, but not for the links in the sub-levels. I have tried with an onclick function that sets .css('display', 'none'), but this disables the menu function completely.

Any help would be much appreciated.

Please see this Fiddle: