Jquery error is not a function

"Error: $ is not a function", this is the error that was being thrown back at me while working on a WordPress site the other day. However for the life of me I couldn't see why my, usual fine JavaScript code, was failing. Was it a problem with my jQuery code, my WordPress installation or both? I…

“Error: $ is not a function”, this is the error that was being thrown back at me while working on a WordPress site the other day. However for the life of me I couldn’t see why my, usual fine JavaScript code, was failing. Was it a problem with my jQuery code, my WordPress installation or both?

I reduced my code down to producing an alert when the DOM was ready, but still it threw the error:

Error: $ is not a function

Well I’m sure we’ve all had this error before, usually when we break or incorrectly reference the jQuery core library. However I doubled checked and it was definitely pointing to the right file.

After a little spree on Google and a bit of research, I found that WordPress loads jQuery in a ‘no-conflicts’ mode to significantly reduce the likelihood of it conflicting with other third party libraries that a owner may install on their blog/site.

What this means in my scenrario, was exactly what the error stated. In ‘no conflict’ mode the $ shortcut is disabled, so you must replace it with the word ‘jQuery’ (notice the capitalised Q).

So if you had a piece of script such as:

[js]$(document).ready(function() {
$(«.someClass»).hide();
$(«#elementID .anotherClass»).eq(2).show();

}[/js]

You’d replace all the dollar symbols with the string ‘jQuery’.

[js]jQuery(document).ready(function() {
jQuery(«.someClass»).hide();
jQuery(«#elementID .anotherClass»).eq(2).show();

}[/js]

So thats one way to circumnavigate the conflict free wrapper that WordPress applies to jQuery.

Another approach, jQuery and conflict modes…

In my situation I was importing some large chunks of jQuery code libraries, so I didn’t really want to duplicate my existing libraries just for the purposes of having one in ‘normal’ mode and one in ‘no-conflicts’ mode.

Then I read you can easily override the ‘no-conflict’ compatibility mode, score! Now normally you shouldn’t just jump in and override such a system, it is there for a reason you know! The WordPress system is built by some very brainy people, much better than myself, so if they think its a requirement for a vanilla install of their system then so be it. However with the project I was working on, I knew exactly what was installed already, and that no further plugins will be scheduled to be installed for a long time. Either way I dropped a few comments in the top of the jQuery source file, as well as a ReadMe file in the jQuery directory, just in case in the future it did become a problem.

Anyway… the solution turned out to be simple passing the dollar shortcut in as a argument for the ready function applied to the document. So our example code becomes:

[js]jQuery(document).ready(function( $ ) {
$(«.someClass»).hide();
$(«#elementID .anotherClass»).eq(2).show();

}[/js]

Notice we still have to use the conflict free wrapper to begin with, but once the page is ready the dollar shortcut will work for your existing code. So no need to go changing those libraries!

Hope that helps someone out, I was nearly tearing my hair out trying to work out why the error “$ is not a function” was being thrown

The JavaScript exception «is not a function» occurs when there was an attempt to call a
value from a function, but the value is not actually a function.

Message

TypeError: "x" is not a function. (V8-based & Firefox & Safari)

Error type

What went wrong?

It attempted to call a value from a function, but the value is not actually a function.
Some code expects you to provide a function, but that didn’t happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method
on does not have this function? For example, JavaScript Objects have no
map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to
provide a function in order to have these methods working properly:

  • When working with Array or TypedArray objects:
    • Array.prototype.every(), Array.prototype.some(),
      Array.prototype.forEach(), Array.prototype.map(),
      Array.prototype.filter(), Array.prototype.reduce(),
      Array.prototype.reduceRight(), Array.prototype.find()
  • When working with Map and Set objects:
    • Map.prototype.forEach() and Set.prototype.forEach()

Examples

A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

const x = document.getElementByID("foo");
// TypeError: document.getElementByID is not a function

The correct function name is getElementById:

const x = document.getElementById("foo");

Function called on the wrong object

For certain methods, you have to provide a (callback) function and it will work on
specific objects only. In this example, Array.prototype.map() is used,
which will work with Array objects only.

const obj = { a: 13, b: 37, c: 42 };

obj.map(function (num) {
  return num * 2;
});

// TypeError: obj.map is not a function

Use an array instead:

const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num * 2;
}); // [2, 8, 18]

Function shares a name with a pre-existing property

Sometimes when making a class, you may have a property and a function with the same
name. Upon calling the function, the compiler thinks that the function ceases to exist.

function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
};

const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function

Use a different property name instead:

function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; //Using this.dogName instead of .name
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
};

const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }

Using brackets for multiplication

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// 2 x (3 + 5) is 16

Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

const helpers = function () {};

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
};

export default helpers;

The correct import usage (App.js):

import helpers from "./helpers";

See also

As you may have noticed during WordPress development, sometime it’s very hard to figure it out how to enqueue script right way?

Should I just add script at the bottom of page in footer? Should I add script in the header of WordPress site? Well, there are some standards established by WordPress framework which everybody should follow.

In this tutorial, we will go over how to enqueue script Typed.min.js right way to your WordPress theme and fix Uncaught TypeError: $ is not a function jQuery error.

This tutorial will help you if you have any of below questions:

  • How to Properly Add JavaScripts and Styles in WordPress
  • How to enqueue Scripts and Styles in WordPress?
  • Loading CSS and JavaScript Into WordPress the Right Way

Let’s understand the scenario first:

For my other Premium site, I wanted to use Typed.min.js with correct WordPress enqueue options.

While working on setting up above effect, I found some strange error which I never faced before. Take a look at that error below:

Above error happened before wrong way to include jQuery to my site.

Before – Using putting below code into Footer Manually:

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://pro.crunchify.com/typed.min.js" type="text/javascript"></script>

<script>
  $(function(){
      $(".element").typed({
        strings: ["App Shah...", " an Engineer (MS)...","a WordPress Lover...", "a Java Developer..."],
        typeSpeed:100,
        backDelay:3000,
        loop:true
      });
  });
</script>

After – Right way to enqueue script in functions.php

function typed_script_init() {
    wp_enqueue_script( 'typedJS', 'https://pro.crunchify.com/typed.min.js', array('jquery') );
}
add_action('wp_enqueue_scripts', 'typed_script_init');

function typed_init() {
    echo '<script>
	jQuery(function($){
      		$(".element").typed({
      	 	strings: ["App Shah...", " an Engineer (MS)...","a WordPress Lover...", "a Java Developer..."],
      	 	typeSpeed:100,
     		backDelay:1000,
     		loop:true
	});
     });</script>';
}
add_action('wp_footer', 'typed_init');

There are two things in above code:

  1. First of all we are using wp_enqueue_script function which has 3rd parameter to use jQuery loaded with WordPress. There is no need to add jQuery manually 🙂 . This is THE right way to enqueue script in wordpress.
  2. We also changed function $(function(){ to jQuery(function($){ in order to fix Uncaught TypeError: $ is not a function error.

Hope this will help you fix and enqueue jQuery error on your site.

As per suggestion from commenter Jaikangam, here are few more options to fix this error:

If you have file crunchify.js then other option is to start the file with like this.

Option-1)

(function($){
$(document).ready(function(){

     // write code here

});

Option-2)

jQuery(document).ready(function(){

    // write code here

});
})(jQuery);

Happy blogging.


Join the Discussion

If you liked this article, then please share it on social media. Still have any questions about an article, leave us a comment.

Share:

I’m an Engineer by profession, Blogger by passion & Founder of Crunchify, LLC, the largest free blogging & technical resource site for beginners. Love SEO, SaaS, #webperf, WordPress, Java. With over 16 millions+ pageviews/month, Crunchify has changed the life of over thousands of individual around the globe teaching Java & Web Tech for FREE.

Reader Interactions

Currently, WordPress is the best website builder on the internet. It has gained its popularity due to the many features it offers. However, much like everything else, as good as this CMS may be, it comes with a few issues as well.

One of these issues is the $ is not a function WordPress error. This error can cause your website to display the 404 pages.

In this article, we would like to discuss the $ is not a function WordPress error.

What is the $ is not a function of WordPress Error?

$ is not a function WordPress error occurs when the code comes before the jQuery library. For example, if a plugin or theme calls a code before calling the right library, you get this error.

By default, WordPress doesn’t understand $ as jQuery and you have to make some modifications to fix this error. However, this process could be challenging for some users without any programming knowledge.

$ is not a Function WordPress Error

As always, before making any changes to the core files of WordPress, we recommend you get a full backup of your website. This is a must, because if you misplace a simple “;” you could completely ruin the website.

The backup is there to restore your website back to what it was before you made the modifications.

Use $ instead of jQuery in WordPress

One of the easy fixes is to use $ in WordPress instead of jQuery. You will have to enqueue the script in your theme’s functions.php file.

wp_enqueue_script("jquery");

Most WordPress theme and plugin developers are aware of this issue. Thus, they rather use jQuery instead of the $ sign to be safe.

For example, the normal jQuery anywhere should look like this:

$(“#element”).function();

In WordPress the jQuery looks like this:

jQuery(“#element”).function();

Writing jQuery in a script hundreds of times makes it harder to read and increases the size of the script. It’s recommended that you map jQuery to be mapped to $ in the footer of your website. Simply, copy and paste the following code in the footer file of your theme:

(function($) {
	// console.log($);
})( jQuery );

If you would like to add the code to the header of your theme, simply use the following code:

jQuery(document).ready(function( $ ) {
	// console.log($);
});

With this code, you can write a clean script for your website.

Use a New Name for jQuery

There are many changes you can make to the jQuery, one of them is the ability to change the $ to any particular name you have in mind. To use a new name for jQuery, simply use the following code and replace the name element with the name you have in mind.

var j = jQuery.noConflict();
j( "div p" ).hide();
// Do something with another library's $()
$( "content" ).style.display = "none";

Disable noConflict Mode

To turn off the jQuery.noConflict in WordPress, use the following command:

$ = jQuery.noConflict(true);

This code should turn off the noConflict mode completely.

The $.noConflict command gives you the ability to control the $ variable back to whatever library it was first assigned to. This command makes sure that jQuery doesn’t have any confliction with the $ object of other libraries.

Conclusion

In this article, we discussed the $ is not a function WordPress error. This error is usually caused when your code is called before calling the jQuery and if you are using $ instead of jQuery in WordPress.

By default, WordPress uses jQuery instead of the normal method of $ and this could cause your website to display the 404 error.

You can use a function in both header or footer to change the name $ to your desired name. Besides, you can disable the noConflict mode in WordPress. noConflict mode gives you the ability to control the $ variables and revert them to whatever library they were originally assigned to.

This mode prevents the confliction between the $ object of other libraries.

Понравилась статья? Поделить с друзьями:
  • Jquery ajax json error
  • Jquery ajax error пример
  • Jquery ajax error php
  • Jquery ajax error message
  • Jquery ajax error internal server error