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:
JavaScript
x
10
10
1
function df_enqueue_scripts() {
2
3
wp_enqueue_script( 'main-js', get_template_directory_uri() . '/assets/src/library/js/main.js', array(), '1.0', true );
4
wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/assets/src/library/js/bootstrap.min.js', array( 'jquery' ), '5.6', true );
5
6
}
7
8
// Register the df_enqueue_scripts with wp_enqueue_scripts hook.
9
add_action( 'wp_enqueue_scripts', 'df_enqueue_scripts' );
10
page-{slug}.php file:
JavaScript
1
16
16
1
<?php
2
3
get_header();
4
?>
5
6
<button type="button" id="ad-button">Ad</button>
7
<button type="button" id="mm-button">MM</button>
8
<button type="button" id="photo-button">Photography</button>
9
<div id="display-photo"></div>
10
<div id="display-mm"></div>
11
<div id="display-ad"></div>
12
13
<?php
14
15
get_footer();
16
main.js file:
JavaScript
1
6
1
$( '#photo-button' ).on( 'click',
2
function () {
3
$( '#display-photo' ).html("Hello <b>world!</b>");
4
}
5
);
6
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.
Advertisement
Answer
I think, the problem with jQuery wrong usage. Probably, wrapping the function with jQuery allows using $ variable and could solve the problem
JavaScript
1
8
1
jQuery(function($){
2
$( '#photo-button' ).on( 'click',
3
function () {
4
$( '#display-photo' ).html("Hello <b>world!</b>");
5
}
6
);
7
})
8
The second required thing is to set jQuery as a dependency for your script and to update the script version to 1.1.
JavaScript
1
2
1
wp_enqueue_script( 'main-js', get_template_directory_uri() . '/assets/src/library/js/main.js', array( 'jquery' ), '1.1', true );
2