Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The default behavior for jQuery is that it can be accessed in Javascript by using "$" or "jQuery":

...

  1. The best way to avoid this issue is to do this:

    Code Block
    languagejs
    (function($) {
    	var element = $(".class") // Will work!
    }(jQuery)
     
    var element = $(".class") // Will fail: $ is not defined

    Note: This will allow you to continue using $ as a selector within the block of code, between { }

  2. Alternately you can just use "jQuery": 

    Code Block
    languagejs
    var element = jQuery(".class") //  Will work!
     
    (function($) {
    	var element = $(".class") // Will work!
    }(jQuery)
     
    var element = $(".class") // Will fail: $ is not defined

    Note: If you go with this option you will have to use "jQuery" everywhere which can start making the code quite bloated

  3. The other option is to override the WordPress jQuery include to your own file which stops it being included in noConflict mode:

    Code Block
    languagephp
    //functions.php (Theme Functions)
    //FROM
    wp_enqueue_script( 'jquery' );	
     
    //TO
    wp_deregister_script('jquery');
    wp_register_script('jquery', get_bloginfo('template_url', 'display') . '/js/jquery.js');
            
    wp_enqueue_script( 'jquery' );	

    Note: There is good reason why by default jQuery is included in noConflict mode by defaults so it doesn't conflict with any other JavaScript libraries that use the dollar sign also, like MooTools or Prototype.

    WARNING: Be sure to add jQuery to the directory you just defined otherwise you will be getting loading errors