Skip to content
Rob Garrison edited this page Jul 31, 2016 · 60 revisions

Sections: Event Callbacks | beforeInsert | switchInput | validate | buildKey | Callback Variables | Callback Functions

Callbacks

  • Add a function to any or all of these callbacks in the initialization code as seen in the example below.

    • initialized
    • beforeVisible
    • visible
    • hidden
    • canceled
    • accepted
    • beforeClose
    • restricted
// Using Callbacks
$('#keyboard').keyboard({
	accepted : function(event, keyboard, el){
		alert('The content "' + el.value + '" was accepted!');
	}
});
  • Parameters:
    • event is the event variable - event.target is the same object as el.
    • keyboard is the keyboard data object which you can also access using $('#keyboard').getkeyboard()
    • el is the #keyboard object (DOM object). Use value to get the input/textarea content. Use el.keyboard to access the popup keyboard object.

Events

  • Triggered Events (all namespacing removed v1.21.0):

    • initialized - Event called immediately after the keyboard has been initialized for the first time.
    • beforeVisible - Event called before the keyboard is made visible, and before being positioned by the position utility (if used)
    • visible - Event called when the virtual keyboard is visible.
    • change - Event called after the virtual keyboard content has been accepted or canceled (non-namespaced event).
    • keyboardChange - Event called with every change in the virtual keyboard input (key clicked or manual input) (changed v1.21.0)
    • beforeClose - Event called when the keyboard is about to close
      • This event has an additional variable which indicates if the content was accepted or ignored. Example added below.
      • This event occurs before the accept or cancelled events, but after the content has been validated.
    • accepted - Event called when the accept button on the virtual keyboard is pressed.
    • canceled - Event called when the virtual keyboard was closed without accepting any changes.
    • hidden - Event called when the virtual keyboard is hidden.
    • inactive - Event called when the virtual keyboard loses focus but is always open (called instead of hidden).
    • restricted - Event called when the restrictInput is true and the user types in a restricted value.
    • keysetChange - Event called when the user changes the keyset.
  • Prior to v1.21.0, the only events that did not included a .keyboard namespace were: restricted & change.

  • The change.keyboard event was renamed to keyboardChange to prevent event conflicts.

// Using triggered events - set up to target all inputs on the page!
$('.ui-keyboard-input').bind('accepted', function(e, keyboard, el){
	var txt = 'Input ID of ' + el.id + ' has the accepted content of ' + el.value;
	alert(txt);
});

// Binding to the "beforeClose" event - it has an extra parameter ("accepted")
$('.ui-keyboard-input').bind('beforeClose', function(e, keyboard, el, accepted){
	var txt = "Virtual Keyboard for " + el.id + " is about to close, and it's contents were ";
	txt += (accepted ? 'accepted' : 'ignored');
	txt += '. Current content = ' + el.value;
	txt += '. Original content = ' + keyboard.originalContent;
	alert(txt);
});

Event names

  • Any of the following triggered event names can be changed by modifying the following variable (v1.20.0+):
$.keyboard.events = {
	// keyboard events
	kbChange        : 'keyboardChange',
	kbBeforeClose   : 'beforeClose',
	kbBeforeVisible : 'beforeVisible',
	kbVisible       : 'visible',
	kbInit          : 'initialized',
	kbInactive      : 'inactive',
	kbHidden        : 'hidden',
	kbRepeater      : 'repeater',
	kbKeysetChange  : 'keysetChange',
	// input events
	inputAccepted   : 'accepted',
	inputCanceled   : 'canceled',
	inputChange     : 'change',
	inputRestricted : 'restricted'
};

Please do not omit any of the definitions above, if you only want to rename a few event names, use jQuery $.extend():

$.extend($.keyboard.events, {
	kbInit    : 'keyboard-has-initialized-prepare-for-world-domination',
	kbVisible : 'rawr-here-we-go',
	kbHidden  : 'okay-maybe-next-week'
});
  • All of the above events are triggered on the input/textarea element.
  • There is one exception, the kbRepeater evnet which is triggered on the key being held down. This allows it to repeat the key within the input/textarea.

beforeInsert - [Function]

  • This callback function (added in v1.26) allows you to intercept the value before it is inserted into the input or textarea.

  • This function is unlike the other callbacks (except the validate callback) in that it is only a callback - there is not triggered event.

  • It works for both physical and virtual typing.

  • The parameters include the same three passed to the triggered callbacks: event (either keypress or whatever the keyBinding is set to use.

  • The last parameter is the actual character(s) about to be inserted.

  • Always return a value from this function. It can be an alterated string or a boolean false to prevent the text from being entered.

    beforeInsert: function(e, keyboard, el, txt) {
      // replace "A" with "Z"; all other keys are returned
      return txt === "A" ? "Z" : txt;
    }
  • Here is a simple demo remapping qwerty to enter a Greek alphabet: https://jsfiddle.net/Mottie/xkk95vf6/

    $(function() {
      var remapGreek = {
        // use key: value pairs to remap the keys
        "A": "Α", "B": "Β", "D": "Δ", "E": "Ε", "H": "Η", "I": "Ι",
        "K": "Κ", "L": "Λ", "M": "Μ", "N": "Ν", "O": "Ο", "P": "Π",
        "R": "Ρ", "S": "Σ", "T": "Τ", "X": "Χ", "Y": "Υ", "Z": "Ζ",
        "F": "Φ", "G": "Γ", "J": "Ξ", "C": "Ψ", "V": "Ω", "U": "Θ",
    
        "a": "α", "b": "β", "d": "δ", "e": "ε", "h": "η", "i": "ι",
        "k": "κ", "l": "λ", "m": "μ", "n": "ν", "o": "ο", "p": "π",
        "r": "ρ", "s": "σ", "t": "τ", "x": "χ", "y": "υ", "z": "ζ",
        "f": "φ", "g": "γ", "j": "ξ", "c": "ψ", "v": "ω", "u": "θ"
      };
    
      jQuery.keyboard.layouts['Greek-custom'] = {
        "lang": ["el"],
        // Greek
        "normal": [
          "\\ 1 2 3 4 5 6 7 8 9 0 ' ] {bksp}",
          "{tab} : w ε ρ τ υ θ ι ο π + }",
          "α σ δ φ γ η ξ κ λ \u0384 \u00A8 # {enter}",
          "{shift} < ζ χ ψ ω β ν μ , . - {shift}",
          "{accept} {alt} {space} {alt} {cancel}"
        ],
        "shift": [
          "| ! \" # $ % & / ( ) = ? [ {bksp}",
          "{tab} ; W Ε Ρ Τ Υ Θ Ι Ο Π + }",
          "Α Σ Δ Φ Γ Η Ξ Κ Λ \u00A8 \u0385 @ {enter}",
          "{shift} < Ζ Χ Ψ Ω Β Ν Μ ; : _ {shift}",
          "{accept} {alt} {space} {alt} {cancel}"
        ],
        // latin characters
        "alt": [
          "\\ 1 2 3 4 5 6 7 8 9 0 ' ] {bksp}",
          "{tab} q w e r t y u i o p + }",
          "a s d f g h j k l \u0384 \u00A8 # {enter}",
          "{shift} < z x c v b n m , . - {shift}",
          "{accept} {alt} {space} {alt} {cancel}"
        ],
        "alt-shift" : [
          "| ! \" # $ % & / ( ) = ? [ {bksp}",
          "{tab} Q W E R T Y U I O P * {",
          "A S D F G H J K L \u00A8 \u0385 @ {enter}",
          "{shift} > Z X C V B N M ; : _ {shift}",
          "{accept} {alt} {space} {alt} {cancel}"
        ]
      };
    
      $('#keyboard').keyboard({
        layout: 'Greek-custom',
        beforeInsert: function(e, keyboard, el, textToAdd) {
          return keyboard.altActive ?
            // don't remap if alt is active
            textToAdd :
            // remap at all other times, but fallback
            // for un-remapped values
            remapGreek[textToAdd] || textToAdd;
        }
      });
    });

switchInput - [Function]

  • This function is only called when the enterNavigation option is true and:
    • The "shift+enter" key is pressed; for input and textarea.
    • Or, "enter" is pressed in an input only. In a textarea, a carriage return is added.
  • The following code shows the default behavior of this function.
    • It closes the current keyboard
    • Finds all keyboards on the page and figures out the index of the current keyboard.
    • Finds the next keyboard, if goToNext is true or previous keyboard, if goToNext is false.
    • If the next keyboard doesn't exist, go back to the first.
    • Or, if the previous keyboard doesn't exist, it will go to the last.
    • Give focus to the input that has a keyboard attached to open that keyboard.
$('#keyboard').keyboard({
  // Go to next or prev inputs
  // goToNext = true, then go to next input; if false go to previous
  // isAccepted is from autoAccept option or true if user presses shift-enter
  switchInput : function(keyboard, goToNext, isAccepted){
    // close this keyboard
    keyboard.close(isAccepted);
    // find ALL inputs with a keyboard attached, but make sure we aren't
    // targetting the preview window - it's a clone of the original input
    var all = $('.ui-keyboard-input:not(.ui-keyboard-preview)'),
    // find the index of the current keyboard, then go forward or backward one input
    indx = all.index(keyboard.$el) + (goToNext ? 1 : -1);
    // If we're on the last input, go back to the first (zero-based index)
    if (indx > all.length - 1) { indx = 0; } // go to first input
    // focus on the selected input; this opens the keyboard for that input;
    // if indx is -1, all.eq(-1) will open the last keyboard
    all.eq(indx).focus();
  }
});

This callback was added to change the enter navigation behaviour. For example, if you don't care if a keyboard is attached to the input, then just change the following line to target all inputs (that are not the preview):

    var all = $('input:not(.ui-keyboard-preview)'),

validate - [Function]

This function is unlike the other callbacks in that it is only a callback - there is no triggered event, so you can not use bind('validate') because this function needs to return a flag of true or false to the plugin. This function is called at two points:

  • During user input

    • But only if the acceptValid option is true.
    • It will validate the content while the user is typing.
    • If the function returns true because the content is valid, the accept button will have the class of "ui-keyboard-valid-input".
    • If the function returns false because the content is invalid the accept button will have the class of "ui-keyboard-invalid-input".
    • When adding your own validate function, make sure to use the isClosing variable to determine if the check is during active input or before keyboard closing. See the example below.
  • Before the beforeClose event to check the validity of the content and abort or continue the keyboard closing.

    • The validity function is always run at this point, even if the acceptValid option is false.
    • If the function returns true, the keyboard will continue on, accept the content and close (if not always open).
    • If this function returns false and the keyboard will abort the close, but only if the cancelClose option is true.
  • This function is set by default to function(keyboard, value, isClosing){ return true; }.

  • Any other actions can be performed or called from inside of this function. For example, if the value is invalid, and you wish to then clear the keyboard input, do the following:

$('#keyboard').keyboard({
  validate: function(keyboard, value, isClosing){
    // test value for an email address
    var test = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/.test(value);
    // if the value is invalid, alert the user
    if (!test && isClosing) {
        alert('please enter a valid email address');
    }
    // return valid test (true or false)
    return test;
  }
});

// modify accept keyaction to alert when content has been accepted
$.extend($.keyboard.keyaction, {
    accept: function(base) {
        if (base.accept()) {
            alert('Accepted!');
        }
    }
});

This example shows how to add a signal/notification that the input is invalid

$('#keyboard').keyboard({
  acceptValid : true,
  validate    : function(keyboard, value, isClosing) {

    // only allow a 3-digit number
    var valid = /^\d{3}$/g.test(value);

    if (isClosing && valid) {

      // *** closing and valid ***
      return true;
    } else if (isClosing && !valid) {

      // *** closing and not valid ***
      // add an indicator/popup here to tell the user the input is not valid
      keyboard.$preview.addClass('red-border') // needs css: .red-border { border: #f00 1px solid; }
      // remove indicator after 5 seconds
      setTimeout(function(){
        keyboard.$preview.removeClass('red-border'); // no more red border
      }, 5000);
      // fire off a canceled event
      keyboard.$el.trigger('canceled', [ keyboard, keyboard.el ]  );
      return false;
    }

    // *** not closing ***
    // continuous checking during input, so don't go nuts here
    // accept button is enabled/disabled automatically if "acceptValid" is true
    return valid;
  }
});

buildKey - [Function]

This function is called during the initial build of a keyboard layout. It is intended to allow you to modify the HTML of the key because any HTML inside the display option is converted into text.

The extra values should be considered as read only as changing them will not effect the behavior of the key, unless the attributes of the $key are modified.

  • In the buildKey callback, both the keyboard object (see "Callback Variables" & "Callback Functions" sections below) and key specific data are provided:

    buildKey : function( keyboard, data ) {
      /*
      data = {
        // READ ONLY
        isAction : [boolean] true if key is an action key
        name     : [string]  key class name suffix ( prefix = 'ui-keyboard-' ); may include decimal ascii value of character
        value    : [string]  text inserted (non-action keys)
        title    : [string]  title attribute of key
        action   : [string]  keyaction name
        html     : [string]  HTML of the key; it includes a <span> wrapping a modified data.value
        // use to modify HTML
        $key     : [object]  jQuery selector of key which is already appended to keyboard
      }
      */
      return data;
    }

    Here is an example of how to use it:

    buildKey : function( keyboard, data ) {
      if ( data.value === 'Cat Emotes' ) {
        // add break
        data.$key.html( 'Cat<br>Emotes' );
      }
      return data;
    }

NOTE The html must contain a span with the class name from the `

This is a list of variables and functions available during any of the above callback functions Note that if the variable has a $ in it's name, then it is a jQuery object.

Objects

  • keyboard.el - original keyboard input object.
  • keyboard.$el - original keyboard input jQuery object; it's the same as doing $( keyboard.el ).
  • keyboard.preview - will point to the preview window input object, if the usePreview option is true; it will point to keyboard.el if usePreview is false.
  • keyboard.$preview - will point to the preview window input jQuery object, if the usePreview option is true; it will point to keyboard.$el if usePreview is false.
  • keyboard.$keyboard - jQuery object of the entire keyboard

Values

  • keyboard.$preview.val() - always get the current keyboard content using this method
  • keyboard.originalContent - contains the text from the input/textarea before the keyboard opened.
  • keyboard.options.{option} - access any of the options; try not to modify them from here as it may break the keyboard.
  • keyboard.last - contains information about the last key pressed
    • start - caret start position.
    • end - caret end position.
    • $key - jQuery object of the last key pressed (empty array if physical keyboard was used).
    • key - text of last key pressed (may not reflect accurately if mousewheel was used).
    • preVal - previous preview input value.
    • val - last (current) preview input value.
    • layout - last layout used by the keyboard (see #333).
    • keyset - array of keyset states for: [ shift, alt, meta ] keys.
    • event - last keyboard event (either keypress, mousedown or touchstart).
    • eventTime - time of last event, likely not the same as the keyboard.last.event.timeStamp value. In v1.22.0, this contains the time when the keyboard closed - useful if you want to prevent reopening the same keyboard when clicking an external link; see #333.
    • virtual - (boolean) if true, the virtual keyboard caused the last (usually "change") event. If false, the physical keyboard caused the last event.

States

  • keyboard.isVisible - true when the keyboard is visible; false when hidden.
  • keyboard.isCurrent() - function returns true when the keyboard is the current; Needed to figure out which one has focus when multiple keyboards are open (alwaysOpen: true).
  • keyboard.shiftActive - true when the shift key is active; false when not active.
  • keyboard.altActive - true when the alt key is active; false when not active.
  • keyboard.metaActive - false when the meta key is no active, and contains the meta key name when it is active (e.g. meta99)
  • keyboard.capsLock - true when the caps lock key is active; false when not active. Please note that this particular value is not 100% reliable as it isn't possible to detect the actual state of this key.
  • keyboard.enabled - true when the keyboard (all keys and preview) are enabled; set to false then call the keyboard.toggle() function to disable the keyboard keys & input.

Most of these functions are NOT chainable, except for the reveal & redraw functions (i.e. keyboard.insertText('hello').close() will NOT work). See the Setup page for more examples on how to use the typing extension.

reveal

  • Use keyboard.reveal()
  • Opens the keyboard.
  • This function is chainable, e.g. keyboard.reveal().insertText('hello') will work.
  • Added in v1.19.0, to change the current layout, call this function with a true flag:
  • Removed true flag in v1.25.22. Use redraw instead.

redraw

  • Extracted the code from keyboard.reveal() in v1.25.22 to change the current layout.

  • Use keyboard.redraw()

  • Removes previous keyboard & rebuilds it after you change the layout.

  • This function is chainable.

    keyboard.options.layout = 'french-azerty-1';
    keyboard.redraw();

accept

  • Use keyboard.accept()
  • This function will accept the keyboard contents, then close the keyboard.

close

  • Use keyboard.close()
  • This function will reject the keyboard contents, then close the keyboard.

insertText

  • Use keyboard.insertText("text")
  • This function will insert text into the keyboard at the current caret position.
  • If you want to backspace, then use "bksp" and nothing else to remove the character to the left of the current caret position.

checkCombos

  • Use keyboard.checkCombos()
  • This function will check the current keyboard contents for letter combinations and convert them (e.g. ~ + o becomes õ).

checkMaxLength

  • Use keyboard.checkMaxLength()
  • This function will check the length of the current keyboard contents and remove any excess.
  • Nothing will happen if the maxLength option is false.

showKeySet(meta)

  • This method was simplified in v1.23.2.

  • Use keyboard.showKeySet(meta)

  • The "meta" variable is needed to tell the function which keyset(s) to show. The order of the keyset names does not matter.

  • See the examples below:

    Example: show shift key set

    keyboard.showKeySet('shift');

    Example: show alt+shift key set

    keyboard.showKeySet('shift+alt');

    Example: show meta2 shifted key set

    keyboard.showKeySet('meta2+shift');

toggle

  • Use keyboard.toggle()
  • This function sets the keyboard state to match the keyboard.enabled state; when false, all keys (except the toggle key) & input are disabled.
  • Add a {toggle} button to your layout to allow the user to change this state.

destroy

  • Use keyboard.destroy()

  • This function completely removes the keyboard and events from the input.

  • This function is needed if you plan to change the keyboard layout when using the same input. See the layout demo.

     keyboard=$('#keyboard').keyboard().getkeyboard();
     keyboard.destroy();

Wiki Pages: Home | FAQ | Setup | Usage | Options ( Layout, Language, Usability, Actions ) | Methods | Theme | Log

Clone this wiki locally