[Solved] $(document).ready is not a function

Solve $(document).ready is not a function

If you develop a website using jQuery with other JavaScript libraries (such as mootools, scriptaculous, etc.) on the same page, you may receive this error message while debugging the page (using firebug):

$ is not a function
$(document).ready(function(){ … (line xxx)

or
$().ready is not a function
or
jQuery : Error: $(document).ready is not a function
(document).ready is not a function

Cause

The error occurs because jQuery is conflicting with the other JavaScript libraries on the page. The other library has already overwritten the $() shortcut for jQuery.

Solution

The best workaround is to wrap the function into this anonymous JavaScript function:

( function($) {
	// code goes here 
} ) ( jQuery );

With this function, we are setting $ as a parameter so $ will overwrite any globally defined variables/references of $ in that particular anonymous function. This allows the use of $ within this function without conflicting with other JavaScript libraries. Let’s see an example below:

This is a sample snippet code that will cause the error similar as above.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript"></script>
 
<!-- Assume "$" is a prototype reference. This will cause error. -->
<script type="text/javascript">
	$(document).ready(function() {
		$().UItoTop({ easingType: 'easeOutQuart' });
	});
</script>

To solve the error, wrap the function inside the anonymous JavaScript function:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js" type="text/javascript"></script>
 
<!-- Assume "$" is a prototype reference. -->
<script type="text/javascript">
	( function($) {
		<!-- Here "$" is a jQuery reference -->
		$(document).ready(function() {
			$().UItoTop({ easingType: 'easeOutQuart' });
		});
	} ) ( jQuery );	
</script>

One Response

  1. Lech January 31, 2017

Leave a Reply