Toggle Class &this


I just discovered Beans, and I'm trying to code a site I have in mind while I learn it. That said, I have a problem with a toggle element. I created the element, assigned the toggle action, and it displays and hides the menu, but I would like the class that is applied to the menu to be applied to the clickable element itself, so it can change from hamburger icon to a cross. Just like you would do with jQuery and this snippet:

$('#toggle').click(function() {

I tried applying the same ID to the clickable element, but it doesn't work.

Also, I tried enqueuing the js snippet, but that does no work at all...

I'm completely lost now. Any help?

Hey Enzo,

Your snippet won't work as it is, you have to declare the $ and fire your code only when the document is ready as follow:

( function( $ ) {
  $( document ).ready( function() {
   $( '#toggle' ).click( function() {
      $( this ).toggleClass( 'active' );
    } );
  } );
} )( window.jQuery );

Please make sure to enqueue your JS file properly.

Happy coding,

Write a reply

Login or register to write a reply, it's free!