0

I am trying to load the chosen library: http://harvesthq.github.com/chosen/

I am enqueuing a .js file as below:

wp_register_script( 'js_custom', plugin_dir_url( __FILE__ ) . 'js/jquery.js', false );
wp_enqueue_script ( 'js_custom' );

Inside the .js file I loading chosen like this:

jQuery(document).ready(function($){
  $('.chzn-select').chosen();
});

But I keep getting this error:

TypeError: Result of expression 'jQuery(".chosen").chosen' [undefined] is not a function.

1
  • 1
    What is in js/jquery.js?
    – s_ha_dum
    Feb 13 '13 at 23:28
2

You forgot to load chosen library:

wp_register_script( 'js_chosen', 'https://raw.github.com/harvesthq/chosen/master/chosen/chosen.jquery.js', array('jquery') );
wp_register_script( 'js_custom', plugin_dir_url( __FILE__ ) . 'js/jquery.js', array('jquery', 'js_chosen') );
wp_enqueue_script ( 'js_custom' );
1
  • FYI to people who try the above. Chosen uses coffee script now so that link doesn't lead to anywhere. Also, when serving files from github try rawgit.com as raw.github.com doesn't always work well. Or use something like cdnjs. Mar 5 '15 at 19:19
0

This is old but for anyone else reading this question, don't use github as it won't work.

<?php

/**
 * Plugin Name: Add JQuery Chosen Quickly
 * Plugin URI: http://wordpress.stackexchange.com/questions/85824/
 * Description: Test/Add chosen to site without adding any files
 * Version: 1.0
 */

function enqueue_chosen_jquery() {
    wp_register_style( 'chosencss', 'https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css', false, '1.1.0', 'all' );
    wp_register_script( 'chosenjs', 'https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js', array( 'jquery' ), '1.1.0', true );
    wp_enqueue_style( 'chosencss' );
    wp_enqueue_script( 'chosenjs' );
    }
add_action( 'wp_enqueue_scripts', 'enqueue_chosen_jquery' );

// Assuming jQuery is loaded in the head
function chosen_jquery_inline() {
if ( wp_script_is( 'jquery', 'done' ) ) { ?>
    <script type="text/javascript">
    jQuery(document).ready(function ($) {
        $( ".chzn-select" ).chosen();
    });
    </script>
<?php }
add_action( 'wp_head', 'chosen_jquery_inline', 999 ); 
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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