TwitterFacebookGoogle

Show/hide various sections of a page using JQuery and CSS

In this post I’ll go over how you can utilize JQuery and CSS classes to show/hide various parts across the different sections of a page without creating a mess!

The Challenge
You’ve got a wizard-like page with multiple steps and you want to be able to show/hide various elements based upon the current step. Below is a dumbed-down example:

The colored boxes represent the parts that are being shared across the various sections of the page. For instance, the green box is being shared by the ‘Image Selection’ and ‘Order Confirmation’ sections. While the red box is being shared by all three sections.

So the challenge is: How do we show/hide these various parts across the sections of the page without making a mess? And by mess, I refer to duplicate code and/or little <% if..then %> snippets scattered throughout the page.

The Solution
By using some CSS/JQuery trickery, of course! What we’ll do is introduce some CSS classes that we will then apply to the various parts for which we need to handle visibility. Here are the classes that we will need:

  • section – Represents a section
  • requestor – Represents the requestor section
  • image-selection – Represents the image selection section
  • confirmation – Represents the order confirmation section

The CSS classes will then be applied to the various parts based upon the section inside which the part is to be shown:

<div>
  <input type='hidden' id='section-to-show' />
  <table>
    <tr>
      <td>Request Type:</td>
      <td class='section requestor'>
        <select>...</select>
      </td>
      <td class='section image-selection confirmation'>
        <%= selectedRequestType %>
      </td>
    </tr>
    ...
    <tr>
      <td>First Name:</td>
      <td><%= firstName %></td>
    </tr> 
    <tr>
      <td>Last Name:</td>
      <td><%= lastName %></td>
    </tr> 
    <tr class='section requestor confirmation'>
      <td>Email</td>
      <td><%= email %></td> 
    </tr>
    ...
    ...
    <tr class='section image-selection confirmation'>
      <td>Image</td>
      <td class='section image-selection'>
        Browse...
      </td>
      <td class='section confirmation'>
        <img src='..' />
      </td>
    </tr>
    ...
  </table>
</div>

A few things to highlight:

– The hidden input field ‘section-to-show’ indicates the section to display. It’s value is set by the server-side code.
– There are two table columns inside the first table row. Only one will be visible based up the section that is being displayed.
– The first name and last name table rows don’t have any classes applied to them. This is because they are always visible.
– The last table row shown above gives an example of how you can make the visibility conditional for both the table row and the table column.
– I skipped various rows in the HTML form above to save some typing and to avoid being repetitive.

And now for the JQuery:

  $(document).ready(function(){
 
    // hide all sections to begin with
    $('.section').hide();
 
    current_section = $('#section-to-show').val();
    $("." + current_section).show();
  });

And there you have it – a cleaner alternative to showing and hiding various parts across the sections of a page!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Dynamically creating input fields on tab via CoffeeScript and JQuery

Below is my very own, very first, super-clean, super-sexy CoffeeScript snippet that dynamically appends input fields as the user tabs through the current input field. The source-code is on the left. On the right you can actually play with it and see it in action!

inputId = 1;
 
jQuery -> 
  $("#fields :input").live 'keydown', (e) ->
    if isModifierKeyPressed e
      return 
 
    if e.keyCode in [9, 13]
      e.preventDefault
 
      if isLastActivity($(this).attr 'id')
	addAnotherTextInput();
 
      $(this).next().focus();
      return false
 
isModifierKeyPressed = (e) ->
  e.ctrlKey or e.altKey or e.shiftKey
 
isLastActivity = (inputFieldId) ->
  inputNumber = 
    (Number) inputFieldId.split('activity')[1]
  inputNumber == inputId
 
addAnotherTextInput = ->
  inputId++
  $("#fields").append getInputField inputId
 
getInputField = (inputId) ->
  return "<input type='text' id='activity#{inputId}' 
                 class='input-super-large' 
                 placeholder='Type something and then press tab' />"
Twitter Email Linkedin Digg Stumbleupon Subscribe

JQuery snippet to detect keystrokes on the numeric key-pad.

The below JQuery snippet returns the character corresponding to the key that was pressed on the QWERTY keyboard or the numeric key-pad. For instance, pressing the '1' key will return the text '1'. Similarly, pressing the '+' key will return back the text '+'.
$(document).keydown(function (event) {
      toCharacter(event.keyCode);
 });
 
function toCharacter(keyCode) {
 
    // delta to convert num-pad key codes to QWERTY codes.
    var numPadToKeyPadDelta = 48;
 
    // if a numeric key on the num pad was pressed.
    if (keyCode >= 96 && keyCode <= 105) {
        keyCode = keyCode - numPadToKeyPadDelta;
        return String.fromCharCode(keyCode);
    }
 
    if (keyCode == 106)
        return "*";
 
    if (keyCode == 107)
        return "+";
 
    if (keyCode == 109)
        return "-";
 
    if (keyCode == 110)
        return ".";
 
    if (keyCode == 111)
        return "/";
 
    // the 'Enter' key was pressed
    if (keyCode == 13)
        return "=";  //TODO: you should change this to interpret the 'Enter' key as needed by your app.
 
    return String.fromCharCode(keyCode);
}

A little explanation is probably in order...


Javascript provides the
String.fromCharCode()
method that converts an ASCII character code into it's equivalent text value. For instance,
String.fromCharCode(65)
returns the character 'A'. The method works great until to try to use it for keys that live on the numeric keypad. The ASCII code for the '1' key on the numeric key pad is 97. If you look this up on the ASCII Table, you will find that the ASCII code 97 corresponds to the character 'a' and not the character '1' denoted on the numeric key pad! The reason for this, as far I can tell, is that the numeric keys simply overload on the existing the ASCII codes. A little calculation will reveal that subtracting 48 from the ASCII code of the numeric keys will give us the "correct" ASCII code. For instance, subtracting 97 (which is the ASCII code for the '1' key on the numeric keypad) from 48 gives us 49. Look up the ASCII code 49 on the ASCII Table and you will find that it maps to the character '1'! For the keys that correspond to the various symbols such as '+', '-', etc., I am simply returning back the corresponding character. No mystery there. Hope this helps!
Twitter Email Linkedin Digg Stumbleupon Subscribe
CyberChimps