Toggle and show hide menus in responsive design

Toggle and show hide menus in responsive design

Hello,

I have a responsive webpage (template) needs to have three sections (search bar, main menu and sub menu) become toggle menus when page re-size smaller than 768px (or the devise screen size is smaller than 768px). Similar to this page: 

I inserted the following code in the bottom of the page - it works but is there a better way or best practice to organize such functions? Many thanks!
<script>
$(function() {
//search bar show hide
$(".searchIcon").on("click touchstart", function(e){
e.stopPropagation();
e.preventDefault();
$(".search").toggle();
})
//main menu show hide
    $(".showhideMain").on("click touchstart", function(e){
    e.stopPropagation(); 
e.preventDefault();
      $("#main-menu").toggle();
    });
    
if(window.innerWidth <= 767){
$("#main-menu").hide();
}else{
$("#main-menu").show();
}

$(window).resize(function screenSize(){
if(window.innerWidth <= 767){
$("#main-menu").hide();
}else{
$("#main-menu").show();
}
});
//sub menu show hide
    $(".showhideSub").on("click touchstart", function(e){
    e.stopPropagation(); 
e.preventDefault();
      $("#sub-menu").toggle();
    });

if(window.innerWidth <= 767){
$("#sub-menu").hide();
}else{
$("#sub-menu").show();
}

$(window).resize(function screenSize(){
if(window.innerWidth <= 767){
$("#sub-menu").hide();
}else{
$("#sub-menu").show();
}
});

});
</script>