I have a full-page menu that opens on a button click with two different sections. The content in #terms doesn’t change, but the content in #links does, based on which button you click. The code itself works fine, but the jQuery feels incredibly bulky and I was wondering if anyone could suggest any ways to make it a bit cleaner. Also, the HTML structure has to pretty well stay as-is because its kind of finnicky with the styling.
I should also note that I’m not the most experienced with jQuery, so…
This is the code in question and the relevant HTML (the buttons at the top are in another part of the HTML, but I included them here to see how they’re structured):
$("#codes-launch, #gfx-launch, #tuts-launch, #menu-close").click(function() {
$("#menu").slideToggle("slow");
$("body").toggleClass("scroll-lock");
});
$("#codes-launch").click(function() {
$("#codes").show();
$("#gfx, #tuts").hide();
});
$("#gfx-launch").click(function() {
$("#gfx").show();
$("#codes, #tuts").hide();
});
$("#tuts-launch").click(function() {
$("#tuts").show();
$("#codes, #gfx").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="codes-launch">Codes</button>
<button id="gfx-launch">Graphics</button>
<button id="tuts-launch">Resources</button>
<div id="menu">
<div id="terms">SOME STUFF</div>
<div id="links">
<button id="menu-close">Close</button>
<div id="codes">Codes</div>
<div id="gfx">Graphics</div>
<div id="tuts">Resources</div>
</div>
</div>
>Solution :
Using a data attribute and a common selector, you can replace all the clicks into one.
$("button[data-toggles]").on("click", function(evt) {
evt.preventDefault();
$("#links > div").hide();
const selector = $(this).data('toggles');
$(selector).show();
$("#menu").slideDown("slow");
$("body").addClass("scroll-lock");
});
$("#menu-close").on("click", function() {
$("#menu").slideUp("slow");
$("body").removeClass("scroll-lock");
});
#menu {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="codes-launch" data-toggles="#codes">Codes</button>
<button id="gfx-launch" data-toggles="#gfx">Graphics</button>
<button id="tuts-launch" data-toggles="#tuts">Resources</button>
<div id="menu">
<div id="terms">SOME STUFF</div>
<div id="links">
<button id="menu-close">Close</button>
<div id="codes">Codes</div>
<div id="gfx">Graphics</div>
<div id="tuts">Resources</div>
</div>
</div>