Quick summary: I have a function in a .js file that's loaded thanks to wp_enqueue_scripts. Now when I try to call that function from the HTML in one of my template files, it doesn't seem to work...
I've researched this and I think I'm doing it all right, but obviously I must have missed something and can't quite put my finger on what it is.
.
So, in functions.php, I have the following code:
function script_assets() {
wp_enqueue_script( 'js-code', get_template_directory_uri() . '/js/js-code.js' );
}
add_action( 'wp_enqueue_scripts', 'script_assets' );
This works as intended, and results in this being added to the head:
<script type='text/javascript' src='http://.../js/js-code.js?ver=4.1.1'></script>
.
Then, in header.php, after wp_head();
I have the following bit of code:
<?php if ( !is_front_page() ) : ?>
<script type="text/javascript">
/* <![CDATA[ */
setTimeout(function(){ deploy($("#rightsec .deployer")); }, 200);
setTimeout(function(){ switchMobile($("#switcher")); }, 200);
/* ]]> */
</script>
<?php endif; ?>
The PHP bit works correctly, the script tags and everything in between go into the HTML whenever I'm not on the front page as intended. It goes after js-code.js is loaded via the line I pasted above. Both deploy()
and switchMobile()
are functions in js-code.js and I know they work, as I use them with no issue in a different context.
However Chrome throws
Uncaught ReferenceError: deploy is not defined
Uncaught ReferenceError: switchMobile is not defined
and the functions are not executed...
I know the question of 'how to call JS functions from HTML' has been asked countless times, but like I said I've been reading many pages and they all seem to say the same thing, which I've followed to the letter, and it still doesn't work...
Any ideas? Thanks.
New developments:
So, it turns out that, for some weird reason, if I only call the functions without using setTimeout()
, the second one* — switchMobile()
— works properly... but not the first one. If I reverse them so that deploy()
is after switchMobile()
, then this time deploy()
works. I am utterly confused :s
*for the sake of clarity my initial example only had one function, when in practice I am calling two. I've edited the question to reflect that.
UPDATE
Tried enclosing the function calls in $(document).ready(function(){ .. });
, tried using switchMobile(jQuery('#switcher'));
, tried not using JQuery at all (with document.getElementById("switcher")
)... Nothing works. Adding an alert()
right next to the function calls works as intended...