• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • 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:

    1. The jQuery function or its $ alias.
    2. Selectors, which can be tags, IDs, names, classes, etc. (H2 tags in this example.)
    3. Actions, of which there are lots (change the CSS value in this example).
    4. Parameters, which vary, depending on the action.

    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:

    • The images have an “onclick” event to call the function showit(). In other words, the function is called when the image is clicked.
    • The showit() function is passed the image object as a parameter.
    • Each image is followed by a <div> containing the text which will be displayed/hidden.
    • The <div> ID is the same as the image ID with the text ‘_Content’ appended.
    • The class “hideContent” is simply a style of {display : none }. So, each <div> is hidden when the page loads.

    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:

    • The function is passed the image object that was clicked.
    • The <div> element is retrieved (variable getDiv). The name of the ID for the <div> is constructed by taking the name of the ID of the image object and appending the text ‘_Content’.
    • The src attribute for the image is changed based on whether or not the <div> is currently displayed: (getDiv.style.display == ‘none’).
    • The display style of the <div> is toggled between “none” and “block” based on whether or not the <div> is currently displayed.

    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:

    • The first command identifies the image object by its ID (a # followed by the ID) and uses the attr action to change the src attribute for the image. The value to be applies to the src attribute (the name of the image) is decided by using the is action to determine whether or not the corresponding <div> is currently hidden. Again, a conditional operator is used to select the required value.
    • The second command identifies the <div> by its ID, and uses the toggle action to toggle between displaying and hiding the <div>.

    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:

    • The $(document).ready action indicates that the enclosed function should run when the page document has loaded.
    • The enclosed command indicates that the hide/show function should be run when a click action occurs for all img elements whose ID start with “toggle”.
    • The only difference in the coding of the show/hide function is that the special value of this is used to identify the object that caused the event to fire, as opposed to passing the object as a parameter.

    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

    Having Fun with Javascript



                         Post this story to del.icio.us
                   Post this story to Digg
        Post this story to Slashdot

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    Midrange Dynamics North America

    Git up to speed with MDChange!

    Git can be lightning-fast when dealing with just a few hundred items in a repository. But when dealing with tens of thousands of items, transaction wait times can take minutes.

    MDChange offers an elegant solution that enables you to work efficiently any size Git repository while making your Git experience seamless and highly responsive.

    Learn more.

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    Micro Focus:  RUMBA for iSeries, the world's most used terminal emulation software
    The 400 School:  Fall Training Sale – Discounts up to 40%! RPG IV COBOL CL Admin Security
    Infor:  Increase performance and profitability with Infor10 Distribution and IBM Power Systems

    IT Jungle Store Top Book Picks

    BACK IN STOCK: Easy Steps to Internet Programming for System i: List Price, $49.95

    The iSeries Express Web Implementer's Guide: List Price, $49.95
    The iSeries Pocket Database Guide: List Price, $59
    The iSeries Pocket SQL Guide: List Price, $59
    The iSeries Pocket WebFacing Primer: List Price, $39
    Migrating to WebSphere Express for iSeries: List Price, $49
    Getting Started with WebSphere Express for iSeries: List Price, $49
    The All-Everything Operating System: List Price, $35
    The Best Joomla! Tutorial Ever!: List Price, $19.95

    Blade Servers Barely Nick IBM i Market Get With The Program

    Leave a Reply Cancel reply

Volume 11, Number 37 -- December 7, 2011
THIS ISSUE SPONSORED BY:

WorksRight Software
SEQUEL Software
Shield Advanced Solutions

Table of Contents

  • Juggling With jQuery
  • SQL Finds a Delta
  • Admin Alert: More Information on Semi-Restricted State, Vendor Profiles, and Storage Pools

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • FAX/400 And CICS For i Are Dead. What Will IBM Kill Next?
  • Fresche Overhauls X-Analysis With Web UI, AI Smarts
  • Is It Time To Add The Rust Programming Language To IBM i?
  • Is IBM Going To Raise Prices On Power10 Expert Care?
  • IBM i PTF Guide, Volume 27, Number 20
  • POWERUp 2025 –Your Source For IBM i 7.6 Information
  • Maxava Consulting Services Does More Than HA/DR Project Management – A Lot More
  • Guru: Creating An SQL Stored Procedure That Returns A Result Set
  • As I See It: At Any Cost
  • IBM i PTF Guide, Volume 27, Number 19

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2025 IT Jungle