I am loading jQuery and my main.js file in the functions.php file as such:
function my_scripts() {
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js", false, null);
wp_enqueue_script('jquery');
}
wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '12303', true);
}
add_action( 'wp_enqueue_scripts', 'ninjatrader_scripts' );
All good here. I have a function in the main.js file I want to call only on specific page templates and am trying to do that via shortcode, but it always returns that the function is undefined.
Here is the function located in main.js:
function menu_sticky() {
var div_top = $('#hero-menu-row-anchor').offset().top;
var navCont = $('#hero-menu-row')
var nav = $('#menu-blognav');
var logo = '<li id="hero-menu-logo"><a href="http://ninjatrader.com" target="_self">NinjaTrader</a></li>';
var visible = false;
$(window).scroll(function () {
if ($(this).scrollTop() > div_top) {
navCont.addClass("fixed");
if(!visible) {
nav.prepend(logo);
visible = true;
}
} else {
navCont.removeClass("fixed");
if(visible) {
$('#hero-menu-logo').remove();
visible = false;
}
}
});
}
and the shortcode in functions.php
function sticky() {
echo '<script>jQuery(function(){ menu_sticky(); });</script>'
}
add_shortcode('stickynav', 'sticky');
And when I put it in a template, it returns “ReferenceError: menu_sticky is not defined” how do you go about loading functions in specific templates correctly?
FWIW, I figured out a way to make this work. Im sure its not ‘the’ way to do it, and I would still greatly appreciate any knowledge. It is just a different way to write the js in PHP I guess, but it took me a bit. Basically in the functions.php file, echo out the js from ‘main.js’ and include the $(function() { menu_sticky(); }); in it. Then use the shortcode as normal.
An alternative option would be to set a flag in a variable depending on whether the sticky nav should be called or not and then call the function from the main.js file.
It should be something like this:
After this you can also reuse the MY_MODULE variable to prefix your custom functions, so you don’t pollute the global namespace – you can even prefix your menu_sticky function: