Skip to content

Why is my Javascript toggleClass code not working?

I am trying to add the .open class to a div when the it is click. It is currently not working, and I’m not sure why.

Here is my JS

(function ($) {
    // sticky footer form class toggle on click
    $(".nb-form .form-header").on("click", function () {
        $(".nb-form").toggleClass("open");
    });

Here is my HTML

<div class="nb-form">
    <div class="form-header">
        <p class="title">Request a Quote</p>
        <img src="https://soldaf.ca/wp-content/uploads/2020/11/Andrew-headshot-e1606168346405.jpg" alt="Andrew Foster" class="user-icon">
    </div>    

    <div class="form-content">
        <p class="message">Send us a message or give us a call at <span class="d-inline-block">(403) 915-6195.</span></p>   
        <?php echo do_shortcode( '[[contact-form-7 id="4545" title="Contact form 1"]]' ); ?>
    </div>
  </div>

For reference, I am trying to replicate exactly what is happening with the bottom right “have a question” widget on this website https://soldaf.ca/

Thanks,

Answer

The issue appears to be because the syntax you’re using to contain the jQuery code is an Immediately Invoked Function Expression (IIFE), and not a jQuery document.ready handler. This means that your code is running before the DOM has loaded, and therefore the elements you’re trying to bind event handlers to do not exist yet.

To fix the problem, use a standard jQuery document.ready event handler:

jQuery($ => {
  // sticky footer form class toggle on click
  $(".nb-form .form-header").on("click", () => {
    $(".nb-form").toggleClass("open");
  });
});
/* Note this CSS is only for demo purposes and isn't relevant to the issue */
img { width: 50px; }
.nb-form .form-content { display: none; }
.nb-form.open .form-content { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nb-form">
  <div class="form-header">
    <p class="title">Request a Quote</p>
    <img src="https://soldaf.ca/wp-content/uploads/2020/11/Andrew-headshot-e1606168346405.jpg" alt="Andrew Foster" class="user-icon" />
  </div>

  <div class="form-content">
    <p class="message">Send us a message or give us a call at <span class="d-inline-block">(403) 915-6195.</span></p>
    <?php echo do_shortcode( '[[contact-form-7 id="4545" title="Contact form 1"]]' ); ?>
  </div>
</div>