0

I am using a child theme and trying to call custom JS from /child-theme/js/custom.js

In my function file I have:

function myprefix_enqueue_scripts() {
    wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/js/custom.js', array(), true );
}
add_action( 'wp_enqueue_scripts', 'myprefix_enqueue_scripts' );

In Javascript I have:

$( document ).ready(function() {
    alert( "Here's your javascript!" );
});

var textID = document.getElementById("logo.no-image"); // go and take the Text from the ID
var text = textID.innerHTML; // Take the text from the
var toChange = text.split(""); // Separrate each letter into array
var newText = ""; // buffer text
var aClassName = ["red", "green", "blue"]; // class name that you want
var colorNumber = 0; // counter to loop into your class

for (var i=0, ii=toChange.length; i<ii; i++){
        if(colorNumber == aClassName.length){ // if you reach the end of your class array
        colorNumber = 0; //Set it back to 0
    }
    // Add between each letter the span with your class
    newText += "<span class="+aClassName[colorNumber]+">"+toChange[i]+"<\/span>";
    colorNumber++
}
// Output your text into the web
textID.innerHTML = newText;

I included the alert to test whether or not the script is being loaded

1 Answer 1

1

In WP jQuery works in compatibility mode by default. It means that the typical $ shortcut for jQuery doesn't work, so it doesn't conflict with any other JavaScript libraries that use the dollar sign also, like MooTools or Prototype.

So you should use jQuery instead of $ in your JS file.

Of course you can wrap the code in an anonymous function where you pass in jQuery to be mapped to $.

(function($) {

    // $ Works here!
    // console.log($);

})( jQuery );

You also have to add jquery as a dependency when you enqueue the script:

function myprefix_enqueue_scripts() {
    wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'), true );
}
add_action( 'wp_enqueue_scripts', 'myprefix_enqueue_scripts' );

PS. I assume that your file is enqueued properly and it really is in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.