Home Is there an easier way to repeat multiple lines of code JQUERY
Reply: 2

Is there an easier way to repeat multiple lines of code JQUERY

jonwa
1#
jonwa Published in 2018-01-11 14:33:40Z

I have multiple functions that use different elements to perform the same task. This is for a mobile menu. So I have a function that when menu button is clicked..open mobile menu, transform hamburger to an "X" and make the page overlay visible. I also have a function that closes the menu when the menu is open and the user changes the orientation of the device. I also have a function when the user clicks/taps anywhere outside of the mobile menu it will close the menu (as well as clicking "X").

In these functions I repeat myself a lot, using "removeClass or toggleClass". Is there an easier way to represent all of these lines of code so that they're declared once somewhere else and then called within all of these functions? A variable maybe? Because I don't like repeating myself.

This is the repeat/example code.

$("#mobile-menu").removeClass("enabled1");
$("#menu-button").removeClass("open");
$("#mobile-menu-wrapper").removeClass("enabled1");
$("#page-overlay").removeClass("enabled1");

smilebomb
2#
smilebomb Reply to 2018-01-11 14:40:15Z

You want to abstract out the 'opening' and 'closing' of the menu to a function...

function openMenu(){
  //include all your slide toggles and what not here
}

function closeMenu(){
 $("#mobile-menu").removeClass("enabled1");
 $("#menu-button").removeClass("open");
 $("#mobile-menu-wrapper").removeClass("enabled1");
 $("#page-overlay").removeClass("enabled1");
}

...and then call that function from wherever you need to.

$('button').on('click',function(){
  openMenu();
});

$('button2').on('click',function(){
  closeMenu();
});
mdatsev
3#
mdatsev Reply to 2018-01-11 14:43:08Z

You could have an array of all the elements you want to remove the class and pass it to a function where for each you remove the class.

function allRemoveClass(selectors, cl) {
  selectors.forEach((s) => $(s).removeClass(cl));
}

let enabled = ["#mobile-menu", "#mobile-menu-wrapper", "#page-overlay"];
allRemoveClass(enabled, "enabled1");

let opened = ["#menu-button"];
allRemoveClass(opened, "open");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.325684 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO