Cannot call a js function from external loaded file on wordpress - javascript

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.

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);

(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.

Related

Why is my onload not working in Wordpress?

I really need to use a onload and I don't understand why it's not working. I made a code snippet to test it out and yet again found that it didn't work. Is wordpress doing this? Or am I making a mistake? I found that events such as onclick and onchange are working.
function do_onload_event()
{
return '<div id="loadevent" onload="do_show_event(event)"></div>' . '<script>
function do_show_event(event)
{
console.log("on load event");
}
</script>';
}
add_shortcode('on_load_event','do_onload_event');
IMHO - Calling onload from in-post shortcode could have many issues of timing or executions. Also, I am not sure that it is possible ot hook to onLoad() or onready() more than once so it would be more compatible..
Since we are dealing with wordpress, you could try another approach using jQuery:
function add_my_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_init_script', 'MyScriptSource/etc', 'jquery', '1.0' ); // jQuery dependency
}
add_action( 'init', 'add_my_scripts' );
Then add another script that calls your method.
jQuery.noConflict();
jQuery(document).ready(function($) {
init();
});
You could of course try also for load event
jQuery(window).load(function($) {
// your function
});
or ..
(function($) {
// your function
})(jQuery);

Call JS function in Wordpress, noob question?

I have simple JavaScript function
function hide()
{
document.getElementById('div_sc_1').style.display = "none";
}
in my themefolder/js file I put
function add_scripts(){
wp_enqueue_script( 'quest',
get_stylesheet_directory_uri().'/js/quest.js',
array('jquery'),
'1.0.0',
false
);
}
add_action( 'wp_enqueue_scripts', 'add_scripts' );
in my function.php.
I can call my function from an <input type="submit" onClick="hide();">
BUT I want make something like that in my function.php
<?php
if(isset($_GET[xxx]))
{
<script>
hide()
</script>
}
?>
I don't understand why it doesn't work.
Since you are adding it directly in the dom, so It may run before the target element even exists, Javascript requires an element to available first in order to do its job.
You have to add it once the document is fully loaded so that it can work.
Maybe try this jQuery(document).ready(function($) { hide(); });
If you add it after the document is ready then Javascript will be able to find your element and execute related functions.

Execute a document.ready in functions.php

I need to run a script after a hook is fired in my functions.php file. Im using a wordpress mailchimp plugin, I need to do some text inserts and display = "none", etc, in the html:
add_action( 'mc4wp_form_success', function() {
// do something
echo '<script type="text/javascript">',
'console.log("starting....");', // this works
'document.getElementById("mailchimp-is-subscribed").style.display = "none";',
'document.getElementById("mailchimp-success-form").style.display = "block";',
'console.log("end");',
'</script>';
});
The error I got was style is null. I assume the document is not ready? $ does not work. Am I doing this wrong? I need to run that code after that hook is called. Putting the code in .js file works great. Thanks
You can add your code as an on DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', function () { ..your_code... }, false);
Check this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Getting jQuery to work in new build WordPress theme

I am new to jQuery and have tried to get scripts to work to no avail. I would like to simplify my script to just see that my theme is in fact recognizing my scriptfile.js
My js file is just:
var success = 'SUCCESS!';
jQuery('nav .home a').hover(function()
{
echo(success);
});
my functions.php file has this:
<?php
function add_my_script() {
wp_enqueue_script(
'preview',
get_template_directory_uri() . '/js/scriptfile.js',
array('jquery')
);
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );
?>
My header.php contains:
<script type="text/javascript"><!--//--><![CDATA[//><!--
jQuery(document).ready(function(jQuery){
});
//--><!]]></script>
I am not getting any errors in firebug, but no output either.
Not sure if this is the problem but first of all your selector is not exactly right.
var success = 'SUCCESS!';
jQuery('nav .home a').hover(function(){ ... });
nav should be .nav for class or #nav for id
echo(success);
Unless echo() is a function somewhere it will not work. If you want to show an alert message use alert(success)
I believe what's happening is that your script file is being included fine but the way it's written the hover event attachment will happen before the DOM is ready. Try this, simply say alert(success); in your js file and see if the alert pops up. If it does, then wrap the hover event handler in a function in your script file and call that function from the document.ready function handler in your header.php. By the way, what's the echo function? Probably you are looking for alert.

Calling external js function from another external js file gives "Undefined" error

I have this code in plugins.js:
$(document).ready(function() {
watermark = function(elemId, text, hoverClass, normalClass, parentId){
// onFocus event
$("#"+elemId).focus(function(){
($(this).val()==text)
$(this).val('');
(parentId!=0)
byId(parentId).className = hoverClass;
});
// onBlur event
$("#"+elemId).blur(function(){
($(this).val()=='')
$(this).val(text);
(parentId!=0)
byId(parentId).className = normalClass;
});
}
});
Then I have this in the index.js file:
new watermark("footer_contact_name", "Name", "footer_form_text_active", "footer_form_text", "footer_form_field_1");
Everything works when written in the same js file, but when calling it like this from the index.js file, I get an undefined function error in FireFox, using Firebug to debug.
Any ideas?
Thanks
BTW: I include these in index.html like this:
<script src="scripts/plugins.js" type="text/javascript"></script>
<script src="scripts/index.js" type="text/javascript"></script>
You need to call the function after the document gets ready - wrap it in:
$(document).ready(function() { });
The watermark functions gets declared when the DOM is ready to be manipulated (inside $(document).ready(function(), therefor won't be available the moment your index.js gets included.
EDIT:
You kind of have to make the call to watermark after the DOM is ready to be manipulated, since it uses elements in the DOM. A solution would be to declare your watermark function outside the $(document).ready(function(), and then call it from index.js inside a $(function() { (shorthand for $(document).ready()):
functions.js:
watermark = function(elemId, text, hoverClass, normalClass, parentId){
// function logic
}
index.js:
$(function() {
new watermark("footer_contact_name", "Name", "footer_form_text_active", "footer_form_text", "footer_form_field_1");
}
You're only defining the watermark() function after the DOM is loaded. You could define it outside the $(document).ready() call and you could embed the $(document).ready() call inside it, so it will execute when the DOM is loaded, but be available before that.
For example:
watermark = function(elemId, text, hoverClass, normalClass, parentId) {
$(document).ready(function() {
/* ... */
}
}

Categories

Resources