Using $ instead of jQuery in WordPress Admin

Well this is not a new issue and neither the solution is but I wanted to repeat it so that newbies don’t waste time hunting for this problem.

jQuery core is added by default in WordPress Admin Pages BUT in noConflict() mode. So if you are writing a plugin and want to use jQuery you will get an error for using because this dollar namespace is not exported in noConflict mode. As a result, your habit of writing

 

will result an error saying $ is undefined. 

To counter this problem, there are a number of ways. First and the most suggested obvious way is to use like

 

BUT, we want to do something more useful. We are going to use a combination of Closure / anonymous function + Global Import.

JavaScript has some very good features. If you have read the design patterns, you will find it very familiar, and if you haven’t it won’t be much difficult. The closures can be self executing functions. Like

 

Now there’s another thing called Global Import using this closure. Let’s have a look at how they look like.

 

Almost all the well written libraries expose a global namespace. For jQuery it’s jQuery, for Yahoo it’s YAHOO and so on. Notice that we have supplied this jQuery nameapce in parameter of closure and using $ in the callback function parameter. Now that $ can be anything. If you write $YO , you will be able to write $YO(document).ready(….) . Why to follow this ? Because you can use any of your legacy script within this anonymous closure without any modification – not even $(document).ready.

So, next time you write some jQuery code in your plugin admin pages for WordPress, consider using the second method mentioned here.

You think you’re good at JavaScript ? Think AGAIN!!

I thought I’m very good at javascript. I had passed my lot of times of programming in early life playing with Javascript. Whatever problems came to me whether mathematical, effects, anything – I used to write JavaScript Codes. And I could debug most of the problems I faced or people faced in different forums. In 2001-2003, I used to give solutions to JS problems asked in experts-exchange.com. And these days, In fact for the last two years, I keep playing with jQuery.

I keep stumbling while I work. It enriches my knowledge on topics i’m interested in. Recently i found a link and it just blew me and my confidence on JavaScript. It’s http://www.dhteumeuleu.com/. I don’t know what these guys are made of. They totally rock. Look at every single script. It won’t be harder to realize that they live javascript and very passionate about doing things. It just told me what’s the possibility. I couldn’t find my favorite from these hundreds of script cause I’m lost. I think all goes to my favorites. Good work guys! Hats off to you!!