I am having troubles calling a function from a external loaded file.
I have search_form.php, from where i call the function, the client.js file where the functions are defined, and the plugin_functions.php file where i load the client.js file.
In plugin_functions.php file i have the following code:
console.log('loaded_client');
function load_client_scripts() {
wp_register_script('js-client', PLUGIN_URL.'includes/js/client.js',array('jquery'),false);
wp_enqueue_script( 'js-client' );
};
add_action( 'wp_enqueue_scripts', 'load_client_scripts' );
In client.js i define the function as follows:
(function($) {
function validateForm(){
console.log('Form validated');
};
})( jQuery );
Finally, in search_form.php i call the function with onclick:
<div onclick="validateForm()">
CLICK ME
</div>
Now, the js file is loading properly, because i get the console output 'loaded_client'. However, when i click the div, i get ReferenceError: validateForm() is not defined.
What am i doing wrong? It surely is a scope problem, but i cannot figure it out.
(function($) {
window.validateForm = function(){
console.log('Form validated');
};
})( jQuery );
<div onclick="window.validateForm()">
CLICK ME
</div>
You are correct, in your example the scope is wrong because wrapped in (function($) {
this anonymous function.
Edit for clarity: If you want it to be a globally accessible function you can attach it to the window object like on this example.
Please try to loading JS into footer.
Set footer true. I think it will work.
wp_register_script( 'js-client', PLUGIN_URL.'includes/js/client.js',array('jquery'),false,true);