WordPress: JS is loaded but functions in it are not working



I have a js file named “main.js” and I enqueued it using wp_enqueue_script in function.php file. This file is getting loaded in my page-{slug}.php, but the functions in it are not executing at all.

The function.php file:

function df_enqueue_scripts() {

    wp_enqueue_script( 'main-js', get_template_directory_uri() . '/assets/src/library/js/main.js', array(), '1.0', true );
    wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/assets/src/library/js/bootstrap.min.js', array( 'jquery' ), '5.6', true );

}

// Register the df_enqueue_scripts with wp_enqueue_scripts hook.
add_action( 'wp_enqueue_scripts', 'df_enqueue_scripts' );

page-{slug}.php file:

<?php

get_header();
?>

<button type="button" id="ad-button">Ad</button>
<button type="button" id="mm-button">MM</button>
<button type="button" id="photo-button">Photography</button>
<div id="display-photo"></div>
<div id="display-mm"></div>
<div id="display-ad"></div>

<?php

get_footer();

main.js file:

$( '#photo-button' ).on( 'click',
function () {
    $( '#display-photo' ).html("Hello <b>world!</b>");
}
);

In short, I write anything in main.js file, the changes which I expect doesn’t happen or doesn’t reflect in my page-{slug}.php file.

Answer

I think, the problem with jQuery wrong usage. Probably, wrapping the function with jQuery allows using $ variable and could solve the problem

jQuery(function($){
        $( '#photo-button' ).on( 'click',
            function () {
                $( '#display-photo' ).html("Hello <b>world!</b>");
            }
        );
    })

The second required thing is to set jQuery as a dependency for your script and to update the script version to 1.1.

wp_enqueue_script( 'main-js', get_template_directory_uri() . '/assets/src/library/js/main.js', array( 'jquery' ), '1.1', true );


Source: stackoverflow