jherax.github.io

This site shows examples for the plugins developed by jherax

Follow me onGitHub

About me

jherax.js + javascript programming + david rivera perez

DAVID RIVERA PEREZ
Bogotá D.C. Colombia
Software Engineer
LinkedIn ProfileProfile
Stack Overflow
Stack Careers

I am software developer from Colombia. I love to create web applications in the front-end, and also build the core of apps with my preferred architectures (N-Tiers and MVC)

Speaking of web development, it is worth mentioning three important architectural patterns, MVC (Model-View-Controller), MVP (Model-View-Presenter) and MVVM (Model-View-viewModel), which can make your life easier. Recently, I began to use MVVM pattern, and I liked the way on how you can keep clean the HTML and JavaScript code.

MVVM is an architectural pattern based on MVC and MVP which attempts to separate the development of user-interfaces (UI) from that of the business logic and behavior in an application. This pattern makes use of declarative "data-Bindings" that allow interaction between "View" and "Model" through a "ViewModel". The viewModel uses an "observable" object which implements the Observer Pattern to notify changes and automatically detect dependencies to update. In JavaScript we can find some MVVM Frameworks like KnockoutJS and Kendo MVVM (demo)

Practice makes perfect: keep reading and trying out by yourself, that way you make the difference between developers who only implement tools, and true developers.

js-utils

This is a suite of utilities for JavaScript and jQuery, which includes tools for validating, text formatting, and other features.

Getting Started

The utility has a dependency on jQuery 1.10+ which must be loaded before js-utils.
It also requires some CSS rules for functions showing tooltips, and other methods.

If jQuery.ui.position is available, all tooltips will be rendered using jQuery.ui, otherwise an internal function for positioning will be used.

fnShowDialog is a facade for ui dialog widget and has a dependency on jQuery.UI 1.9+.
But if you don't want to use jQuery.ui, this method can be overridden by specifying the source property to the function that will replace it.

The library has the following structure:

  • jsu: main namespace
    • author: me :^)
    • version: release number
    • dependencies: array with name of dependencies
    • createNS: utility to create safe namespaces
    • wrapper: selector where dynamic HTML is placed
    • regional: namespace to set the language setting
    • settings: namespace to set global settings
  (function() {
    // None of below settings are mandatory.

    // We set the container of the views
    jsu.wrapper = "#main-section";

    // We set the language setting
    jsu.regional.set(jsu.regional.english);

    // Sets the default setting for tooltips
    jsu.settings.position = {
      at: "left bottom",
      my: "left+2 top+5"
    };

    // Add your code for plugins init, event handlers, etc...
  })();

In many programming languages, namespacing is a technique employed to avoid collisions with other objects or variables in the global context. They're also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified.

Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions. In practice this means you should avoid creating global objects unless they are absolutely necessary.

Is critical as it's important to safeguard your code from breaking in the event of another script on the page using the same variable or method names as you are. To overcome some of these issues, we take advantage of the Module Pattern through namespace injection. The logic is shielded from the global scope by a function wrapper (usually self-invoking) which exposes an object representing the module’s public interface.

I recommend this excellent book: Learning JavaScript Design Patterns.
Also worth reading these articles:

This utility makes life easier when you require create nested namespaces.
For example, you need to create the following object structure:

  • animation
    • g2D
      • slide
    • g3D
      • cubic
    • tools
  // using closures, modules, IIFE, are good practices
  (function() {
    jsu.createNS("animation.g2D.slide");
    jsu.createNS("animation.g3D.cubic");
    // you can get the reference of created namespace
    var tools = jsu.createNS("animation.tools");
    // If you use local/cached references is recommended declare them
    // within a function or module at the top of your function scope
    // (this is a dependancy declaration pattern)
  })();

This namespace exposes objects and methods to setup your language preferences.
If we are using jQuery.UI, we can provide a language to configure the datepicker widget.
Available predefined languages are jsu.regional.english and jsu.regional.spanish
By default spanish language is set, although you can specify language using method set()
e.g. jsu.regional.set(jsu.regional.english);
You can define your own language settings:

(function() {
  // Create the locale language object
  // (the text should be in Italian)
  jsu.regional.italian = {
    culture: "it", //locale codes: http://www.science.co.il/Language/Locale-codes.asp
    wordPattern: null, //regular expression pattern for text capitalization in fnCapitalize
    timeFormat: "HH:mm", //pattern for time. HH: 0-23 hour, hh: 1-12 hour, mm: minutes, ss: seconds
    dateFormat: "MM/dd/yyyy", //pattern for date. dd: 2-digit day, MM: 2-digit month, yyyy: 4-digit year
    dateFormatError: "The date format is incorrect", //text for fnIsValidDate when date format is wrong
    dateIsGreater: "The date can't be greater than today", //text of date validation in fnIsValidDate
    dateIsLesser: "The date can't be lesser than today", //text of date validation in fnIsValidDate
    validateRequired: "This field is required", //text for $.fnEasyValidate required fields
    validateFormat: "The format is incorrect", //text for $.fnEasyValidate wrong format
    dialogTitle: "Information", //default jQuery.ui.dialog title
    dialogCancel: "Cancel", //default $.fnConfirm cancel text
    dialogOK: "Agree" //default $.fnConfirm approve text
  };
  // We set the created language setting
  jsu.regional.set(jsu.regional.italian);
})();

If you want to provide additional languages to other plugins, you can pass a function as second parameter in method set(); Keep in mind that some plugins can be configured only previous to its initialization.

(function() {
  // We will create italian language for datepicker plugin
  // Additional languages for datepicker can be found at:
  // github.com/jquery/jquery-ui/tree/master/ui/i18n
  $.datepicker.regional['it'] = {
    closeText: 'Chiudi',
    prevText: '<Prec',
    nextText: 'Succ>',
    currentText: 'Oggi',
    monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
          'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
    monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
          'Lug','Ago','Set','Ott','Nov','Dic'],
    dayNames: ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'],
    dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
    dayNamesMin: ['Do','Lu','Ma','Me','Gi','Ve','Sa'],
    weekHeader: 'Sm',
    dateFormat: 'dd/mm/yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''
  };
  // We set the created language setting
  jsu.regional.set(jsu.regional.italian, function() {
    $.datepicker.setDefaults($.datepicker.regional['it']);
  });
})();

This namespace is used to define a default behaviour for some functions.

  • position: This object sets the default setting for all functions that use $.position to display a tooltip (fnIsValidDate, fnShowTooltip, $.fnMaxLength, $.fnEasyValidate). The object consist of three properties:
    • at: String. Defines which position on the target element to align the positioned element against: "horizontal vertical" alignment. Acceptable horizontal values: "left", "center", "right" Acceptable vertical values: "top", "center", "bottom"
      Each dimension can also contain offsets, in pixels e.g., "right+10 top-25"
    • my: String. Defines which position on the element being positioned to align with the target element: "horizontal vertical" alignment. (See the at option for full details on possible values)
    • collision: String. When the positioned element overflows the window in some direction, move it to an alternative position. (Only if jQuery.ui.position is available)
  (function() {
    // Sets default setting for tooltips
    jsu.settings.position = {
      at: "left bottom",
      my: "left+2 top+5",
      collision: "none"
    };
  }());

jQuery extensions


Usage

Adds support for browser detect, because jquery 1.9+ deprecates the browser property.
For detecting capabilities, is better to use Modernizr.
Returns Object

  // see browser and version
  console.log(jsu.browser);
  // check for a specific browser
  if (jsu.browser.msie) { ... }
  if (jsu.browser.chrome) { ... }
  if (jsu.browser.mozilla) { ... }
  if (jsu.browser.opera) { ... }

This object has two methods to determine the type of the <input> element.

  • isText (dom): This function returns true when the dom parameter is a writable <input>
    Elements classified in this category are: Category:text
  • isCheck (dom): This function returns true when the dom parameter is a checkable <input>
    Elements classified in this category are: input type checkbox and radio.
  <input type="radio" id="radio" />
  <input type="date" id="date" />
  <textarea id="area"></textarea>
  (function() {
    //use $.get() to get DOM element
    var area = $("#area").get(0);
    var date = $("#date").get(0);
    var radio = $("#radio").get(0);
    if (jsu.inputType.isText(area)) area.value = "I am category:text";
    if (jsu.inputType.isText(date)) date.value = new Date().toISOString().substring(0, 10);
    if (jsu.inputType.isCheck(radio)) radio.checked = true;
  })();

This utility allow us to determine if an event handler was created previously by specifying a namespace.
Note: Namespacing events is a technique to handle tasks differently depending on the event namespace used, and it is very useful when you've attached several listeners to the same event, and need to do something with just one of them. Check this article: Namespaced Events in jQuery
Returns Boolean

  • dom: DOM element
  • eventname: String event type
  • namespace: String event namespace
  var txb = $("#txtName").get(0);
  // Checks if the event handler was defined previously
  var defined = jsu.handlerExist(txb, "focus", "fnHighlight");
  // Creates the event handler by namespacing the event
  !defined && $(txb).on("focus.fnHighlight", function(e) {
    console.log("Event type:", e.type);
    console.log("Namespace:", e.namespace || e.handleObj.namespace);
    // Add your code here...
  });

Determines if the entry parameter is a DOM Element.
Returns Boolean

  • object: Object to validate
  var obj = { name: "Mordecai" };
  if (jsu.isDOM(obj)) { ... } //false
  obj = document.getElementById("txtName");
  if (jsu.isDOM(obj)) { ... } //true
  obj = $(":button");
  if (jsu.isDOM(obj)) { ... } //false
  obj = $(":button").get(0);
  if (jsu.isDOM(obj)) { ... } //true

Determines if the entry parameter is a function.
Returns Boolean

  • object: Object to validate
  var fn = {};
  if (jsu.isFunction(fn)) { fn(); } //false
  fn = null;
  if (jsu.isFunction(fn)) { fn(); } //false
  fn = "function";
  if (jsu.isFunction(fn)) { fn(); } //false
  fn = function() { alert("is function"); };
  if (jsu.isFunction(fn)) { fn(); } //true

This is a reference to JSON.stringify and provides a polyfill for old browsers.
fnStringify serialize an object, array or primitive value and returns it as a JSON string.
Returns String

  • json: Object to be serialized
  var jsonPerson = {
      name: "David",
      sex: "male",
      age: 30
  };
  console.log(jsu.fnStringify(jsonPerson));

  // We use jQuery.extend to merge the contents of
  // two or more objects together into the first object.
  var jsonNew = $.extend({ alias: 'jherax' }, jsonPerson);
  console.log(jsu.fnStringify(jsonNew));

Dynamically add an external script. This method is useful to inject dependencies from an external file, in case your code might fail if it depends on a specific component. Thus for example, if you have a function that uses the kendo.ui.window component to build a window, you can check for dependencies before trying to access that component.
Returns undefined this method returns nothing.

  • path: String source of the script to be added. It can also be a JSON object with a set of attributes for script tag: { src: String, async: Boolean, defer: Boolean, charset: String }
    We can also specify other properties like { execute: Bolean, before: String } which dictate whether to run the script once loaded, or indicate where to insert it (see the before parameter).
  • before: String part of src attribute of the element that identifies where the script will be added. This parameter is optional and if it is not specified, the new script will be inserted before "jherax.js"
  function fnShowWindow(o) {
    var d = $.extend({
      content: null,
      title: "Information",
      appendTo: "body",
      width: "360px"
    }, o);
    if(!window.kendo)
      jsu.fnAddScript({ src: '/scripts/kendo/kendo.core.js', execute: true });
    //After the kendo core is loaded
    if (!kendo.ui.Window)
      jsu.fnAddScript({ src: '/scripts/kendo/kendo.window.js', execute: true });
    //Adds another script asynchronously
    jsu.fnAddScript({ src: '/scripts/fullscreen.js', before: 'kendo.core.js', async: true });
    //Implementation...
  }

Dynamically add an external stylesheet. This method is useful to inject a cascading style sheet resource from an external file, in case that you use some plugins requiring specific css and you don't want to include them inside your main stylesheet.
Returns undefined this method returns nothing.

  • path: String source of the stylesheet to be added.
  • before: String part of href attribute of the element that identifies where the resource will be added. This parameter is optional and if it is not specified, the new stylesheet will be appended to <head>
  (function(){
    //Adds the stylesheet just before main.css link
    jsu.fnAddCSS("/content/css/jquery.dataTables.css", "main.css");
    //or appends the stylesheet to <head> element
    //jsu.fnAddCSS("/content/css/jquery.dataTables.css");
    $('.dataTable').wrap('<div class="tt-wrapper">').dataTable();
  }());

Escapes user input to be treated as a literal string in a regular expression.
This mean that special characters will be treated as literals.
e.g. The expression "(\\w+)" will turn into "\(\\w\+\)"
Returns String, or null if text parameter is not a string

  • text: String to literalize
  var re1 = new RegExp("[abc]+\\d"); //string as regular expression pattern
  var re2 = new RegExp(jsu.fnEscapeRegExp("[abc]+\\d")); //literal string
  console.log("re1: " + re1.test("ac1") + ", regexp: " + re1.source);
  console.log("re2: " + re2.test("ac1") + ", regexp: " + re2.source);

Gets the value of a specific parameter in the querystring (search in the address bar).
Returns String. If the parameter is not found, an empty string is returned.

  • query: String with name of the parameter to search for.
  //assuming you have the following url
  //http://www.google.com.co/search?q=300+rise+of+an+empire&oq=300

  //we want to retrieve the value of [q] parameter
  var q = jsu.fnGetQueryToString("q");
  //prints: "300+rise+of+an+empire"
  console.log(q);

Gets the querystring from address bar and is returned as a JSON object.
Note: The entry parameter is not mandatory, and if not specified, all variables found in the querystring will be retrieved in a JSON object.
Returns Object in JSON notation.

  • query: String with name of the parameter to search for.
  //assuming you have the following url
  //http://www.youtube.com/watch?v=hrZl_EQUbRQ&hd=1

  //we want to retrieve all values from querystring
  var q = jsu.fnGetQueryToJSON();
  console.log(q); //prints: {v: "hrZl_EQUbRQ", hd: "1"}

  //we want to retrieve the variable [v] and its value
  var v = jsu.fnGetQueryToJSON("v");
  console.log(v); //prints: {v: "hrZl_EQUbRQ"}

Clones an object and set all its properties to read-only.
In some cases, you may need to lock an object to prevent being modified.
This could be useful, for example, if you need preserve a model object.
Returns Object

  • object: Object to be cloned
  var ajaxResponse = {
    serie: "Lenovo IdeaPad Z710",
    features: {
      processor: "Intel Core i7-4700MQ",
      graphics: "NVIDIA GeForce GT 745M",
      memory: "PC3-12800 DDR3L",
      ram: 8
    }
  };
  // Clone the original object
  var readOnly = jsu.fnCloneObject(ajaxResponse);
  console.log("READ-ONLY OBJECT:", readOnly);
  readOnly.serie = "ThinkPad W540";
  readOnly.features.ram = 16;
  console.log("READ-ONLY OBJECT:", readOnly);

Gets the string representation of the specified date according to regional setting dateFormat timeFormat
Note: This function has support for ISO 8601 format which allow to set the value on input of type date, datetime, datetime-local. According to w3.org the value attribute must be a valid date-time as defined in RFC 3339.
Returns Object

  • options: Object Optional. If not provided, the current date and time is returned. If you pass an argument, you can specify some of the following options:
{
  date: Date|String|Number //date to parse according to regional setting (Default: new Date)
  ISO8601: Boolean //the date will be formatted according to ISO 8601 (Default: false)
}

Note: The object returned has the following properties:

{
  date: String //gets the date according to [dateFormat]
  time: String //gets the time according to [timeFormat]
  dateTime: String //gets the date with [dateFormat] + [timeFormat]
}
  (function() {
    // We set the language setting
    jsu.regional.set(jsu.regional.english);

    // No arguments, gets the current date
    var d = jsu.fnGetDate();
    $("#date").html(d.date +" <b>"+ d.time +"</b>");

    // We provide a specific date and format (output ISO-8601)
    var dt = "12/24/2013 23:59:13";
    var iso = jsu.fnGetDate({ date: dt, ISO8601: true });
    console.log("ISO 8601:", iso.dateTime);

    // We provide a date in ISO 8601 (output regional)
    dt = "1995-12-17T03:24:59Z"; //Z UTC
    iso = jsu.fnGetDate({ date: dt });
    console.log("UTC:", iso.dateTime);

    // We provide a date in ISO 8601 (output regional)
    dt = "1995-12-17T03:24:59-05:00"; //-05:00 offset
    iso = jsu.fnGetDate({ date: dt });
    console.log("Time offset:", iso.dateTime);

    // We provide a specific date
    dt = new Date(1395971368528);
    d = jsu.fnGetDate({ date: dt });
    console.log("Regional:", d.dateTime);
  })();

Gets the date object from a string in ISO 8601 format.
It is mandatory that input parameter be a string in ISO 8601, otherwise null is returned.
Note: Time offset and UTC are omitted for the entry parameter.
Returns Date or Null

  • date: String date as string in ISO 8601 format
  jsu.fnDateFromISO8601(0);
  jsu.fnDateFromISO8601(null);
  jsu.fnDateFromISO8601("12/17/1995");
  var date = jsu.fnDateFromISO8601("1995-12-17T03:24:59Z");
  console.log("Date:", date);

Converts a pure HTML string to encoded html, so if you have the string <p>hello</p>,
this function will encode the hmtl text to &lt;p&gt;hello&lt;/p&gt;
This method can be used just as a function: fnGetHtmlText (value)
or as delegate for jQuery .val() or .text() fnGetHtmlText (index, value)
Returns String with encoded html

  • value: String html to be encoded
  <textarea rows="4"></textarea>
  <textarea rows="6" id="target-v"></textarea>
  <div id="demo-wrapper">
    <h3>fnGetHtmlText</h3>
    <p><u>Delegated function</u></p>
  </div>
  setTimeout(function() {
    var html = $("#demo-wrapper").html();
    $("textarea").val($.trim(html));
    // you can run it just as a function
    var htmlEncoded = jsu.fnGetHtmlText(html);
    console.log("Encoded:", htmlEncoded);
    $("#target-v").fnShowTooltip("This html will be encoded ...3");
  }, 1);

  setTimeout(function() {
    $(".vld-tooltip").remove();
    $("#target-v").fnShowTooltip("This html will be encoded ...2");
  }, 1000);

  setTimeout(function() {
    $(".vld-tooltip").remove();
    // you can also run it as a delegate for .val() or .text()
    // note that we just pass the reference to the function
    $("#target-v").val(jsu.fnGetHtmlText).fnShowTooltip("Encoded");
  }, 2000);

Gets the selected text in the document.
Note: There are some <input> elements that not support text selection.
Returns Object with the following properties:

  { text: String, slice: String, start: Number, end: Number }
  var sel = jsu.fnGetSelectedText();
  if (sel.text !== "") alert(sel.text);
  console.log(sel);

Gets the cursor position of dom element.
Note: There are some <input> elements that not support text selection.
Returns Number

  var text = $("#txtName").val("Hello!").get(0);
  var pos = jsu.fnGetCaretPosition(text);
  console.log(pos);

Sets the cursor position in the dom element.
Note: There are some <input> elements that not support text selection.

  • dom: DOM element category:text
  • position: Number that indicates where the cursor is set
  var text = $("#txtName").get(0);
  text.value = "Hello World!";
  text.focus();
  jsu.fnSetCaretPosition(text, 5);
  //cursor is positioned after "Hello"

Applies a transformation to the text, removing all line-breaks, spaces, and tabs from the beginning and end of the supplied string. If the whitespace characters occur in middle of the string, also they are removed.
Note: When object parameter is a DOM element, the value property is used as the string to transform.
Note: The object defined in jsu.regional.<language>.wordPattern is a regular expression used to lowercasing some words after text capitalization. Only works when type parameter is "word"
Note: You can use this function as a jQuery extension, see jQuery.fnCapitalize.
Returns String

  • object: String or DOM element category:text
  • type: String specifying the text transformation. Can be one of the following values:
    • "word" transform to lowercase and then turns the first letter of each word into uppercase
    • "title" turns the first letter of each word into uppercase
    • "first" turns only the first letter to uppercase
    • "upper" transform to uppercase
    • "lower" transform to lowercase
  var text = "\n  make  your\t  code DRY  \n ";
  console.log('original text: "' + text + '"');
  console.log('word : "' + jsu.fnCapitalize(text, "word" ) + '"');
  console.log('title: "' + jsu.fnCapitalize(text, "title") + '"');
  console.log('first: "' + jsu.fnCapitalize(text, "first") + '"');
  console.log('upper: "' + jsu.fnCapitalize(text, "upper") + '"');
  console.log('lower: "' + jsu.fnCapitalize(text, "lower") + '"');

If you want to lowercase specific words, you can do it this way:

  (function() {
    // We configure the global language setting
    // The following words will always be lowercase
    jsu.regional.english.wordPattern = /\s(?:And|Are|At|A|O[nrf]|By|In|The)\b/g;
    jsu.regional.set(jsu.regional.english);
    var text = " pc AND KEYBOARD\t ArE oN tHe table ";
    console.log("Before: ", '"' + text + '"');
    // Transforms the text after 2 seconds
    setTimeout(function() {
      text = jsu.fnCapitalize(text, "word");
      console.log("After: ", '"' + text + '"');
    }, 2000);
  })();

Sets numeric format according to es-CO culture by placing the decimal . and thousands , separator.
Note: When object parameter is a DOM element, the value property is used as the string to format.
Note: You can use this function as a jQuery extension, see jQuery.fnNumericFormat.
Returns String with the formatted number

  var num = "123456789,47.15";
  console.log(jsu.fnNumericFormat(num)); //sends string
  var dom = $("#txtName").val(num).get(0);
  jsu.fnNumericFormat(dom) //sends DOM
  console.log(dom.value);

Validates the format, depending on type supplied. Date validations are run according to regional setting.
Note: When object parameter is a DOM element, the value property is used as the string to validate.
Note: You can use this function as a jQuery extension, see jQuery.fnIsValidFormat.
Returns Boolean

  • object: String or DOM element category:text
  • type: String specifying the type of validation:
    • "t" validates the time format [timeFormat]
    • "d" validates the date format [dateFormat]
    • "dt" validates full date format [dateFormat + timeFormat]
    • "pass" validates the password strength (must have 8-20 characters, 1+ uppercase, 1+ number)
    • "email" validates the email address
    • "lat" validates the latitude
    • "lon" validates the longitude
  (function() {
    //We configure the global language setting
    jsu.regional.set(jsu.regional.english);
    var _dateTime = "10/31/2013 16:10";
    var _email = "some-mail.gmail.com";
    var _pass = "insufficient";
    console.log(jsu.fnIsValidFormat(_dateTime, "dt"));
    console.log(jsu.fnIsValidFormat(_email, "email"));
    console.log(jsu.fnIsValidFormat(_pass, "pass"));
  })();

Evaluates whether the entry DOM element has the date format for the value property.
Date validations are performed according to regional setting dateFormat timeFormat
The validation message is displayed with a tooltip. If jQuery.ui.position is available, the tooltip will be rendered using jQuery.ui, otherwise an extended method for jQuery.position is used.
Note: You can use this function as a jQuery extension, see jQuery.fnIsValidDate.
Important: You can customize the messages defined in jsu.regional namespace:
dateIsGreater dateIsLesser dateFormatError
Returns Boolean

  { compareTo: Date|String, isFuture: Boolean, warning: String, position: Object }
  (function() {
    //Configure the global language setting
    jsu.regional.set(jsu.regional.english);
    var d = new Date();
    $("#txtLicence").val(
      jsu.fnGetDate({ date: d.setHours(24) }).date);
    $("#txtBirthday").val(
      jsu.fnGetDate({ date: d.setHours(24) }).date);
  }());

  //Validates elements in the form
  $("#btnSend").on("click", function() {
    var dBirthday = $("#txtBirthday").get(0);
    var dDriverLic = $("#txtLicence").get(0);

    if (!jsu.fnIsValidDate(dDriverLic)) return false;
    if (!jsu.fnIsValidDate(dBirthday, {
        compareTo: dDriverLic.value,
        warning: "Your birthday can't be greater than driver's license expedition"
    })) return false;

    alert("Submit form");
  });

This function is very useful when you need display a validation message.
It shows the message in a tooltip at the right side of dom and focuses that element.
The tooltip element is painted according to the rules defined by .vld-tooltip class.
It has the following DOM structure: <span class="vld-tooltip"> your message </span>
Important: If jQuery.ui.position is available, the tooltip is rendered by jQuery.ui.position, otherwise an extended method for built-in jQuery.position is used.
Note: By specifying jsu.settings.position you can override the position for all tooltips.
Note: You can use this function as a jQuery extension, see jQuery.fnShowTooltip.
Returns Boolean, always returns false

  • dom: DOM element to where the tooltip is positioned
  • message: String with the message to display
  • position: Object This parameter is not mandatory. It defines the position where the tooltip is displayed and have the following properties:
{
  at: String. Default "right center". //Defines which position on the target element to align the positioned element against: "horizontal vertical" alignment.
  my: String. Default "left+6 center". //Defines which position on the element being positioned to align with the target element: "horizontal vertical" alignment.
  collision: String. Default "flipfit". //Only works when jQuery.ui.position is available.
}
  $(function() {
    // Configure the global language setting
    jsu.regional.set(jsu.regional.english);

    var email = $("#txtEmail").get(0);
    var admission = $("#txtDate").get(0);

    if (!jsu.fnIsValidFormat(email, "email")) {
      // Displays the tooltip at the default position
      return jsu.fnShowTooltip(email, "The email address is not valid");
    }
    if (!jsu.fnIsValidFormat(admission, "d")) {
      // Displays the tooltip at the specified position
      return jsu.fnShowTooltip(
        admission,
        "The admission date is not valid", {
            at: "left bottom",
            my: "left+2 top+5"
        });
    }
  });

Sets the default setting for all functions showing tooltips

  (function() {
    // Sets default setting for tooltips
    jsu.settings.position = {
      at: "left bottom",
      my: "left+2 top+5"
    };
  }());

  $(function() {
    // Validates some fields
    if (!$("#txtBirthday").fnIsValidDate({
        warning: "Your next birthday can't be lesser than today",
        isFuture: true
    })) return false;

    var pass = $("#txtPassword");
    if (!pass.fnIsValidFormat("pass")) {
      return !pass.fnShowTooltip("The password did not meet the requirements");
    }
  });

This is a facade for jQuery.ui.dialog which is a modal window useful for displaying text, DOM or jQuery elements. You can display text as html by passing the string to content property.
Generated HTML is appended by default to where jsu.wrapper selector indicate, but if you want to place it into a specific element, then you can provide the wrapper selector to appendTo property.
There are some images used to display an icon to the left of text, only if content parameter is a string.
Also you can display existing HTML elements by passing the DOM or jQuery object to content property.
The closeOnPageUnload option determines whether dialog should be closed on window.beforeunload event.
Note: It has a dependency on jQuery.UI and also has some css rules.
Returns jQuery dialog element

Sets the focus on all input:text and textarea elements, except those that have .no-auto-focus
This function is useful when you need validate form fields using any of the below jQuery plugins.

  $(document).on("ready", function() {
    $("#txtDate").datepicker().addClass("no-auto-focus");
    $("#txtName").fnCapitalize("word");
    $("#txtID").fnNumericInput();
  });
  $("#btnSendForm").on("click", function() {
    jsu.fnSetFocus();
  });

Shows a overlay screen with the "loading" indicator at the center.
The progress animation is done via CSS3, so you must add the following css:
#floatingBarsG .blockG @keyframes fadeG .bg-fixed .bg-opacity
Returns Boolean, always returns true

  • options: Object that provides the following properties:
  { show: Boolean, hide: Boolean, delay: Number }
  $("#btnTest").on("click", function() {
    jsu.fnLoading();
    setTimeout(function() {
      jsu.fnLoading({ hide:true });
    }, 8000);
  });

jQuery plugins

This is a set of utilities for jQuery.
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy API that works cross-browser. If you want to learn more about jQuery, here is a full guide: How jQuery Works.

Sets the collection of jquery objects in the center of screen.
Elements are centered using fixed position.
Returns jQuery

  // with existing element
  $(".warning").fnCenter();
  // or create a new one
  var div = $('<div id="divHello" />').css({
    'padding': '20px',
    'background': '#ccc',
    'borderRadius': '5px'
  }).appendTo("body").html("<h4>Hello jQuery</h4>");
  div.fnCenter();

Limits the maximum length of characters allowed in the elements category:text
A tooltip will be placed on the right side of input element showing the characters remaining.
It has a dependency on jQuery.UI for positioning, and also has a css class .vld-tooltip
Returns jQuery

  • length: Number specifying the max length of characters
  $("#txtName").fnMaxLength(20);
  $(".numbers").fnMaxLength(10);

This is the jQuery extension for fnCapitalize function.
Applies a transformation to the text, removing all line-breaks, spaces, and tabs from the beginning and end of the supplied string. If the whitespace characters occur in middle of the string, also they are removed.
Note: The object defined in jsu.regional.<language>.wordPattern is a regular expression used to lowercasing some words after text capitalization. Only works when type parameter is "word"
Note: The text is transformed when the blur event occurs.
Returns jQuery

  • type: String specifying the text transformation. Can be one of the following values:
    • "word" transform to lowercase and then turns the first letter of each word into uppercase
    • "title" turns the first letter of each word into uppercase
    • "first" turns only the first letter to uppercase
    • "upper" transform to uppercase
    • "lower" transform to lowercase
  setTimeout(function() {
    var text = "\n do\t it  with\t  jQuery\t\n ";
    var $input = $("#txtName").val(text).width(180);
    $input.fnShowTooltip("This text will be transformed");
    $input.fnCapitalize("title").focus();
  }, 1);

  //raise blur event to transform text
  setTimeout(function() {
    alert("click to transform");
    $("#txtName").blur();
  }, 2000);

If you want to lowercase specific words, you can do it this way:

  (function() {
    // We configure the global language setting
    // The following words will always be lowercase
    jsu.regional.english.wordPattern = /\s(?:And|Are|At|A|O[nrf]|By|In|The)\b/g;
    jsu.regional.set(jsu.regional.english);
    // You can bind the event handler at beginning
    var $input = $("#txtName").fnCapitalize("word");
    var text = " pc AND KEYBOARD\t ArE oN tHe table ";
    // Raise blur event to transform text
    $input.val(text).focus();
    setTimeout(function() {
      alert("transform");
      $input.blur();
    }, 2000);
  })();

This is the jQuery extension for fnNumericFormat.
Sets numeric format according to es-CO culture.
Places the decimal . and thousands , separator.
Note: Text is formatted when keyup, blur events occurs.
Returns jQuery

  var num = "123456789,47.15";
  console.log(num); //number to be formatted
  $("#txtName").val(num).fnNumericFormat().focus();

This function allows that only numeric keys can be pressed at the input.
Returns jQuery

  $(".vld-numeric").fnNumericInput();

This function applies a mask for the allowed characters.
Returns jQuery

  • mask: It can be one of these types:
    • String: a literal with the allowed characters.
    • RegExp: a regular expression for the allowed characters.
  $("#txtGrade").fnCustomInput("abc1-6");
  $("#txtEmail").fnCustomInput(/[@ñ;.\-\w]/);

Disables the specified keyboard keys.
To allow a set of characters, better use $.fnCustomInput
Returns jQuery

  • keys: String with character(s) that will be blocked
  // prevents the spacebar be pressed in the document
  $(document).fnDisableKey(" ");
  // avoids pressing the keys q,w,e,r,t on the input
  $("#txtName").fnDisableKey("qwert");

This is the jQuery extension for fnIsValidFormat function.
Validates the format of value, depending on type supplied.
Date validations are performed according to regional setting.
Returns Boolean

  • type: String specifying the type of validation:
    • "t" validates the time format [timeFormat]
    • "d" validates the date format [dateFormat]
    • "dt" validates full date format [dateFormat + timeFormat]
    • "pass" validates the password strength (must have 8-20 characters, 1+ uppercase, 1+ number)
    • "email" validates the email address
    • "lat" validates the latitude
    • "lon" validates the longitude
  (function() {
    //We configure the global language setting
    jsu.regional.set(jsu.regional.english);
    var dt = $("#date").val("12/31/2013 23:10");
    var isValid = dt.fnIsValidFormat("dt");
    console.log("Is dateTime: ", isValid);
  })();

This is the jQuery extension for fnIsValidDate function.
Evaluates whether the first element in the collection has the value with date format.
Date validations are performed according to regional setting dateFormat timeFormat
The validation message is displayed with a tooltip. If jQuery.ui.position is available, the tooltip will be rendered using jQuery.ui, otherwise an overloaded function for jQuery.position is used.
Important: You can customize the messages defined in jsu.regional namespace:
dateIsGreater dateIsLesser dateFormatError
Returns Boolean

  • options: Object that provides the following settings:
  { compareTo: Date|String, isFuture: Boolean, warning: String }
  (function() {
    //We configure the global language setting
    jsu.regional.set(jsu.regional.english);
    var d = new Date();
    $("#txtLicence").val(
      jsu.fnGetDate({ date: d.setHours(24) }).date);
    $("#txtBirthday").val(
      jsu.fnGetDate({ date: d.setHours(24) }).date);
  }());

  //Validates elements in the form
  $("#btnSend").on("click", function() {
    if (!$("#txtLicence").fnIsValidDate()) return false;
    if (!$("#txtBirthday").fnIsValidDate({
        compareTo: $("#txtLicence").val(),
        warning: "Your birthday can't be greater than driver's license expedition"
    })) return false;

    alert("Submit form");
  });

Validates the form fields with css class .vld-required through a submit button.
It has a dependency on jQuery.UI for the validation notification.
If you wish to validate only a set of elements in the form, you can specify a validation group by adding data-validation attribute to the elements to validate and also to the submit button.
Returns jQuery

  • options: Object that provides the following properties:
  { fnvalidator: Function, firstItemInvalid: Boolean }
<select id="ddlType" class="vld-required" data-validation="group.a">
  <option value="0">Select...</option>
  <option value="1">Magnetic</option>
  <option value="2">Electric</option>
</select>
<input type="number" id="txtValue" class="vld-numeric vld-required" data-validation="group.a"/>
<input type="date" id="txtDate" class="vld-required"/><!--This one isn't in validation group-->
<button type="submit" id="btnAdd" data-validation="group.a">Add new item</button>
$(document).on("ready", function () {
  $(".vld-numeric").fnNumericInput();
  $("#txtDate").datepicker().addClass("no-auto-focus");
  //$("#btnAdd").fnEasyValidate(); //only validates required fields
  $("#btnAdd").fnEasyValidate({
    firstItemInvalid: true,
    fnValidator: function (btn) {
      var num = $('#txtValue').get(0);
      if (parseFloat(num.value) < 1000) {
        return jsu.fnShowTooltip(num, "Price must be greater than $999"); //cancel submit
      }
      return true; //submit the form
    }
  });
});

This is the jQuery extension for fnShowTooltip function.
This function is very useful when you need display a validation message.
A tooltip is shown at the right side of current element, and set focus on that element.
The tooltip element is painted according to the rules defined by .vld-tooltip class.
It has the following DOM structure: <span class="vld-tooltip"> your message </span>
Important: If jQuery.ui.position is available, the tooltip is rendered by jQuery.ui.position, otherwise an extended method for built-in jQuery.position is used.
Note: By specifying jsu.settings.position you can override the position for all tooltips.
Returns jQuery

  • message: String with the message to display
  • position: Object This parameter is not mandatory. It defines the position where the tooltip is displayed and have the following properties:
{
  at: String. Default "right center". //Defines which position on the target element to align the positioned element against: "horizontal vertical" alignment.
  my: String. Default "left+6 center". //Defines which position on the element being positioned to align with the target element: "horizontal vertical" alignment.
  collision: String. Default "flipfit". //Only works when jQuery.ui.position is available.
}
  (function() {
    // Configure the global language setting
    jsu.regional.set(jsu.regional.english);
    // Sets default setting for tooltips
    jsu.settings.position = {
      at: "left bottom",
      my: "left+2 top+5"
    };
  }());

  $(function() {
    var email = $("#txtEmail");
    var admission = $("#txtDate");

    if (!email.fnIsValidFormat("email")) {
      // Displays the tooltip at the default position
      return !email.fnShowTooltip("The email address is not valid");
    }
    if (!admission.fnIsValidFormat("d")) {
      // Displays the tooltip at the specified position
      return !admission.fnShowTooltip(
        "The admission date is not valid", {
            at: "left+2 top-5",
            my: "left bottom"
        });
    }
    if (!$("#txtBirthday").fnIsValidDate({
        warning: "Your next birthday can't be lesser than today",
        isFuture: true
    })) return false;
  });

The magic of myth and legend has come true in our time. One types the correct incantation on a keyboard, and a display screen comes to life, showing things that never were nor could be;
The computer resembles the magic of legend in this respect, too. If one character, one pause, of the incantation is not strictly in proper form, the magic doesn't work. Human beings are not accustomed to being perfect, and few areas of human activity demand it. Adjusting to the requirement for perfection is, I think, the most difficult part of learning to program.
~ Frederick Brooks.