How to use jQuery and $ sign in WordPress

Photo of author
Written By geekerhub

Experienced WordPress developer with over 10 years of experience working with the platform

jQuery is one of the best scripting languages to create any kind of functionalities with ease but sometimes it doesn’t work as it should due to some compatibility issues. This is where most developers feel confused when they try to use jQuery and $ sign.
For example,
When you use the simple jQuery script in WordPress plugin like this:

$(document).ready(function(){
    // jQuery code is in here
});

But when you check the page in the firebug, it will show the error messages like:
TypeError: $ is not a function
The solution to this error is not everyone’s cup of tea. It requires some in-depth technical knowledge about libraries as well.

Solution:
As WordPress is used for several types of apps, sites, and blogs, there are some issues with the libraries when you use jquery with $ sign.
For that, you can use the below script syntax.

jQuery(document).ready(function($){
 // Use $ as your jQuery object.
 var body = $( 'body' );
});

This way you can use the $ sign in jQuery.
Another solution is quite easier.

(function($){
 // your code
})(jQuery);

Just write your code inside the closure brackets & use $ not jQuery.
This one is easier to use but you need to consider WordPress libraries protocols.
To check the code with no conflict, follow the below script.

var jq=jQuery.noConflict();
jq(document).ready(function(){  
   alert("Hi this will not conflict now");
   jq('selector').show();
});

If it works, you will get the alert “Hi this will not conflict now”.
Try the above codes to use $ in jQuery to make it work as per your requirements.

Need Troubleshooting?
Still, having an issue while using jQuery in WordPress? If yes, we can help you troubleshoot the issue and make your WordPress functionality work accordingly.
Please comment on your issue, we would love to fix it.

Leave a Comment