1

I'm trying to make my code check if an element with an ID named navbarSupportedContent has a class named show. My code doesn't seem to work and I don't know why.

I'm using Bootstrap, so Bootstrap will do most of the work for me but whenever I press a button a class named show will be a added to the html element below.

Whenever the class show is detected on #navbarSupportedContent the function should trigger but nothing happens.

$(document).ready(function() {
  $("#navbarSupportedContent").change(function() {
    console.log("Change detected");
    if ($('#navbarSupportedContent').hasClass('show') == true) {
      console.log("Scroll is locked");
      $('body').addClass('lock-scroll');
    } else {
      console.log("Scroll is unlocked");
      $('body').removeClass('lock-scroll');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="navbarSupportedContent" class="collapse navbar-collapse"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
placeholder
  • 162
  • 1
  • 9
  • There is no event raised in the DOM when a `class` changes. Depending on whatever Bootstrap control you're using to change the class you could potentially listen for one of its events instead. Failing that, your final option is to use a MutationObserver. See the duplicate I marked for more information about that. – Rory McCrossan Dec 11 '19 at 15:53

2 Answers2

2

Change events only trigger for form elements when the value is changed for form elements, it won't trigger for an element like div when some attributes changed.

You can use MutationObserver for listening attribute change.

var $div = $('#navbarSupportedContent');

var observer = new MutationObserver(function(mutations) {
  console.log("Change detected");
  if ($('#navbarSupportedContent').hasClass('show') == true) {
    console.log("Scroll is locked");
    $('body').addClass('lock-scroll');
  } else {
    console.log("Scroll is unlocked");
    $('body').removeClass('lock-scroll');
  }
});

observer.observe($div[0], {
  attributes: true,
  attributeFilter: ['class']
});

$div.click(() => $div.toggleClass('show'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="navbarSupportedContent" class="collapse navbar-collapse">abc</div>

Refer : https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit , https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You can try to change

if( $('#navbarSupportedContent').hasClass('show') == true ) 

to

if( $('#navbarSupportedContent').hasClass('show')) 
  • 1) While your example is better practice, they are logically identical and will make no difference. 2) This will only work if the class exists when the JS runs, which the OP states is not the case, otherwise the code would already be working. – Rory McCrossan Dec 11 '19 at 15:52