Monday, February 27, 2012

How to Create a Simple jQuery Function

     I really feel the title of this should be "How to Turn Any Simple Function into a Reusable jQuery Function", but aside from that title being really long, if you're a bit of a jQuery noob, then you probably typed something similar to the the actual title in Google and thus ended up here.

     If you've used jQuery, or are just starting out, then you should realize jQuery functions as simplified namespace calls of otherwise tedious function calls.  For example, $.ajax() is a jQuery function that provides almost all of the complexities of an ajax call into one name space where parameters are passed through in simple json style such as $.ajax({ url: '' });.  You too can have this power!

     To demonstrate this easy procedure, I'm going to take something simple, used quite frequently ... everywhere and make it into a simple, reusable set of functions. So what is this all powerful command?  Simply tuning your cursor from default to waiting and back again.

     First, I'll look at the most simple approach.  Perhaps you simply want to set your cursor t wait while something is happening and then to default when that event is done.  So at the start of your action you may have something like:
While at the end of your action your change becomes:
     While this is a simple process, when surrounded by jQuery calls, it can look completely out of place and may not fit in the manner you wish.  So we want to change these calls to fit in jQuery style functions we can use again and again.

     A prior warning, this next couple steps negates paying attention to jQuery name-spacing and is not "best practice", however, before I end this article, I will explain a better way to "crop" this down to size and review why name-spacing is important, I promise.  For now, let's stick with the simple process of making those jQuery functions!

     The first thing to know is that this doesn't have to be wrapped in your typical "document.ready" bubble, as jQuery already provides a "plug-in" style way of adding your functions, after you've called for jQuery.  The mark up is simple:
     With that said, you are now ready to make your first custom jQuery function.  Inside your new extension set up, simply start your function with an if statement that determines if the namespace you're using is available in the jQuery library.  This if function is as simple as:
     Keep in mind, this check is no magic.  It is as simple as javascript trying to use the function $.cursorDefault and then getting a kick back tell it that namespace is undefined.  Yay! Then we can use it!  For future reference, get familiar with the console, and if ever question a namespace you are about to use, then simply try to console log it first to see if it exist.  For example, before writing this function we're about to write, if you want to double check if that namespace exist, then do the following:
  1. Use a browser like Google chrome and go to your page or even the jQuery homepage
  2. Open the debugging console (ctrl+shift+j in Chrome)
  3. Click to type in the console
  4. Type $.YourDesiredFunctionName
  5. If it says something like undefined after you press enter, then you are in the clear to use this as a function name, just be careful it doesn't interfer with any other desired
     Finally, we can make our first function.
     Walla! It was just that easy!  And reuse is even easier.  Simply type `$.cursorDefault();` and at that moment it is called, your cursor will magically become normal again.  Now where is that wait function?
     Oh there it is, but there is a problem here.  The namespace issue!  It's never a good idea to make multiple function names where one will do.  This is where you must be work smarter, not harder.  Think about what our two functions are doing and what they are similar too.
     Well, one function sets it to default or 0 as seen in the binary world, whereas the other provides it an action state.  This is very similar to a boolean!
     But how do we simulate this out of two functions?  Parameters!
    So now all we need is a new function name not being used by jQuery and one that probably want be used by other plugins.  In our case we'll use "cursorWait", as we already have it tested and working, but this time we're going to make a parameter change to it.
     So let's see how to rewrite this into one function name:
     Now, you have written your first jQuery function, and it's reuse is simple.
     Before we go,let me point out that our final function solution can actually be written in several ways.  I chose the switch statement simply to drive home the point that this will work weather it has a parameter or not.  However, since the only param we need is `false`, you could just as easily use a full if statement or even a online if statement such as:
     That's all for now!  Keep an eye out for more easy jQuery tips and even other language and library tips in the near future!  Good luck!

An Intro

     In case anyone cares, I'm starting this blog with a little info on me and why I'm making this blog.  First of all, let it be noted that this is the about the 3rd time in 5 years I've wanted to start a blog and never get past my first post.  So, while this time I expect to carry it much further, I can't mislead anyone by promising this to be ongoing thing unless of course I have "encouragement" to do otherwise or simply maintain my self-will to maintain this blog.  That being said, here's to the new and hopefully final attempt!

     Next I should mention a little of my background and experience.  Of course I have had 0 college training in coding.  That's not to say I never went to college.  I did go for four years in pursuit of a business degree.  Then life happened, I never graduated, flip-flopped from one thing to the next till a former employer gave me a chance behind the keyboard.  Suddenly the sun rose and I began to question myself, "You've done this since you were 9 ... Why the hell did you go to school for business!?"

    So here I am, 3-4 years later, coding the complexities of life into a simple software solution.  At my previous employer, I was responsible for simple formats under vb and c# with a large reference to understanding the dreaded "win32 libs" ... all of them.  Our company provided software for law enforcement and thus I became the guy responsible for adding certain "securities" to our programs, such as disabling the keyboard while a vehicle is in motion.  It was fun, and beyond entertaining, however, a slight error in management left to seek other means of income, preferably in the same field I had become acquainted with.

   Today I help develop both a website for the sale of and a web software for the use of a product my company has designed.  At my back is a great structural engineer and between the two of us, we have created a new type of diagnostic tool not yet seen in the medical world using features of web-design not often seen on the internet.  Now, I won't claim to know it all, and my pure javascript writing can sometimes be annoyingly week, but designing and launching the program we have has put me in quite a spot of often times, figuring out how to do things that have yet to be done, or simply, finding easier ways to do things others have made complicated.

    All that said, a large majority of what I do today requires me to stay up to date in several languages and peeks my interest into all languages and libraries.  As time flows on, I find myself moving from one project to another, constantly learning new techniques, new libraries, and sometimes, new languages.  While I've had quite a background in .Net languages and an older background in javascript and perl, most recently I tend to be caught up in PHP through CodeIgniter and javascript via jQuery.  I mention this so as to help future readers understand, that this blog my contain 5 months worth of entries on doing things in jQuery, and then may suddenly flip the script and have 7 months of blogs on how to do things in Ruby.

     I don't intend to ever focus this blog to one type of learning other than coding in general.  So periodically, as my personal habits and/or career shifts and changes, so will my post of blogs.  At present, I'm obsessed with the newest version of jQuery (1.7 at moment) and will probably make my next several post about simple things I've learned to do in jQuery that I feel all beginners should know or at least understand to some extent.