Is threre any better way to accomplish this using jquery?

I am trying to hide all elements when one button is clicked and only the menu belonging to that specific button should appear. If I do like this that will be too long if more buttons and menus are there.

Are there any methods that can shorten this and get the desired result?

$(document).ready(function(){  

    $("#steps").click(function(){
        $("#calculateMenu").hide();
        $("#stepsMenu").show();    
    });

    $("#calculate").click(function(){ 
        $("#stepsMenu").hide(); 
        $("#calculateMenu").show();
    });
});

Answer

You could do it like this:

$("#steps,#calculate").click(function() {
  var id = $(this).attr("id");
  $("[id*=Menu]").hide();
  $("#" + id + "Menu").show();
});

All element where id contains Menu will be hidden, and then we will show the “correct” element

Demo

$("#steps,#calculate").click(function() {
  var id = $(this).attr("id");
  $("[id*=Menu]").hide();
  $("#" + id + "Menu").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="steps">steps</button>
<button id="calculate">calculate</button>



<div id="stepsMenu">stepsMenu</div>
<div id="calculateMenu">calculateMenu</div>

Leave a Reply

Your email address will not be published. Required fields are marked *