Q:

add/remove class on click, navigation li item

I was trying to find solution but i can't, every single code wasn't good for my project. Here is navigation structure

<nav>
  <ul class="menu">
    <li>
      <ul class="submenu">
        <li><a></a></li>
        <li><a></a></li>
        <li><a></a></li>
        <li><a></a></li>
      </ul>
    </li>
    <li>
      <ul class="submenu">
        <li><a></a></li>
        <li><a></a></li>
        <li><a></a></li>
        <li><a></a></li>
      </ul>
    </li>
    <li></li>
    <li></li>
  </ul>
</nav>

$(".menu li").click(function(){
    $(this).toggleClass("visible");
});
$('body').click(function(){
 
  if( $(".menu li").hasClass("visible") ){
   $(".menu li").removeClass("visible");
  
       };
  });

What a want to achieve is next:

When i click on .menu li to add class active
When i click on another .menu li item or on .submenu li a, remove class active from another li item that has that class
And also when i click anywhere else (example body) also remove class from .menu li

I hope you understand what i want. Sorry for my bad grammar
Update:
Toggle Solution
Modified code by:  @Sasa Novakovic (thank you again bro :) )

function removeActiveMenuClass(active_element){
    $('.menu li').not(active_element).removeClass('visible');
}

$( '.menu>li' ).click(function(e) {
    e.stopPropagation();
    var $_this = $(this);

    removeActiveMenuClass($_this);
    if ($_this.hasClass('visible')) {
        $_this.removeClass('visible');
    }
    else {
        $_this.addClass('visible');
    }
});

$('body').click(function() {
    removeActiveMenuClass();
});

A:

Here is the code for you jsfiddle.
$('html').click(function() {
    removeActiveMenuClass();
});

$( '.menu>li, .submenu>li' ).click(function(e) {
    e.stopPropagation();
    removeActiveMenuClass();
    $(this).addClass('active');
});

function removeActiveMenuClass(){
    $('.menu li').removeClass('active');
}

