Juggling With jQuery
December 7, 2011 Paul Tuohy
Note: The code accompanying this article is available for download here. Way back in May 2009, I wrote about some of my experiences with Javascript. Well, time has moved on and I, hopefully, have become a more experienced Javascript programmer. Part of that experience has been in coming to grips with the many Javascript libraries and frameworks that are available for download. When it comes to Javascript, here is what has been happening to me. I came across a requirement for a feature on a Web page (e.g., a calendar to allow the selection of dates), so I did a quick Google search, found a library/framework that did what I wanted, downloaded it, and used it. As time progressed and I included more features, I ended up with a number of Javascript scripts that may or may not need to be included in Web pages, depending on what features I was using on the page. And, if I was lucky, none of them would conflict with each other. The good news is that Javascript libraries/frameworks have also being evolving and there are now a number of these libraries/frameworks that can cover most (if not all) of your Javascript needs. These include slick functions for screen effects (such as fading, pop ups, accordion effects), add-on features (like calendars), handling AJAX, and a host of other items. You can find an excellent comparison of these frameworks and libraries here on Wikipedia. As an aside, when looking at a library, select one that has a mobile equivalent. This step can save you a lot of work when you move from Web to mobile development. But there are two frameworks that have an exceptionally high profile at the moment: ExtJS and jQuery. My personal preference is for jQuery. I find jQuery to be easier to get to grips with. Your mileage may vary and a lot depends on how you are designing and maintaining your Web pages and what sort of features you use most. It is worth having a look at both. In this article I am going to take a quick look at using jQuery. Getting jQuery The core jQuery library can be downloaded here. There are two versions of jQuery available: a production (or minimized) version, where the source code is compressed, spaces and line breaks have been removed and variable names are shortened; and a development version, which is worth having a look at if you want to see how to write some clever Javascript code. Additional plug-ins and features may be customized and downloaded by following the UI link. But, at the moment, we are just interested in the core library. The jQuery Web site includes full documentation, tutorials, and examples, so there is no shortage of information and help available. You can also find an introductory tutorial to jQuery here at the always excellent W3Schools site. Getting Started With jQuery In order to use jQuery, you must ensure that your downloaded jQuery library is included in your HTML document, using a <script> directive in the <head> section, as shown in the first piece of code below. Of course, your directive may be different depending on where you placed the download jQuery library and what you called it. <script type="text/javascript" src="jQuery.min.js"></script> This piece of code demonstrates how to include the jQuery library. All the power of jQuery is accessed through a single function called jQuery or its alias “$”. Or, to be more precise, all of the jQuery functionality is contained within a namespace that may be referenced using the name jQuery or $. Next we will look at some code that shows jQuery commands that set the color of all H2 tags to red. First, we must note that jQuery commands are made up of four parts:
And here are the sample jQuery commands: jQuery('h2').css('color':'red'); // or $('h2').css('color':'red'); We will return to jQuery in a moment. A Reminder Let’s take a look at some Javascript code to show or hide data on a page. This is a variation of a function I showed in the original article. Clicking on an arrow image means that some text becomes visible on the page and the arrow image changes. Clicking on the new arrow image means that the text is hidden again and the arrow image reverts back to its original form. The next code sample shows sample HTML for images that can be clicked and the corresponding text that is displayed/hidden. Before we look at the code, the important points to note are:
This is the HTML required to enable the display and non-display of content: <p>Click here <img src="arrowRight.gif" onclick="showIt(this);" id="toggletest1" /> for text</p> <div id="toggletest1_Content" class="hideContent"> <p>Some hidden text.</p> </div> <p>Click here <img src="arrowRight.gif" onclick="showIt(this);" id="toggletest2" /> for more text</p> <div id="toggletest2_Content" class="hideContent"> <p>Some more hidden text. </p> </div> Next, we’ll see the code in the showit() function. The main points are to note are:
Here is the code for the showIt() function: function showIt(element) { var getDiv=document.getElementById(element.id + '_Content'); element.src = (getDiv.style.display == "block") ? "arrowRight.gif" : "arrowDown.gif" ; getDiv.style.display = (getDiv.style.display == "block") ? "none" : "block"; }; It may be “neat” Javascript ,but let’s be honest, it is not the easiest to read. In case you are not familiar with it, the last line of the showIt() function is a conditional operator that assigns a value of “none” or “block” to the getDiv display style depending on whether or not the current getDiv display style is “block”. The Same With jQuery Now, let’s see what is involved in doing the same with jQuery. We will use the some of the exact same HTML shown above, and we need to ensure that we include our jQuery library. This code shows the jQuery version of the showIt() function: function showIt(obj) { var getDiv= "#" + obj.id + "_Content"; $("#" + obj.id).attr({src : ($(getDiv).is(':hidden') ? "arrowDown.gif" : "arrowRight.gif") }); $(getDiv).toggle(); }; Notice the code consists of two jQuery commands:
Not all that different from the original Javascript function, although that toggle action is a bit easier to use. Now let’s see how jQuery and a naming convention can make our coding even easier. Beefing Up With jQuery This next price of code shows a new version some of the HTML code above. In this version, the onclick attributes have been removed from the two images. We are going to apply a naming rule for the ids used: the image ids must begin with “toggle” and the <div> ID must be the image ID with “_Content” appended. Just as it was in the original, but now it is a rule. <p>Click here <img src="arrowRight.gif" id="toggletest1" /> for text</p> <div id="toggletest1_Content" class="hideContent"> <p>Some hidden text. </p> </div> <p>Click here <img src="arrowRight.gif" id="toggletest2" /> for more text</p> <div id="toggletest2_Content" class="hideContent"> <p>Some more hidden text. </p> </div> This HTML is required to enable the display and non-display of content without onclick. With our rule in place, we can now code the jQuery command: $(document).ready(function(){ $("img[id^=toggle]").click(function() { var getDiv= "#" + this.id + "_Content"; $("#" + this.id).attr({src : ($(getDiv).is(':hidden') ? "arrowDown.gif" : "arrowRight.gif") }); $(getDiv).toggle(); }) }); The jQuery command shown above is used to apply show/hide process for all required images/divisions. The main points to note are:
With this function in place, we can apply the show/hide function, wherever we want, simply by following the naming rules. It Gets Better Well, that was just a quick taste of a simple use of jQuery. It gets even more impressive as the requirements get more complicated (UI functions, AJAX, and so on). As with any programming language, life can be a lot easier if you don’t have to reinvent the wheel, and you can stand on the shoulders of those who have gone before. jQuery provides broad shoulders to stand on. Paul Tuohy is CEO of ComCon, an iSeries consulting company, and is one of the co-founders of System i Developer, which hosts the RPG & DB2 Summit conferences. He is an award-winning speaker who also speaks regularly at COMMON conferences, and is the author of “Re-engineering RPG Legacy Applications,” “The Programmers Guide to iSeries Navigator,” and the self-study course called “iSeries Navigator for Programmers.” Send your questions or comments for Paul to Ted Holt via the IT Jungle Contact page. RELATED STORY
|