Gustavo Cohen Gustavo Cohen - 10 months ago 49
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', '', array('jquery'), '1.12.4', true);
wp_enqueue_script( 'bootstrap-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', '' );
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

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!!


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:

    // ... your code that can reference $ comes here.

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