I want to add/remove a class on the html and body tags in the dom when my nav menu is opened or closed. Is this the most optimal way of writing this logic?

$( '#navbarNav' ).on( 'show.bs.collapse', function() {
    $( 'html, body' ).addClass( 'noscroll' );

$( '#navbarNav' ).on( 'hide.bs.collapse', function() {
    $( 'html, body' ).removeClass( 'noscroll' );
  • \$\begingroup\$ It would be a good idea to mention that you are using Bootstrap, especially specifially which JS plugins. \$\endgroup\$ – RoToRa Sep 29 '19 at 9:48

Don't repeat the queries. Store any queries that are called more than once in a variable, and utilize jQuery's chaining:

const navbarNav = $( '#navbarNav' );
const htmlBody = $( 'html, body' );

navbarNav.on( 'show.bs.collapse', function() {
    htmlBody.addClass( 'noscroll' );
}).on( 'hide.bs.collapse', function() {
    htmlBody.removeClass( 'noscroll' );

Why are you setting the class on both the html and body elements? Either should be sufficient.

Name the class semantically. Just like you call a class for important text "important" and not "red", just because it happens to be red, you don't call a class that indicates whether the main navigation is open "noscroll" but "main-nav-open" (for example).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.