Solomon Closson Solomon Closson - 2 months ago 9
Javascript Question

jQuery TypeError: $ is not a function - But how to continue to use $?

Trying to get around this error here, which is problematic for me...

Basically, I am defining a variable as an object from the start. The object has functions that utilize jQuery, but I need to set properties of the object during page load (which seems that I need to set them before the jQuery document is ready perhaps?)

Anyways, here is a .js file that loads in the head of the page using

var MyObject = {

Property1 : null,
Property2 : null,
Property3 : null,
Property4 : 0,

Initialize: function() {
// Do some code in here...
if ($('#some-element').length)
{
MyObject.Property1 = $('#some-element').data('property');
$('#some-element').click(MyObject.On_ClickProperty1);
}


},
On_Click_Property1: function() {
alert('You Clicked ' + MyObject.Property1);

if (MyObject.Property2 !== null)
alert('Property2 = ' + MyObject.Property2);
}
}

jQuery(document).ready(MyObject.Initialize);


This is a very small example here. But now I would like to set MyObject.Property2 on the actual page somewhere (In the Body) and have it update, and that should work fine, since
Initialize
function doesn't actually run until Document.Ready. So I put something like this in the body of the Document...

<script>
MyObject.Property2 = 'This Is Property 2';
</script>


The problem I get now is an on Page Load...
TypeError: $ is not a function


Now, if I wrap the .js file with the following code like so:

(function($){
var MyObject = {

Property1 : null,
Property2 : null,
Property3 : null,
Property4 : 0,

Initialize: function() {
// Do some code in here...
if ($('#some-element').length)
{
MyObject.Property1 = $('#some-element').data('property');
$('#some-element').click(MyObject.On_ClickProperty1);
}


},
On_Click_Property1: function() {
alert('You Clicked ' + MyObject.Property1);

if (MyObject.Property2 !== null)
alert('Property2 = ' + MyObject.Property2);
}
}

jQuery(document).ready(MyObject.Initialize);
})(jQuery);


I no longer see this error, however,
MyObject.Property2
is not being set and the alert for Property2 gives null.

How can I accomplish this properly? So that I don't get
$
typeError, and I can still use
$
(NOT
jQuery
within the Property functions), and I can actually set the value of
Property2
before the alert of MyObject.Property2 shows up??

Answer

Seems like you have jquery loaded in no conflict mode. https://api.jquery.com/jquery.noconflict/ You can assign $ back to jquery if you are not using $ for any other library. Add below on header before var MyObject.

var $ = jQuery.noConflict(true);

Also you can try loading that script file in footer. Here is how I would do it. On header I would initialize empty object globally.

var MyObject = {}; 

Then you could do

(function($){
  MyObject.property1 = null;
  MyObject.Initialize = function () {
    //your codes
  }
  //other lines here
})(jQuery);