Add custom JS


I've been trying to add some custom js, but I can't make it work, and I don't know why. I just need to add this JS snippet:

$('#toggle').click(function() {
   $(this).addClass('active');
   $('#example-primary-mobile-menu').toggleClass('active');
});

I tried different things, for example:

add_action( 'wp_enqueue_scripts', 'my_function_name' );

function my_function_name() {

 beans_compile_js_fragments( 'jquery', array( get_stylesheet_directory_uri() . '/js.js' ) );

}

And also:

function wpdocs_theme_name_scripts() {
    wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );

I've tried some more things, but as they didn't work I just deleted them and cannot remember now (my head is a js mess right now...).

What am I doing wrong? How could I get that snippet to work? Thank you very much!


Hey Enzo,

You last snippet is correct but you have to replace get_template_directory_uri() (which should be used in parent themes) with get_stylesheet_directory_uri() which must be used in child themes.

Happy coding,

Write a reply

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