Dollar Sign JQuery

In my last post we discussed how to harness the power of JQuery in WordPress. What if you want to use the dollar sign in WordPress instead of jQuery? In this article I would like to show you how to properly mark up your JQuery, when to tell your script to run, and a quick tip on how to make the $() work instead of having to write out jQuery() in complicated functions.

The code example below shows you how to correctly start and end any scripts that you write. You begin with <script> and end with </script> just like a div. Then it is good practice to add any JQuery calls inside of an anonymous function as seen below:

<script>
function(){

	jQuery('.gform_button').addClass("btn btn-gray");
    
};
</script>

It is also good practice to put all of your scripts into the footer of your website. If you write your code in the footer, because your browser reads code from top to bottom, your scripts won’t run until your browser gets down to the footer. Most of the time that is fine but sometimes we want our script to run earlier than that. In this case, we would preface the anonymous function with a document ready function as seen below:

<script>
jQuery(document).ready(function(){

	jQuery('.gform_button').addClass("btn btn-gray");
    
});
</script>

Trick to use the dollar sign in WordPress instead of jQuery

If you happen to be writing a more complicated script, you will want to use the dollar sign in WordPress instead of jQuery. It can be really annoying to have to re-write jQuery over and over again, plus it can cause your code to bloat in size. Good news, there is a solution!

The Solution

var $ = jQuery.noConflict();

$( ".whatever" ).hide();

or you can…

(function($) {
	
	// $ Works! You can test it with next line if you like
	// console.log($);
	
})( jQuery );

Again…you can use a document ready function if you need to with this.

Big thanks to Chris Coyier for sharing his take on how to use the dollar sign in WordPress instead of jQuery on his blog Digging Into WordPress.