maguskrool maguskrool - 1 month ago 6
jQuery Question

Using $ instead of jQuery in wordpress child theme

$I'm building a wordpress (v. 3.6) site using a child theme of the Twenty Thirteen theme.
My theme's header.php has

<body <?php body_class(); ?> onResize="resizeHandler();">


This is the .js file for the theme, myChildTheme.js:

var myStuff;
function resizeHandler() {
myStuff = jQuery(".stuff");
console.log("resized, and here's stuff: "+ myStuff);
}


In order to use $ instead of "jQuery" I tried the solutions I found on the web. The new myChildTheme.js:

jQuery(document).ready(function($) {
var myStuff;
function resizeHandler() {
myStuff = $(".stuff");
console.log("resized, and here's stuff: "+ myStuff);
}
});


But then I get a console reference error saying that resizeHandler is not defined.

I have enqueued and registered the theme's scripts and styles in what I believe is the correct way.

functions.php:

function myChildTheme_scripts_styles() {
wp_enqueue_style( 'myChildTheme-fonts', myChildTheme_fonts_url(), array(), null );
}
add_action( 'wp_enqueue_scripts', 'myChildTheme_scripts_styles' );

function myChildTheme_scripts() {
wp_enqueue_script('myChildTheme_functions', get_stylesheet_directory_uri().'/js/myChildTheme.js', array('jquery'), '', true);
wp_enqueue_script('isotope_source', get_stylesheet_directory_uri().'/js/jquery.isotope.min.js', array('jquery'), '', true);
}
add_action( 'wp_enqueue_scripts', 'myChildTheme_scripts' );


Any hints on how I can get $ to work? Thanks.

Answer

You need to attach the resize event via jQuery itself. Try this:

<body <?php body_class(); ?>>
jQuery(document).ready(function($) {
    var myStuff;
    function resizeHandler() {
        myStuff = $(".stuff"); // note $ use here
        console.log("resized, and here's stuff: "+ myStuff);
    }

    $(window).resize(resizeHandler);
});

FYI your console will output resized, and here's stuff: [Object object] - this is normal.

Comments