1

I have a very strange issue with JQuery, its about a starting of JQuery code when document is ready, as I know there is no difference to use one of methods $(function(){//CODE});, (function($)(){//CODE}(JQuery) or $(document).ready(function(){//CODE});.

Like what said on What is the difference between $(document).ready(function() and $(function() ?

So I like always to use $(function(){//CODE}); method, but when I using this method in some pages working well, but in another I got errors like If I use $.fn.extend or $.browser.msie , I'll get '$.fn is undefined' issue, tried to use (function($)(){//CODE}(JQuery) and that error disappeared, I just want to know why this happening and really if there is and difference between each method !

Community
  • 1
  • 1
Al-Mothafar
  • 7,949
  • 7
  • 68
  • 102

2 Answers2

2

Probably a javascript import in the offending page is redefining the $ variable. This variable doesn't reference jQuery anymore, hence the error. When using the (function($)(){//CODE}(JQuery) construct, you create a closure where the $ variable is once again bound to the jQuery object, and everything goes well inside this closure.

Another way to avoid problems is to always use jQuery instead of $. Example : jQuery(function(){//CODE});

solendil
  • 8,432
  • 4
  • 28
  • 29
  • You know what, It seems like as what you said, I replaced all $ with jQuery and that solved my problem, I just really wonder. Thanks – Al-Mothafar Nov 23 '11 at 10:13
0

It looks like when you're getting the error, you have set jQuery.noConflict (or someone has).

$ is just an alias for jQuery - other frameworks use this too though.

There should be no problem using $(function(){code}) ..or.. jQuery(function(){code})

El Ronnoco
  • 11,753
  • 5
  • 38
  • 65
  • Yes, I know if I have `$.noConflict` I'll get that, but the strange is I don't have it, I tried to search in source code but no result for `$.noConflict` . – Al-Mothafar Nov 23 '11 at 09:39
  • @Al-Mothafar Are you using any other frameworks? And does the script tag referencing jQuery come before your own script tag? – El Ronnoco Nov 23 '11 at 09:42
  • hmm you shouldn't get a conflict with YUI. Can you post your code? – El Ronnoco Nov 23 '11 at 10:07
  • Its like any code with JQuery, its large and hard to put it, working well and this first time getting that issue while I'm testing, nothing special, any way replacing $ with jQuery solve my problem ! – Al-Mothafar Nov 23 '11 at 10:16