Gustavo Cohen Gustavo Cohen - 3 months ago 10
jQuery Question

Can't get my js script to work inside wordpress

I enqueued a file "my-script" inside wordpress through function.php in order to add some jQuery functionality to the site. The main purpose was to hide the carousel controls if only one item was present (one image or div) Unfortunately I can't even get wordpress to even read the file. I placed a simple alert to show after document is loaded and nothing happens. This is how I enqueued several scripts including "my-script"

/* Enqueuing Scripts */
function enqueue_my_scripts() {
wp_enqueue_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', array('jquery'), '1.12.4', true);
wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap JavaScript goodness
wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js' , array('jquery'), true);
}

add_action('wp_enqueue_scripts', 'enqueue_my_scripts');

function enqueue_my_styles() {
wp_enqueue_style( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );
wp_enqueue_style( 'my-style', get_template_directory_uri() . '/style.css');
wp_enqueue_style( 'my-ot-style', get_template_directory_uri() . '/dynamic.css');

}
add_action('wp_enqueue_scripts', 'enqueue_my_styles');


and this is the contents of 'my-script' file

$(document).ready(function(){
alert( "Test My-Script" );
});


Nothing happens. I currently have the divs with the carousel controls hidden through CSS, but would like to get it working so the site evaluates if it has just one item before hiding them

Thanks in advance!!

Answer

In WordPress you cannot use $ just like that to reference your own loaded jQuery. This is because WordPress has called jQuery.noConflict().

One solution is to reference jQuery instead of $. If you still want your script to use $, then write this:

jQuery(document).ready(function($){
    // ... your code that can reference $ comes here.
});

Don't forget to specify the $ as callback function parameter.