Documentation | Code |
---|---|
jQuery Plugin: jKit
Put jQuery and jKit on all your pages and HTML becomes so much better. And the best thing? You really don’t have to be a programmer to create a trully amazing website! jKit has 99% of all the features you ever need. You don’t have to check out dozens of plugins, learn how to use them, only to find out they don’t work in a specific browser. And even if jKit doesn’t have that one feature you need right now, jKit is fully extendable with plugins and command replacements, all that and your API always stays the same.
Copyright
LicensejKit is open source and MIT licensed. For more informations read the license.txt file Basic UsageInside your head tag or at the bottom of your page before the closing body tag:
On your HTML elements:
The Source | |
Create our plugins local scope, make sure $ is mapped to jQuery and guarantee that undefined really is undefined. | 57 (function($, undefined) { |
Create our main function with the following parameters:
| 65 $.jKit = function(element, options, moreoptions) { |
Define all plugin defaults. These can be overwritten by the plugins options set on init. | 69 var defaults = { |
First we set some general defaults: | 73 74 75 76 77 78 79 80 81 82 83 84 85 prefix: 'jkit', dataAttribute: 'data-jkit', activeClass: 'active', errorClass: 'error', successClass: 'success', ignoreFocus: false, ignoreViewport: false, keyNavigation: true, touchNavigation: true, plugins: {}, replacements: {}, delimiter: ',', loadminified: true, |
codeblock: macros | |
Now we set some default macros for often used command/parameter combinations: | 91 92 93 94 macros: { 'hide-if-empty': 'binding:selector=this;source=text;mode=css.display', 'smooth-blink': 'loop:speed1=2000;duration1=250;speed2=250;duration2=2000' }, |
codeblock: /macros | |
Next we’re defining all the default options for each command. You can get a good overview of them on the official cheat sheet. | 101 102 commands: {} }; |
Set an alias to this so that we can use it everywhere inside our plugin: | 106 var plugin = this; |
Create an object for the plugin settings: | 110 plugin.settings = {}; |
Create an opject to store all jKit command implementations | 114 plugin.commands = {}; |
Array to stor all command execution so that we can find out if something was already executed | 118 plugin.executions = {}; |
And while were’re at it, cache the DOM element: | 122 123 var $element = $(element), element = element; |
In case we are just applying a single command, we need to take the options from the moreoptions parameter: | 127 128 129 130 131 132 133 if (typeof options == 'string'){ var singlecommand = options; if (moreoptions == undefined){ moreoptions = {}; } options = moreoptions; } |
For a few things, we need some local plugin variables and objects, let’s set them now: | 137 138 139 140 var startX, startY; var windowhasfocus = true; var uid = 0; var commandkeys = {}; |
We want to know if the current window is in focus or not, we can do this with the window object (just not in IE7 & 8): | 144 145 146 147 148 149 150 if ($.support.htmlSerialize || $.support.opacity){ $(window).focus(function() { windowhasfocus = true; }).blur(function() { windowhasfocus = false; }); } |
Plugin Functions | |
The following collection of functions are internally used. There is a way to call them with an external script, but you should know what you’re doing! Here’s an exmaple:
The above code would call the plugin.executeCommand() function. | |
initThe init function is called on plugin init and sets up all the stuff we need. | 165 plugin.init = function($el){ |
In case this function is called without a specific DOM node, use the plugins main DOM element: | 169 if ($el == undefined) $el = $element; |
Extend the plugin defaults with the applied options: | 173 174 175 176 plugin.settings = $.extend({}, defaults, options); var s = plugin.settings; if (singlecommand != undefined){ |
If this is an initialization of a single command, all we have to do is execute that one command: | 180 181 182 plugin.executeCommand($el, singlecommand, options); } else { |
It’s now time to find all DOM nodes that want to execute a jKit command. You can either use the data-jkit attribute, or the rel attribute. However, we strongly recommend to use the data-jkit attribute! The rel attribute support will probably removed at some point. | 188 189 190 $el.find("*[rel^=jKit], *["+s.dataAttribute+"]").each( function(){ var that = this; |
Get the rel or data-jkit attribute and extract all individual commands (they have to be inside square brackets): | 194 195 196 197 198 199 200 201 202 203 204 var rel = $(this).attr('rel'); var data = $(this).attr(s.dataAttribute); if (data != undefined){ rel = $.trim(data).substring(1); } else { rel = $.trim(rel).substring(5); } rel = rel.substring(0, rel.length-1); rel = rel.replace(/]s+[/g, "]["); relsplit = rel.split(']['); |
Now look at each command seperately: | 208 $.each( relsplit, function(index, value){ |
First convert all the escaped characters into internal jKit strings. Later we convert them back and unescape them. | 212 213 214 215 216 217 218 219 220 221 value = value .replace(/\=/g,'|jkit-eq|') .replace(/\:/g,'|jkit-dp|') .replace(/\;/g,'|jkit-sc|') .replace(/\[/g,'|jkit-sbo|') .replace(/\]/g,'|jkit-sbc|') .replace(/\*/g,'|jkit-st|') .replace(/\ /g,'|jkit-sp|'); value = $.trim(value); |
Is this a macro call? Let’s check if we find a macro with this name: | 225 if (s.macros[value] != undefined) value = s.macros[value]; |
Now it’s time to parse the options: | 229 var options = plugin.parseOptions(value); |
It’s still possible that this is a macro, just with changed options. Let’s check that and apply the macro if needed: | 233 234 235 236 237 if (s.macros[options.type] != undefined){ var macrooptions = plugin.parseOptions(s.macros[options.type]); options.type = macrooptions.type; options = $.extend({}, macrooptions, options); } |
If this is a macro definition, add the current command string to the macros array: | 241 242 243 if (options.type == 'macro' && relsplit[index-1] != undefined){ plugin.settings.macros[options.name] = relsplit[index-1]; |
If this is the special repeat command, parse the options and than add it to the delivered event handler: | 247 248 249 250 251 252 253 254 255 256 257 258 } else if (options.type == 'repeat' && relsplit[index-1] != undefined){ var prevoptions = plugin.parseOptions(relsplit[index-1]); $el.on( options.onevent, function(){ if (options.delay == undefined) options.delay = 0; setTimeout( function(){ plugin.executeCommand($(that), prevoptions.type, prevoptions); }, options.delay); }); } else { |
Looks like this isn’t one of the special use commands, so lets execute one of the regular ones. | |
If the targets option is set, we first have to find out to which target nodes we have to apply the command: | 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 var targets = []; if (options.target != undefined){ var targetsplit = options.target.split('.'); targetsplit = [targetsplit.shift(), targetsplit.join('.')] if (targetsplit[1] == undefined){ targetsplit[1] = '*'; } switch(targetsplit[0]){ case 'children': $(that).children(targetsplit[1]).each( function(){ targets.push(this); }); break; case 'each': $(that).find(targetsplit[1]).each( function(){ targets.push(this); }); break; default: targets.push(that); } } else { targets.push(that); } $.each( targets, function(i,v){ |
First parse all dynamic options. They are declared like this:
| 298 var thisoptions = plugin.parseDynamicOptions(options); |
Now it’s time to find out what the command key is for this specific command call. This can be set either by the commandkey option, the dot syntax or if both are not set, we take the elements id attribute or as a last option, we just generate an unique id. | 304 305 306 307 308 309 310 311 if (thisoptions.commandkey == undefined){ var id = $(that).attr("id"); if (id != undefined){ thisoptions.commandkey = id; } else { thisoptions.commandkey = s.prefix+'-uid-'+(++uid); } } |
Now as we have the commandkey, we store it in the plugins commandkey array together with some other useful information for later use: | 316 317 318 319 320 321 322 if (thisoptions.commandkey != undefined){ commandkeys[thisoptions.commandkey] = { 'el': v, 'options': thisoptions, 'execs': 0 }; } |
Next we need to check if we have to immediately execute the command or if we have to execute it later on a specific event: | 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 if (thisoptions.onevent !== undefined || thisoptions.andonevent !== undefined){ var events = []; if (thisoptions.onevent !== undefined) events.push(thisoptions.onevent); if (thisoptions.andonevent !== undefined) events.push(thisoptions.andonevent); var e = events.join(' '); $el.on( e, function(){ if (s.replacements[thisoptions.type] != undefined && typeof(s.replacements[thisoptions.type]) === "function"){ s.replacements[thisoptions.type].call(plugin, v, thisoptions.type, thisoptions); } else { plugin.executeCommand(v, thisoptions.type, thisoptions); } }); } if (thisoptions.onevent === undefined){ |
If this is a command that follows another command we need to make sure that the command before this one in the command chain has already been executed: | 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 if (relsplit[index-1] != undefined){ var prevcmd = ''; if (relsplit[(index-1)] != undefined){ var prevoptions = plugin.parseOptions(relsplit[index-1]); prevcmd = prevoptions.type + '.' + thisoptions.commandkey + '.executed'; } if (prevcmd != '' && plugin.executions[prevoptions.type + '.' + thisoptions.commandkey + '.executed'] === undefined){ $el.on( prevcmd, function(){ if (s.replacements[thisoptions.type] != undefined && typeof(s.replacements[thisoptions.type]) === "function"){ s.replacements[thisoptions.type].call(plugin, v, thisoptions.type, thisoptions); } else { plugin.executeCommand(v, thisoptions.type, thisoptions); } }); } else { if (s.replacements[thisoptions.type] != undefined && typeof(s.replacements[thisoptions.type]) === "function"){ s.replacements[thisoptions.type].call(plugin, v, thisoptions.type, thisoptions); } else { plugin.executeCommand(v, thisoptions.type, thisoptions); } } } else { |
If we don’t have an event set, we execute it immediately. Wee need to check if a command replacement for this command is available and if yes, call it. | 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 if (s.replacements[thisoptions.type] != undefined && typeof(s.replacements[thisoptions.type]) === "function"){ s.replacements[thisoptions.type].call(plugin, v, thisoptions.type, thisoptions); } else { plugin.executeCommand(v, thisoptions.type, thisoptions); } } } }); } }); }); } }; |
applyMacroThe applyMacro function lets us execute predefined macros. | 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 plugin.applyMacro = function($el, macro){ var s = plugin.settings; if (s.macros[macro] != undefined){ var value = s.macros[macro]; var options = plugin.parseOptions(value); if (s.replacements[options.type] != undefined && typeof(s.replacements[options.type]) === "function"){ s.replacements[options.type].call(plugin, $el, options.type, options); } else { plugin.executeCommand($el, options.type, options); } } }; |
parseOptionsThe parseOptions function takes a command string and creates an array out of it with all options. It automatically detects the command type and command key. An input string can look like this (optionally with additional spaces and newlines):
| 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 plugin.parseOptions = function(string){ var relsplit = string.split(':'); var commandsplit = relsplit[0].split('.'); var options = { 'type': $.trim(commandsplit[0]) }; if (commandsplit[1] !== undefined){ options['commandkey'] = commandsplit[1]; } if (options.execute == undefined){ options.execute = 'always'; } if (relsplit.length > 1){ var optionssplit = relsplit[1].split(';'); $.each( optionssplit, function(key, value){ var optionssplit2 = value.split('='); options[$.trim(optionssplit2[0])] = $.trim(optionssplit2[1]); }); } return options; }; |
fixSpeedThe fixSpeed function is used to make sure that a speed option has a correct value, either “slow”, “fast” or an integer. | 465 466 467 468 469 470 471 472 plugin.fixSpeed = function(speed){ if (speed != 'fast' && speed != 'slow'){ speed = parseInt(speed); } return speed; }; |
parseDynamicOptionsThe parseDynamicOptions looks for dynamic options that look like this:
Currently only the random options are supported, but more stuff is planned, like increase or decrease. | 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 plugin.parseDynamicOptions = function(options){ var parsedoptions = {}; for (index in options){ var v = options[index]; if (v !== undefined && v.indexOf("{") > -1 && v.indexOf("|") > 0 && v.indexOf("}") > 1){ var option = ''; var dyn = false; var dynstr = ''; var parse = false; for (var i=0; i<=(v.length-1);i++){ if (!dyn && v.charAt(i) == '{'){ dyn = true; } else if (dyn && v.charAt(i) == '}'){ dyn = false; parse = true; } if (dyn || parse){ dynstr += v.charAt(i); if (parse){ dynstr = dynstr.slice(1, -1); var dynsplit = dynstr.split('|'); if (dynsplit[0] == 'rand'){ var valsplit = dynsplit[1].split('-'); option += plugin.getRandom(Number(valsplit[0]), Number(valsplit[1])); } parse = false; dynstr = ''; } } else { option += v.charAt(i); } } parsedoptions[index] = option; } else { parsedoptions[index] = v; } } return parsedoptions; } |
getRandomThe getRandom function simply generates a random number between a minimum number and a maximum number. | 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 plugin.getRandom = function(min, max) { if(min > max) { return -1; } if(min == max) { return min; } var r; do { r = Math.random(); } while(r == 1.0); return min + parseInt(r * (max-min+1)); } |
findElementTagThe findElementTag function makes it possible to find the tag name of a specific element in a previously defined structure. This makes it possible to write agnostic HTML for tab or similar structures. For example on the tab command, both this structures would be succesfully detected:
Check the tab command to get an example of how to use the function. | 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 plugin.findElementTag = function($container, selector, pos, defaultval){ var output = ''; if ( pos !== undefined && !isNaN(pos) && parseInt(pos) == pos ){ if ($container.find(selector).length > pos){ output = $($container.find(selector).get(pos)).prop('tagName'); } } else { var tags = {}; $container.find(selector).each( function(i){ if (i < 25){ var tag = $(this).prop('tagName'); if (tag[0] != ''){ if (tags[tag] !== undefined){ tags[tag]++; } else { tags[tag] = 1; } } } else { return false; } }); var max = 0; var maxkey = ''; for (var key in tags){ if (tags[key] > max){ max = tags[key]; maxkey = key; } } output = maxkey; } if (output !== undefined && output != ''){ return output; } else { return defaultval; } }; |
addDefaultsThe addDefaults function adds all the default options to the options array. Additionally all speed options are fixed if needed. | 627 628 629 630 631 632 633 634 635 636 637 638 639 plugin.addDefaults = function(command, options){ if (plugin.settings.commands[command] != undefined){ var c = plugin.settings.commands[command]; $.each(c, function(i, v){ if (options[i] == undefined) options[i] = v; if (i.indexOf('speed') > -1) options[i] = plugin.fixSpeed(options[i]); }); } return options; }; |
executeCommandThe executeCommand function is used to execute a command on a specific DOM node with an array of options. | 645 plugin.executeCommand = function(that, type, options){ |
First create a few shortcuts: | 649 650 var s = plugin.settings; var $that = $(that); |
Create a temporary array in case this command isn’t already implemented or loaded. The array acts as a command queue that stores all executions of this command till the command is actually loaded. | 655 656 657 if (plugin.commands[type] === undefined){ plugin.commands[type] = []; } |
As long as this plugin command is an array, we know that it isn’t loaded already, so load it! | 661 if ($.isArray(plugin.commands[type])){ |
Craete an entry in the command queue with the current element and options: | 665 666 667 668 plugin.commands[type].push({ 'el': that, 'options': options }); |
We only have to start the ajax in case this was the first command in the queue: | 672 673 674 675 676 677 678 679 680 681 if (s.loadminified){ var commandurl = 'jquery.jkit.commands/' + type + '.min.js'; } else { var commandurl = 'jquery.jkit.commands/' + type + '.js'; } if (plugin.commands[type].length == 1){ $.ajax({ url: 'jquery.jkit.commands/' + type + '.js', success: function(data){ |
The script loaded succesfully! Store the queue in a temporary array and than eval the loaded script. This way it will be loaded in the current scope and add itself to the plugin object. The jQuery.getScript method would load it globally, that’s of no use to us. | 687 688 689 if (data.indexOf('plugin.commands.') !== -1){ var queue = plugin.commands[type]; eval(data); |
Now execute all commands in our queue: | 693 694 695 696 697 698 699 700 701 $.each(queue, function(i,v){ plugin.executeCommand(v.el, type, v.options); }); } }, dataType: "text" }); } |
We can stop this function now. It will be called again with the same options as soon as the command is loaded. | 705 706 707 return $that; } |
Everything below here will be executes if the command is loaded. | |
Trigger the jkit-commandinit event on the main element with all useful information attached to it. This event is currently not used internally, but can of course be listened to from outside the plugin. | 714 $element.trigger('jkit-commandinit', { 'element': $that, 'type': type, 'options': options }); |
Check if there is a limit set on how many times we’re allowed to execute this command (based on the command key) | 718 719 720 721 722 723 if (options.commandkey !== undefined){ commandkeys[options.commandkey]['execs']++; if ((options.execute == 'once' && commandkeys[options.commandkey]['execs'] > 1) || (!isNaN(options.execute) && commandkeys[options.commandkey]['execs'] > options.execute)){ return $that; } } |
Add all default options where there isn’t an option set: | 727 728 729 options = plugin.addDefaults(type, options); $.each( options, function(i,v){ |
Convert jKit’s special escaping strings to their regular characters: | 733 734 735 736 737 738 739 740 741 742 if (typeof v == 'string'){ options[i] = v = v .replace(/|jkit-eq|/g,'=') .replace(/|jkit-dp|/g,':') .replace(/|jkit-sc|/g,';') .replace(/|jkit-sbo|/g,'[') .replace(/|jkit-sbc|/g,']') .replace(/|jkit-st|/g,'*') .replace(/|jkit-sp|/g,' '); } |
Call or get all dynamic options (those with an asterix at the end): | 746 747 748 749 750 751 752 if (typeof v == 'string' && v.slice(-1) == '*'){ options[i] = window[v.slice(0, -1)]; if (typeof options[i] == 'function'){ options[i] = options[i].call(that); } } }); |
Execute the commands main function: | 756 757 758 759 760 761 762 763 764 plugin.commands[ type ].execute($that, options); if (type != 'remove'){ $element.trigger(type + '.' + options.commandkey + '.executed', {}); plugin.executions[type + '.' + options.commandkey + '.executed'] = true; } return $that; }; |
triggerEventThe triggerEvent function is used by various commands to trigger an event on an element with the commands options added to it: | 771 772 773 774 775 776 777 778 779 780 781 782 783 plugin.triggerEvent = function(event, $el, options){ if (options.commandkey !== undefined){ var eventsplit = event.split(' '); $.each( eventsplit, function(i,v){ $element.trigger(options.commandkey+'.'+v, { 'element': $el, 'options': options }); }); } }; |
cssFromStringThe cssFromString function is used by the animation command. It parses a specially formated string and creates an object that contains all CSS data. Here’s an exmaple of the string format:
| 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 plugin.cssFromString = function(css){ var partsplit = css.split(','); var cssdata = {}; $.each( partsplit, function(i,v){ var innersplit = v.split('('); if (innersplit.length == 2){ var property = innersplit[0]; var value = innersplit[1].slice(0,-1); cssdata[property] = value; } }); return cssdata; }; plugin.addCommandDefaults = function(c, d){ |
Add the defaults: | 818 defaults.commands[c] = d; |
And trigger the loaded event for this command (command.name.loaded) so everyone knows that this command is ready: | 822 823 824 $element.trigger('command.'+c+'.loaded', {}); }; |
addKeypressEventsThe addKeypressEvents function is used by the key command and various other features and adds a specific keycode event to an element. | 832 plugin.addKeypressEvents = function($el, code){ |
Check first if key navigations aren’t globally switched off: | 836 if (plugin.settings.keyNavigation){ |
Listen to the documents keydown event: | 840 $(document).keydown(function(e){ |
Only add the event if this isn’t a textaream, select or text input: | 844 if ( this !== e.target && (/textarea|select/i.test( e.target.nodeName ) || e.target.type === "text") ) return; |
Map keycodes to their identifiers: | 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 var keys = { 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta" }; |
Add the alphabet: | 904 905 906 907 908 for(var i=48; i<=90; i++){ keys[i] = String.fromCharCode(i).toLowerCase(); } if ($.inArray(e.which, keys)){ |
Add special keys: | 912 913 914 915 916 917 918 var special = ''; if (e.altKey) special += 'alt+'; if (e.ctrlKey) special += 'ctrl+'; if (e.metaKey) special += 'meta+'; if (e.shiftKey) special += 'shift+'; var keycode = special+keys[e.which]; |
If the code matches, trigger the event: | 922 923 924 925 926 927 928 929 930 931 if (keycode == code){ $el.trigger(special+keys[e.which]); e.preventDefault(); } } }); } } |
jKit CommandsBelow are all commands included in this version of jKit. All other commands will be autoloaded. | |
Init CommandThe init command is a special internal command that inits a DOM node with jKit. It shares all the features of other commands, but is always included and a central part of jKit. | 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 plugin.commands.init = (function(){ var command = {}; plugin.addCommandDefaults('init', {}); command.execute = function($that, options){ plugin.init($that); plugin.triggerEvent('complete', $that, options); }; return command; }()); |
Encode CommandThe encode command apply various encodings to the content of an element. If the option is code, the content is not only HTML encoded, it can even remove the extra tab whitespace you get if you have that content indented inside the code element. | 971 plugin.commands.encode = (function(){ |
Create an object that contains all of our data and functionality. | 975 var command = {}; |
This are the command defaults: | 979 980 981 982 plugin.addCommandDefaults('encode', { 'format': 'code', 'fix': 'yes' }); |
The execute function is launched whenever this command is executed: | 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 command.execute = function($that, options){ switch(options.format) { case 'code': var src = $that.html(); if (options.fix == 'yes'){ src = preFix(src); } $that.html(src.replace(/</g, '<').replace(/>/g, '>')); break; case 'text': $that.html($that.text()); break; case 'esc': $that.html(escape($that.html())); break; case 'uri': $that.html(encodeURI($that.html())); break; } }; var preFix = function(str){ var lines = str.split("n"); var min = 9999; $.each( lines, function(i,v){ if ($.trim(v) != ''){ var cnt = -1; while(v.charAt(cnt+1) == "t"){ cnt++; } cnt++; if (cnt < min){ min = cnt; } } }); $.each( lines, function(i,v){ lines[i] = v.substr(min); }); return lines.join("n"); }; return command; }()); |
Chart CommandThe chart command let’s us create simple horizontal bar charts using different sized divs. This is definitely a good candidate for a command replacement using the canvas element to draw different charts. | 1049 plugin.commands.chart = (function(){ |
Create an object that contains all of our data and functionality. | 1053 var command = {}; |
This are the command defaults: | 1057 1058 1059 1060 1061 1062 plugin.addCommandDefaults('chart', { 'max': 0, 'delaysteps': 100, 'speed': 500, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 1066 1067 1068 command.execute = function($that, options){ var s = plugin.settings; |
First get the main label from the THEAD and the main element id: | 1072 1073 var label = $that.find('thead > tr > th.label').text(); var id = $that.attr('id'); |
Now get all data column labels from the THEAD | 1077 1078 1079 1080 1081 1082 1083 var datalabels = []; $that.find('thead > tr > th').each( function(){ if (!$(this).hasClass('label')){ datalabels.push( $(this).text() ); } }); |
And the last thing we need is all the data from the tbody: | |
task: Why do we get the TH from TBODY? This should be TDs! | |
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 var max = 0; var plots = []; $that.find('tbody tr').each( function(){ var plot = { 'label': $(this).find('th.label').text(), 'data': [] }; $(this).find('th').each( function(){ if (!$(this).hasClass('label')){ var val = Number($(this).text()); max = Math.max(val, max); plot.data.push(val); } }); plots.push(plot); }); | |
Set the maximum value for our chart either from the options or from all the data values: | 1106 1107 1108 if (options.max > 0 && max < options.max){ max = options.max; } |
Time to construct our chart element: | 1112 1113 1114 1115 var $chart = $('<div/>', { id: id, 'class': s.prefix+'-chart' }); |
Now loop through each data label and add the data from each plot to it. We are using a delay for each plot and increase that delay with each new data label. This way we get a nice animation where every plot is shown a little bit later. | 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 var steps = 0; var delay = 0; $.each(datalabels, function(i,v){ steps++; var $step = $('<div/>', { 'class': s.prefix+'-chart-step' }).html('<label>'+v+'</label>').appendTo($chart); $.each( plots, function(i2,v2){ if (plots[i2].data[i] > 0){ var $plot = $('<div/>', { 'class': s.prefix+'-chart-plot '+s.prefix+'-chart-plot'+i2 }).appendTo($step); $('<div/>') .text(plots[i2].label) .delay(delay) .animate({ 'width': (plots[i2].data[i]/max*100)+'%' }, options.speed, options.easing) .appendTo($plot); $('<span/>', { 'class': s.prefix+'-chart-info' }) .text(label+' '+plots[i2].label+': '+plots[i2].data[i]+' '+options.units) .appendTo($plot); } }); if (steps == datalabels.length){ setTimeout( function(){ plugin.triggerEvent('complete', $that, options); }, options.speed+delay); } delay += Number(options.delaysteps); }); |
Evyerything is set up, so replace the original element with our new chart: | 1160 1161 1162 $that.replaceWith($chart); }; |
Add local functions and variables here … | 1166 1167 1168 return command; }()); |
Animation CommandThe animation command has two uses. Either it can be used to animate the CSS of an element or it can be used to animated a kind of keyframe animation with attribute tweenings. | 1177 plugin.commands.animation = (function(){ |
Create an object that contains all of our data and functionality. | 1181 var command = {}; |
This are the command defaults: | 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 plugin.addCommandDefaults('animation', { 'fps': 25, 'loop': 'no', 'from': '', 'to': '', 'speed': '500', 'easing': 'linear', 'delay': 0, 'on': '' }); |
The execute function is launched whenever this command is executed: | 1198 1199 1200 command.execute = function($that, options){ var s = plugin.settings; |
First check if this is a CSS animation: | 1204 if (options.to != ''){ |
If the from option is set, we first have to set the initial CSS: | 1208 1209 1210 if (options.from != ''){ $that.css( plugin.cssFromString(options.from) ); } |
use setTimeout to delay the animation, even if the delay is zero: | 1214 setTimeout(function() { |
Either add an event that starts the animation or start it right away: | |
task: Dublicate code and the delay doesn’t make much sense with an event like this. | |
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 if (options.on != ''){ $that.on( options.on, function(){ $that.animate( plugin.cssFromString(options.to), options.speed, options.easing, function(){ if (options.macro != undefined) plugin.applyMacro($that, options.macro); plugin.triggerEvent('complete', $that, options); }); }); } else { $that.animate( plugin.cssFromString(options.to), options.speed, options.easing, function(){ if (options.macro != undefined) plugin.applyMacro($el, options.macro); plugin.triggerEvent('complete', $that, options); }); } }, options.delay); } else { | |
This is a keyframe animation. Let’s first set some initial variables: | 1239 1240 1241 1242 1243 1244 options.interval = 1000 / options.fps; var frames = []; var pos = 0; var lastframe = 0; |
Loop through each keyframe and collect all the useful information we can find and parse the frame command that sets each frames options. | 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 $that.children().each( function(){ var rel = $(this).attr('rel'); var data = $(this).attr(s.dataAttribute); if (data != undefined){ var start = data.indexOf('['); var end = data.indexOf(']'); var optionstring = data.substring(start+1, end); } else { var start = rel.indexOf('['); var end = rel.indexOf(']'); var optionstring = rel.substring(start+1, end); } var frame = plugin.parseOptions(optionstring); frame.el = $(this); if (frame.easing == undefined) frame.easing = 'linear'; frame.start = pos; pos += parseInt(frame.steps); frame.end = pos; lastframe = pos; pos++; frames.push(frame); }); options.lastframe = lastframe; $that.css('overflow', 'hidden'); |
Replace the original elements content with the first frame only: | 1283 $that.html(frames[0].el); |
And now start the animation: | 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 window.setTimeout( function() { animation(frames, -1, $that, options); }, 0); } }; var animation = function(frames, current, el, options){ if ((windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus) && (el.jKit_inViewport() || !el.jKit_inViewport() && plugin.settings.ignoreViewport)){ plugin.triggerEvent('showframe showframe'+(current+1), el, options); |
Loop through each frame and run the frames action in case it matches the current frame number: | 1301 1302 $.each( frames, function(index, value){ if (value.start == current){ |
First add the new element by cloning it from the frames object and calculate the duration this frame is visible: | 1307 1308 el.html(value.el.clone()); var duration = (value.end - value.start) * options.interval; |
Depending on the action that is set for this frame, we need to start different kind of animations: | 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 if (value.action == 'fadeout'){ el.children(":first").show().fadeTo(duration, 0, value.easing); } else if (value.action == 'fadein'){ el.children(":first").hide().fadeTo(duration, 1, value.easing); } else if (value.action == 'fadeinout'){ el.children(":first").hide().fadeTo(duration/2, 1, value.easing).fadeTo(duration/2, 0, value.easing); } else if (value.action == 'tween'){ var next = frames[index+1].el; el.children(":first").animate({ 'font-size': next.css('font-size'), 'letter-spacing': next.css('letter-spacing'), 'color': next.css('color'), 'opacity': next.css('opacity'), 'background-color': next.css('background-color'), 'padding-top': next.css('padding-top'), 'padding-bottom': next.css('padding-bottom'), 'padding-left': next.css('padding-left'), 'padding-right': next.css('padding-right') }, duration, value.easing); } } }) |
Move one step forward: | 1338 1339 1340 1341 1342 1343 current++; var nextloop = false; if (current > options.lastframe){ current = 0; nextloop = true; } |
Is the animation finsihes or do we have to go to the next step? | 1347 1348 1349 if ((nextloop && options.loop == "yes") || !nextloop){ window.setTimeout( function() { animation(frames, current, el, options); }, options.interval); } |
Some additional stuff to trigger in case the animation is finished: | 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 if (options.loop == "no"){ if (options.macro != undefined) plugin.applyMacro(el, options.macro); plugin.triggerEvent('complete', el, options); } } else { window.setTimeout( function() { animation(frames, current, el, options); }, options.interval); } }; return command; }()); |
Tooltip CommandThe tooltip command displays additional information for an element on mouseover. | 1374 plugin.commands.tooltip = (function(){ |
Create an object that contains all of our data and functionality. | 1378 var command = {}; |
This are the command defaults: | 1382 1383 1384 1385 1386 1387 plugin.addCommandDefaults('tooltip', { 'text': '', 'color': '#fff', 'background': '#000', 'classname': '' }); |
The execute function is launched whenever this command is executed: | 1391 1392 1393 command.execute = function($that, options){ var s = plugin.settings; |
Create the tooltip div if it doesn’t already exist: | 1397 1398 1399 1400 1401 1402 1403 if ($('div#'+s.prefix+'-tooltip').length == 0){ $('<div/>', { id: s.prefix+'-tooltip' }).hide().appendTo('body'); } $tip = $('div#'+s.prefix+'-tooltip'); |
Display the tooltip on mouseenter: | 1407 $that.on('mouseenter', function(e){ |
Has this tooltip custom styling either by class or by supplying color values? | 1411 1412 1413 1414 1415 if (options.classname != ''){ $tip.html(options.text).removeClass().css({ 'background': '', 'color': '' }).addClass(options.classname); } else { $tip.html(options.text).removeClass().css({ 'background': options.background, 'color': options.color }); } |
Correctly position the tooltip based on the mouse position: | 1419 $tip.css('top', (e.pageY+15-$(window).scrollTop())).css('left', e.pageX); |
Fix the tooltip position so that we don’t get tooltips we can’t read because their outside the window: | 1424 1425 1426 if ( parseInt($tip.css('left')) > $(window).width() / 2 ){ $tip.css('left', '0px').css('left', e.pageX - $tip.width()); } |
Stop any possible previous animations and start fading it in: | 1430 1431 1432 $tip.stop(true, true).fadeIn(200); plugin.triggerEvent('open', $that, options); |
Fade out the tooltip on mouseleave: | 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 }).on('mouseleave click', function(e){ var speed = 200; if ($tip.is(':animated')){ speed = 0; } $tip.stop(true, true).fadeOut(speed); plugin.triggerEvent('closed', $that, options); }); }; return command; }()); |
Show CommandThe show command is used to reveal an element, animated or not. | 1461 plugin.commands.show = (function(){ |
Create an object that contains all of our data and functionality. | 1465 var command = {}; |
This are the command defaults: | 1469 1470 1471 1472 1473 1474 plugin.addCommandDefaults('show', { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 command.execute = function($that, options){ $that.hide().jKit_effect(true, options.animation, options.speed, options.easing, options.delay, function(){ plugin.triggerEvent('complete', $that, options); }); }; return command; }()); |
Swap CommandThe swap command replaces a DOM node attribute, for example an image, with another value on hover. | 1496 plugin.commands.swap = (function(){ |
Create an object that contains all of our data and functionality. | 1500 var command = {}; |
This are the command defaults: | 1504 1505 1506 1507 plugin.addCommandDefaults('swap', { 'versions': '_off,_on', 'attribute': 'src' }); |
The execute function is launched whenever this command is executed: | 1511 1512 1513 1514 1515 1516 command.execute = function($that, options){ var s = plugin.settings; var versions = options.versions.split(s.delimiter); var active = false; |
We have to store the original attributes value to swap the attribute back on mouseleave: | 1520 1521 var original = $that.attr(options.attribute); var replacement = $that.attr(options.attribute).replace(versions[0],versions[1]); |
In case the attribute is an image source, we have to preload the image or the swapping could have a delay: | 1525 1526 1527 if (options.attribute == 'src'){ $('<img/>')[0].src = replacement; } |
Finally, add the two event handlers with the swapping code: | 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 $that.on( 'mouseenter click', function(){ if (!active){ $that.attr(options.attribute, replacement ); plugin.triggerEvent('active', $that, options); active = true; } }).on( 'mouseleave click', function(){ if (active){ $that.attr(options.attribute, original ); plugin.triggerEvent('inactive', $that, options); active = false; } }); }; return command; }()); |
Limit CommandThe limit command either limts the characters of a string or the elements inside a container by a set number. | 1557 plugin.commands.limit = (function(){ |
Create an object that contains all of our data and functionality. | 1561 var command = {}; |
This are the command defaults: | 1565 1566 1567 1568 1569 1570 1571 1572 plugin.addCommandDefaults('limit', { 'elements': 'children', 'count': 5, 'animation': 'none', 'speed': 250, 'easing': 'linear', 'endstring': '...' }); |
The execute function is launched whenever this command is executed: | 1576 command.execute = function($that, options){ |
Limit the number of elements. Set speed to zero if you want to hide them immediately or use an animation: | 1581 1582 1583 1584 1585 1586 1587 1588 1589 if (options.elements == 'children'){ $that.children(':gt('+(options.count-1)+')').each(function(){ $(this).jKit_effect(false, options.animation, options.speed, options.easing); }); setTimeout( function(){ plugin.triggerEvent('complete', $that, options); }, options.speed); |
Limit the number of characters in a string: | 1593 1594 1595 } else { var newtext = $that.text().substr(0,options.count); |
Add an endstring if needed: | 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 if (newtext != $that.text()){ newtext = newtext.substr(0,newtext.length-options.endstring.length)+options.endstring; $that.text(newtext); } } }; return command; }()); |
Lorem CommandThe lorem command adds lorem ipsum text or paragraphs to your element, very usefull for “work in progress” projects. | 1618 plugin.commands.lorem = (function(){ |
Create an object that contains all of our data and functionality. | 1622 var command = {}; |
This are the command defaults: | 1626 1627 1628 1629 1630 plugin.addCommandDefaults('lorem', { 'paragraphs': 0, 'length': '', 'random': 'no' }); |
The execute function is launched whenever this command is executed: | 1634 command.execute = function($that, options){ |
The lorem ipsum text: | 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 var lorem = [ 'Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.', 'Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.', 'Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.', 'Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis.', 'At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.', 'Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.' ]; var text = ''; |
Randomize the paragraphs first? | 1652 1653 1654 if (options.random == "yes"){ lorem = $.fn.jKit_arrayShuffle(lorem); } |
Add a specific number of paragraphs: | 1658 1659 1660 1661 1662 if (options.paragraphs > 0){ for ( var i=1; i<=options.paragraphs; i++ ) { text += '<p>'+lorem[(i-1)%7]+'</p>'; } |
Or add a specific number of characters: | 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 } else { if (options.length != undefined && options.length != ''){ var i=1; while(text.length < options.length-1){ text += lorem[(i-1)%7]+' '; text = text.substring(0, options.length-1); i++; } } else { text = lorem[0]; } } $that.html(text); }; return command; }()); |
Plugin CommandThe plugin command makes it possible to add jQuery plugins that can be used the same way as jKit commands. | 1696 plugin.commands.plugin = (function(){ |
Create an object that contains all of our data and functionality. | 1700 var command = {}; |
This are the command defaults: | 1704 1705 1706 plugin.addCommandDefaults('plugin', { 'script': '' }); |
The execute function is launched whenever this command is executed: | 1710 1711 1712 command.execute = function($that, options){ var s = plugin.settings; |
First check if this is a plugin we registered on plugin init: | 1716 1717 1718 1719 1720 1721 1722 1723 1724 if (s.plugins[options.script] != undefined){ options.functioncall = s.plugins[options.script]['fn']; if (s.plugins[options.script]['option'] != undefined){ options.option = s.plugins[options.script]['option']; } options.script = s.plugins[options.script]['path']; } |
Temporarly enable ajax caching: | 1728 $.ajaxSetup({ cache: true }); |
1732 if (options.script != undefined){ | |
Load the script from the server: | 1736 $.getScript(options.script, function() { |
The plugin has loaded, now all we need to do is correctly initialize it by calling the correct function name with the correct set of parameters: | 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 if (options.option != undefined){ $that[ options.functioncall ]( options[options.option] ); } else { delete(options.type); delete(options.script); $that[ options.functioncall ]( options ); } plugin.triggerEvent('complete', $that, options); }); } |
Stop ajax caching again: | 1756 1757 1758 1759 1760 1761 1762 $.ajaxSetup({ cache: false }); }; return command; }()); |
Split CommandThe split command can take a string, for example a comma separeted one, and create new HTML elements out of the individual parts. This way a simple comma separated list can be transformed into an unordered list. | 1771 plugin.commands.split = (function(){ |
Create an object that contains all of our data and functionality. | 1775 var command = {}; |
This are the command defaults: | 1779 1780 1781 1782 1783 1784 plugin.addCommandDefaults('split', { 'separator': '', 'container': 'span', 'before': '', 'after': '' }); |
The execute function is launched whenever this command is executed: | 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 command.execute = function($that, options){ var parts = $that.text().split(options.separator); $that.html(''); $.each( parts, function(i,v){ $('<'+options.container+'/>').text(v).appendTo($that); }); $that.html(options.before+$that.html()+options.after); }; return command; }()); |
Random CommandThe random command can be used to randomly select a specific amount of elements from a collection of elements. All not selected ones will either be hidden or completely removed from the DOM. | 1812 plugin.commands.random = (function(){ |
Create an object that contains all of our data and functionality. | 1816 var command = {}; |
This are the command defaults: | 1820 1821 1822 1823 plugin.addCommandDefaults('random', { 'count': 1, 'remove': 'yes' }); |
The execute function is launched whenever this command is executed: | 1827 1828 1829 1830 command.execute = function($that, options){ var childs = $that.children().size(); var shownrs = []; |
Create an array of index numbers of our randomly selected elements: | 1834 1835 1836 1837 1838 1839 while(shownrs.length < options.count){ var shownr = Math.floor(Math.random() * childs); if ($.inArray(shownr, shownrs) == -1){ shownrs.push(shownr); } } |
Now loop through all elements and only show those we just slected: | 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 var i = 0; $that.children().each( function(){ if ($.inArray(i, shownrs) == -1){ if (options.remove == 'yes'){ $(this).remove(); } else { $(this).hide(); } } else { $(this).show(); } i++; }); }; return command; }()); |
Command TemplateThis is a template for commands. It should be used as a starting point to create new commands. | 1868 plugin.commands.api = (function(){ |
Create an object that contains all of our data and functionality. | 1872 var command = {}; |
This are the command defaults: | 1876 1877 1878 1879 1880 1881 1882 plugin.addCommandDefaults('api', { 'format': 'json', 'value': '', 'url': '', 'interval': -1, 'template': '' }); |
The execute function is launched whenever this command is executed: | 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 command.execute = function($that, options){ if (options.url != ''){ readAPI($that, options); } }; var readAPI = function($el, options){ if (options.format == 'json'){ |
Create an ajax jsonp request: | 1900 1901 1902 1903 1904 1905 1906 1907 1908 $.ajax({ type: "GET", url: options.url, contentType: "application/json; charset=utf-8", dataType: "jsonp", error: function(){ plugin.triggerEvent('error', $el, options); }, success: function(data) { |
If a template is supplied in the options, use it to display the data we just received: | 1912 if (options.template != '' && plugin.commands.template !== undefined){ |
First we add the template HTML to our element: | 1916 $el.html(plugin.commands.template.templates[options.template].template.clone().show()); |
Than we add the data to each element that has the data-jkit-api attribute: | 1920 1921 1922 1923 1924 1925 $el.find('[data-jkit-api]').each(function(){ var value = $(this).attr('data-jkit-api'); try { $(this).text(eval('data.'+value.replace(/[^a-zA-Z0-9.[]_]+/g, ''))); } catch(err) { } }); |
And lastly, we remove all elements that have the data-jkit-api-if attribute, but didn’t get a value from the API: | 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 $el.find('[data-jkit-api-if]').each(function(){ var value = $(this).attr('data-jkit-api-if'); var test = undefined; try { eval('test = data.'+value.replace(/[^a-zA-Z0-9.[]_]+/g, '')); } catch(err) { } if (test == undefined){ $(this).remove(); } }); |
In case we don’t use a template, just add the specified value as text to the element: | 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 } else { if (options.value != ''){ try { $el.text(eval('data.'+options.value.replace(/[^a-zA-Z0-9.[]_]+/g, ''))); } catch(err) { } } else { $el.text(data); } } |
Trigger some stuff now as everythimng is set up: | 1957 1958 if (options.macro != undefined) plugin.applyMacro($el, options.macro); plugin.triggerEvent('complete', $el, options); |
Do we have to read the API in a specific interval? If yes, set a timeout: | 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 if (options.interval > -1){ setTimeout( function(){ readAPI($el, options); }, options.interval*1000); } } }); } }; return command; }()); |
Replace CommandThe replace command makes it possible to replace content based on a regex pattern. It acts on the HTML level, so not only text is replacable! | 1984 plugin.commands.replace = (function(){ |
Create an object that contains all of our data and functionality. | 1988 var command = {}; |
This are the command defaults: | 1992 1993 1994 1995 1996 plugin.addCommandDefaults('replace', { 'modifier': 'g', 'search': '', 'replacement': '' }); |
The execute function is launched whenever this command is executed: | 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 command.execute = function($that, options){ var str = new RegExp(options.search, options.modifier); $that.html($that.html().replace(str,options.replacement)); }; return command; }()); |
Sort CommandThe sort command helps you convert a normal table into a sortable table by converting TH elements of a table into clickable buttons that sort the table based on the data inside the same column as the TH. | 2018 plugin.commands.sort = (function(){ |
Create an object that contains all of our data and functionality. | 2022 var command = {}; |
This are the command defaults: | 2026 2027 2028 2029 2030 2031 plugin.addCommandDefaults('sort', { 'what': 'text', 'by': '', 'start': 0, 'end': 0 }); |
The execute function is launched whenever this command is executed: | 2035 2036 2037 command.execute = function($that, options){ var s = plugin.settings; |
First we need to know the exact position of the current TH inside the heading TR, the index: | 2041 2042 2043 2044 2045 var index = $that.parent().children().index($that); $that.on('click', function(){ plugin.triggerEvent('clicked', $that, options); |
First we have to create an array with the content we need to base the sort on: | 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 var rows = []; $that.parent().parent().parent().find('tbody > tr').each( function(){ var $td = $(this).find('td:nth-child('+(index+1)+')'); switch(options.what){ case 'html': var str = $td.html(); break; case 'class': var str = $td.attr('class'); break; default: var str = $td.text(); break; } if (options.start > 0 || options.end > 0){ if (options.end > options.start){ str = str.substring(options.start, options.end); } else { str = str.substring(options.start); } } rows.push({ 'content': $(this).html(), 'search': str }); }); |
task: It should be possible to use way less code in the code below! | |
Now sort the array. There are currently three different ways to sort:
Depending on the current class of the TH, we either sort ascending or descending. | 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 if ($that.hasClass(s.prefix+'-sort-down')){ $that.parent().find('th').removeClass(s.prefix+'-sort-down').removeClass(s.prefix+'-sort-up'); $that.addClass(s.prefix+'-sort-up'); rows.sort( function(a,b){ if (options.by == 'num'){ a.search = Number(a.search); b.search = Number(b.search); } if (options.by == 'date'){ var a = new Date(a.search); var b = new Date(b.search); return (a.getTime() - b.getTime()); } else { if (a.search > b.search) return -1; if (a.search < b.search) return 1; return 0; } }); } else { $that.parent().find('th').removeClass(s.prefix+'-sort-down').removeClass(s.prefix+'-sort-up'); $that.addClass(s.prefix+'-sort-down'); rows.sort( function(a,b){ if (options.by == 'num'){ a.search = Number(a.search); b.search = Number(b.search); } if (options.by == 'date'){ var a = new Date(a.search); var b = new Date(b.search); return (b.getTime() - a.getTime()); } else { if (a.search < b.search) return -1; if (a.search > b.search) return 1; return 0; } }); } |
Everything is ready, let’s clear the whole TBODY of the table and add the sorted rows: | 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 var $body = $that.parent().parent().parent().find('tbody'); $body.html(''); var tbody = ''; $.each( rows, function(i,v){ tbody += '<tr>'+v.content+'</tr>'; }); $body.html(tbody); plugin.triggerEvent('complete', $that, options); }); }; return command; }()); |
Parallax CommandThe parallax command is used to create a parallax scrolling effect with different layers that look like a 3D scenery. Sidescrolling games in the old days used this kind of faked 3D effect quite a lot. | 2155 plugin.commands.parallax = (function(){ |
Create an object that contains all of our data and functionality. | 2159 var command = {}; |
This are the command defaults: | 2163 2164 2165 2166 2167 2168 plugin.addCommandDefaults('parallax', { 'strength': 5, 'axis': 'x', 'scope': 'global', 'detect': 'mousemove' }); |
The execute function is launched whenever this command is executed: | 2172 2173 2174 2175 2176 command.execute = function($that, options){ var s = plugin.settings; var strength = options.strength / 10; |
We have to attach our event to different DOM elements based on the the type of parallax we want. The first option will use window scrolling to set the position of each layer, the other two use the mouse position for that. | 2182 2183 2184 2185 2186 2187 2188 if (options.detect == 'scroll'){ var $capture = $(window); } else if (options.scope == 'global'){ var $capture = $(document); } else { var $capture = $that; } |
Set the correct event: | 2192 $capture.on( options.detect, function(event) { |
We only want to go through all calculations if needed, so check if our element is inside the viewport and that the window has focus: | 2197 2198 if ((windowhasfocus || !windowhasfocus && s.ignoreFocus) && ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport)){ var cnt = 1; |
Get either the scroll or the mouse position: | 2202 2203 2204 2205 2206 2207 2208 if (options.detect == 'scroll'){ var xaxis = $(window).scrollLeft() + $(window).width() / 2; var yaxis = $(window).scrollTop() + $(window).height() / 2; } else { var xaxis = event.pageX; var yaxis = event.pageY; } |
Loop through each layer and set the correct positions of each one of them: | 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 $that.children().each( function(){ var box = $that.offset(); if (options.axis == 'x' || options.axis == 'both'){ var offsetx = (xaxis-box.left-($that.width()/2))*strength*cnt*-1 - $(this).width()/2 + $that.width()/2; $(this).css({ 'left': offsetx+'px' }); } if (options.axis == 'y' || options.axis == 'both'){ var offsety = (yaxis-box.top-($that.height()/2))*strength*cnt*-1 - $(this).height()/2 + $that.height()/2; $(this).css({ 'top': offsety+'px' }); } cnt++; }); } }); }; return command; }()); |
Zoom CommandThe zoom command makes it possible to zoom into images on mouseover. To do that it overlays the selected image with a div that has that image as its background. | 2244 plugin.commands.zoom = (function(){ |
Create an object that contains all of our data and functionality. | 2248 var command = {}; |
This are the command defaults: | 2252 2253 2254 2255 2256 plugin.addCommandDefaults('zoom', { 'scale': 2, 'speed': 150, 'lightbox': 'no' }); |
The execute function is launched whenever this command is executed: | 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 command.execute = function($that, options){ var s = plugin.settings; var type = 'zoom'; $that.parent().css('position', 'relative'); $that.on( 'mouseover', function(){ var pos = $that.position(); var height = $that.height(); var width = $that.width(); $zoom = $('<div/>', { 'class': s.prefix+'-'+type+'-overlay' }).css( { 'position': 'absolute', 'height': height+'px', 'width': width+'px', 'left': pos.left + 'px', 'top': pos.top + 'px', 'overflow': 'hidden', 'background-image': 'url('+$that.attr('src')+')', 'background-repeat': 'no-repeat', 'background-color': '#000', 'opacity': 0 }).on( 'mouseout', function(){ $zoom.fadeTo(options.speed, 0, function(){ $zoom.remove(); plugin.triggerEvent('zoomout', $that, options); }); }).mousemove(function(e){ |
Detect the mouse poition relative to the selected image: | 2295 2296 2297 2298 var offset = $(this).offset(); var x = (e.pageX - offset.left) * (options.scale-1); var y = (e.pageY - offset.top) * (options.scale-1); |
And than move the background image of the overlayed div: | 2302 2303 2304 2305 2306 $zoom.css('background-position', '-'+x+'px -'+y+'px'); }).fadeTo(options.speed, 1, function(){ plugin.triggerEvent('zoomin', $that, options); }).insertAfter($that); |
Optionally add a lightbox to the overlay image: | 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 if (options.lightbox == 'yes'){ plugin.executeCommand($zoom, 'lightbox', {}); } }); }; return command; }()); |
Partially CommandThe partially command let’s us display an element only partially in case it is bigger than our supplied maximum height. The whole height is shown only on specific user action (hover over element or click of the down key) | 2329 plugin.commands.partially = (function(){ |
Create an object that contains all of our data and functionality. | 2333 var command = {}; |
This are the command defaults: | 2337 2338 2339 2340 2341 2342 2343 plugin.addCommandDefaults('partially', { 'height': 200, 'text': 'more ...', 'speed': 250, 'easing': 'linear', 'on': 'mouseover' }); |
The execute function is launched whenever this command is executed: | 2347 2348 2349 command.execute = function($that, options){ var s = plugin.settings; |
First store the original height, we need it later. | 2353 var originalHeight = $that.height(); |
Only add the magic is we need, in other words, if the lement is higher than our maximum height: | 2357 if (originalHeight > options.height){ |
We can only add our more div if it’s relatively positioned, so force that one on it: | 2361 $that.css('position', 'relative'); |
Create the more div: | 2365 2366 2367 2368 2369 var $morediv = $('<div/>') .addClass(s.prefix+'-morediv') .appendTo($that) .html(options.text) .css( { width: $that.outerWidth()+'px', opacity: 0.9 }); |
Add the event handlers and animations: | 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 plugin.addKeypressEvents($that, 'down'); plugin.addKeypressEvents($that, 'up'); if (options.on == 'click' || $.fn.jKit_iOS()){ var openEvent = 'click'; var closeEvent = 'click'; } else { var openEvent = 'mouseenter'; var closeEvent = 'mouseleave'; } $that.css({ 'height': options.height+'px', 'overflow': 'hidden' }).on( openEvent+' down', function() { if ($that.height() < originalHeight){ $morediv.fadeTo(options.speed, 0); $that.animate({ 'height': originalHeight+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('open', $that, options); }); } }).on( closeEvent+' up', function(){ if ($that.height() == originalHeight){ $morediv.fadeTo(options.speed, 0.9); $that.animate({ 'height': options.height+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('closed', $that, options); }); } }); } }; return command; }()); |
Showandhide CommandThe showandhide command is used to reveal an element and than hide it again, animated or not. | 2414 plugin.commands.showandhide = (function(){ |
Create an object that contains all of our data and functionality. | 2418 var command = {}; |
This are the command defaults: | 2422 2423 2424 2425 2426 2427 2428 plugin.addCommandDefaults('showandhide', { 'delay': 0, 'speed': 500, 'duration': 10000, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 command.execute = function($that, options){ $that.hide().jKit_effect(true, options.animation, options.speed, options.easing, options.delay, function(){ plugin.triggerEvent('shown', $that, options); $that.jKit_effect(false, options.animation, options.speed, options.easing, options.duration, function(){ plugin.triggerEvent('complete', $that, options); }); }); }; return command; }()); |
Filter CommandThe filter command lets you filter DOM nodes based on some input. | 2452 plugin.commands.filter = (function(){ |
Create an object that contains all of our data and functionality. | 2456 var command = {}; |
This are the command defaults: | 2460 2461 2462 2463 2464 2465 2466 2467 2468 plugin.addCommandDefaults('filter', { 'by': 'class', 'affected': '', 'animation': 'slide', 'speed': 250, 'easing': 'linear', 'logic': 'and', 'global': 'no' }); |
The execute function is launched whenever this command is executed: | 2472 command.execute = function($that, options){ |
The filter has to run on init and after every change of elements that have the jkit-filter class, so we have our own function we can call on all those events, the filterElements function, and let that function do all the hard work. | 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 $that.find('.jkit-filter').each( function(){ $(this) .data('oldval', $.trim( $(this).val() ) ) .on( 'change click input', function(){ if ( $.trim( $(this).val() ) != $(this).data('oldval') ){ $(this).data('oldval', $.trim( $(this).val() ) ); if (options.loader !== undefined) $(options.loader).show(); plugin.triggerEvent('clicked', $that, options); filterElements($that, options); } }); }); |
In case there’s already a filter value set, we need to trigger the filtering right now: | 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 $that.find('.jkit-filter').each( function(){ if ($.trim($(this).val()) != ''){ if (options.loader !== undefined) $(options.loader).show(); plugin.triggerEvent('clicked', $that, options); filterElements($that, options); return false; } }); }; |
The filterElements function is used by the filter command. It’s doing the heavy lifting for the command. | 2514 var filterElements = function($el, options){ |
First we need to go through each filter element to find out by what we have to filter the affected elemnts. We’re splitting each elements value to get the separate words into an array. | 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 var selections = []; $el.find('.jkit-filter').each( function(){ var vals = []; var valsplit = $(this).val().split(' '); $.each( valsplit, function(i,v){ v = $.trim(v); if (v != '') vals.push(v); }); selections = selections.concat(vals); }); |
Where do we have to look for our affected DOM nodes? Inside the body or inside the current element? | 2533 2534 2535 2536 2537 if (options.global == 'yes'){ $container = $('body'); } else { $container = $el; } |
Loop through all affected elements and check if they have to be displayed or not. | 2541 $container.find(options.affected).each( function(){ |
First create a few cashes to speed up the following loop through the filter selections: | 2545 2546 2547 2548 2549 2550 2551 var $current = $(this); if (options.by == 'text'){ var currentText = $current.text().toLowerCase(); } if (selections.length > 0){ |
As we have two options, one where we need to find each selection and one where we only have to find one of the selections, we first have to create an array with all found selections: | 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 var found = []; $.each( selections, function(i,v){ if (options.by == 'class'){ if ($current.hasClass(v)){ found.push(v); } } else if (options.by == 'text'){ if (currentText.indexOf(v.toLowerCase()) > -1){ found.push(v); } } }); |
Hide or show the element based on our search result: | 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 if ( found.length == selections.length || (found.length > 0 && options.logic == 'or') ){ $current.jKit_effect(true, options.animation, options.speed, options.easing, 0); } else { $current.jKit_effect(false, options.animation, options.speed, options.easing, 0); } } else { $current.jKit_effect(true, options.animation, options.speed, options.easing, 0); } }); |
Fire the complete event at the right time and hide the optional loader animation: | 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 setTimeout( function(){ if (options.loader !== undefined) $(options.loader).hide(); plugin.triggerEvent('complete', $el, options); }, options.speed); }; return command; }()); |
Slideshow CommandThe slideshow command is being used to create slideshows of either images or any other kind of HTML content. | 2604 plugin.commands.slideshow = (function(){ |
Create an object that contains all of our data and functionality. | 2608 var command = {}; |
This are the command defaults: | 2612 2613 2614 2615 2616 2617 2618 2619 plugin.addCommandDefaults('slideshow', { 'shuffle': 'no', 'interval': 3000, 'speed': 250, 'animation': 'fade', 'easing': 'linear', 'on': '' }); |
The execute function is launched whenever this command is executed: | 2623 command.execute = function($that, options){ |
Get all slides: | 2627 var slides = $that.children(); |
If needed, shuffle the slides into a random order: | 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 if (options.shuffle == 'yes'){ var tmp, rand; var slidecount = slides.length; for(var i =0; i < slidecount; i++){ rand = Math.floor(Math.random() * slidecount); tmp = slides[i]; slides[i] = slides[rand]; slides[rand] = tmp; } } $that.css( { 'position': 'relative' } ); |
Add the first slide and set a hidden data attribute so we know if the slideshow is running or not. | 2647 2648 2649 2650 $that.html(slides[0]); $.data($that, 'anim', false); if (options.on != ''){ |
In case the on option is set to mouseover, we have to set an additional mouseleave event. | 2655 2656 2657 2658 2659 if (options.on == 'mouseover'){ $that.on( 'mouseleave', function(){ $.data($that, 'anim', false); }); } |
Set the correct events and use a setTimeout function to call the slideshow function: | 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 $that.on( options.on, function(){ if (options.on == 'click'){ if ($.data($that, 'anim')){ $.data($that, 'anim', false); } else { $.data($that, 'anim', true); window.setTimeout( function() { slideshow(slides, 0, $that, options); }, 0); } } else if (options.on == 'mouseover'){ if (!$.data($that, 'anim')){ $.data($that, 'anim', true); window.setTimeout( function() { slideshow(slides, 0, $that, options); }, 0); } } }); } else { |
No event is set, so we just run the slideshow right now: | 2683 2684 2685 2686 2687 2688 $.data($that, 'anim', true); window.setTimeout( function() { slideshow(slides, 0, $that, options); }, options.interval); } }; |
The slideshow function replaces one slide with the next one. This one is is really simple, so not much to comment, just that the old element is first being hidden and than the new one shown, with or whitout an animation. | 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 var slideshow = function(slides, current, el, options){ if ($.data(el, 'anim')){ if ((windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus) && (el.jKit_inViewport() || !el.jKit_inViewport() && plugin.settings.ignoreViewport)){ if (current < (slides.length-1)){ current++; } else { current = 0; } plugin.triggerEvent('hideentry hideentry'+(current+1), el, options); el.jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ el.html(slides[current]); plugin.triggerEvent('showentry showentry'+(current+1), el, options); el.jKit_effect(true, options.animation, options.speed, options.easing, 0, function(){ window.setTimeout( function() { slideshow(slides, current, el, options); }, options.interval); }); }); } else { window.setTimeout( function() { slideshow(slides, current, el, options); }, options.interval); } } }; return command; }()); |
Cycle CommandThe cycle command let’s you “cycle” through a sequence of values and apply them to a set of DOM nodes. This can be classes, html, attributes or css. | 2734 plugin.commands.cycle = (function(){ |
Create an object that contains all of our data and functionality. | 2738 var command = {}; |
This are the command defaults: | 2742 2743 2744 2745 2746 2747 plugin.addCommandDefaults('cycle', { 'what': 'class', 'where': 'li', 'scope': 'children', 'sequence': 'odd,even' }); |
The execute function is launched whenever this command is executed: | 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 command.execute = function($that, options){ var s = plugin.settings; var seq = options.sequence.split(s.delimiter); var pos = 0; var sel = options.where; if (options.scope == 'children'){ sel = '> '+sel; } $that.find(sel).each( function(){ if (seq[pos] != undefined && seq[pos] != ''){ switch(options.what){ case 'class': $(this).addClass(seq[pos]); break; case 'html': $(this).html(seq[pos]); break; default: |
If it’s not a class or html, it has to be a dot separated combination like for exmaple css.color or attr.id, so split it: | 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 var what = options.what.split('.'); if (what[0] == 'attr'){ $(this).attr(what[1], seq[pos]); } else if (what[0] == 'css'){ $(this).css(what[1], seq[pos]); } } } pos++; if (pos > seq.length-1) pos = 0; }); }; return command; }()); |
Binding CommandThe binding command lets you bind different kind of values and even functions to different things, for example attributes. It’s a very powerfull command with tons of options. | 2802 plugin.commands.binding = (function(){ |
Create an object that contains all of our data and functionality. | 2806 var command = {}; |
This are the command defaults: | 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 plugin.addCommandDefaults('binding', { 'selector': '', 'source': 'val', 'variable': '', 'mode': 'text', 'interval': 100, 'math': '', 'condition': '', 'if': '', 'else': '', 'speed': 0, 'easing': 'linear', 'search': '', 'trigger': 'no', 'accuracy': '', 'min': '', 'max': '' }); |
The execute function is launched whenever this command is executed: | 2831 2832 2833 2834 2835 command.execute = function($that, options){ window.setTimeout( function() { binding($that, options); }, 0); }; |
The binding function connects different things to other things. It’s a really powerfull function with many options. | 2840 var binding = function(el, options){ |
Only run the code if the window has focus: | 2844 if (windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus){ |
First we need to get our value or multiple values that we later convert into one. Only run the following code if we didn’t bind to a function already. | 2849 if (options.value == undefined){ |
If the selector option is set, we don’t use a variable for our source, that means we have to get our variable from the selector element: | 2854 if (options.selector != ''){ |
The selector can have multiple elements that we have to check. And the source option can be separated with a dot, so prepare those two things first: | 2859 2860 var selsplit = options.selector.split('|'); var sourcesplit = options.source.split('.'); |
Now create an array that holds one or all of our values and run through each selector: | 2864 2865 var values = []; $.each(selsplit, function(i, v) { |
The selector is either a jQuery selector string or “this” that references the current element or “parent” that references the parent of the current element. | 2870 2871 2872 2873 2874 if (v == 'this'){ v = el; } else if (v == 'parent'){ v = $(el).parent().get(0); } |
A jQuery selector string can match more than one string, so run through all of them: | 2878 $(v).each( function(){ |
The source option defines from where exactly we get our value. There are quite a few options. | 2883 switch(sourcesplit[0]){ |
We can trigger this binding by an event. This will simply call this function again as soon as the event fires with the value set to 1. | 2888 2889 2890 2891 2892 2893 2894 2895 2896 case 'event': $(this).on( sourcesplit[1], function(e){ options.value = 1; binding(el, options); if (options.macro != undefined) plugin.applyMacro($(el), options.macro); }); break; |
“html” will get the HTML of the element: | 2900 2901 2902 2903 2904 case 'html': var temp = $(this).html(); break; |
“text” will get the putre text of the element: | 2908 2909 2910 2911 2912 case 'text': var temp = $(this).text(); break; |
“attr” will get a specific attribute that is specified after the dot, for example attr.id: | 2917 2918 2919 2920 2921 case 'attr': var temp = $(this).attr(sourcesplit[1]); break; |
“css” will get a specific css value that is specified after the dot, for example css.width. Many of the options will be calculated by jQuery so that we get the correct result in any browser. | 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 case 'css': if (sourcesplit[1] == 'height'){ var temp = $(this).height(); } else if (sourcesplit[1] == 'innerHeight'){ var temp = $(this).innerHeight(); } else if (sourcesplit[1] == 'outerHeight'){ var temp = $(this).outerHeight(); } else if (sourcesplit[1] == 'width'){ var temp = $(this).width(); } else if (sourcesplit[1] == 'innerWidth'){ var temp = $(this).innerWidth(); } else if (sourcesplit[1] == 'outerWidth'){ var temp = $(this).outerWidth(); } else if (sourcesplit[1] == 'scrollTop'){ var temp = $(this).scrollTop(); } else if (sourcesplit[1] == 'scrollLeft'){ var temp = $(this).scrollLeft(); } else { var temp = $(this).css(sourcesplit[1]); } break; |
“scroll” will get the page scroll offset, either from top or from the left side: | 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 case 'scroll': switch(sourcesplit[1]){ case 'top': var temp = $(window).scrollTop(); break; case 'left': var temp = $(window).scrollLeft(); break; } break; |
“clearance” will calculate the clearence around an element in relation to the window. If nothing is supplied after the dot, each side will be checked. | 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 case 'clearance': var cTop = el.offset().top-$(window).scrollTop(); var cBottom = $(window).scrollTop() + $(window).height() - ( el.offset().top + el.height() ); var cRight = ($(window).width() + $(window).scrollLeft()) - (el.offset().left + el.width()); var cLeft = el.offset().left - $(window).scrollLeft(); switch(sourcesplit[1]){ case 'bottom': var temp = cBottom; break; case 'top': var temp = cTop; break; case 'right': var temp = cRight; break; case 'left': var temp = cLeft; break; default: var temp = Math.min.apply(Math, [ cBottom, cTop, cRight, cLeft ]); } break; |
“has” tries to find out if the element has a specific thing and gives back either true or false: | 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 case 'has': switch(sourcesplit[1]){ case 'class': var temp = $(this).hasClass(options.search); break; case 'text': var temp = $.fn.jKit_stringOccurrences($(this).text().toLowerCase(), options.search.toLowerCase()); break; case 'attribute': var temp = ($(this).attr(options.search) !== undefined); break; case 'val': var temp = $.fn.jKit_stringOccurrences($(this).val().toLowerCase(), options.search.toLowerCase()); break; case 'element': var temp = $(this).find(options.search).length; break; case 'children': var temp = $(this).children(options.search).length; break; case 'hash': var temp = (window.location.hash == options.search); break; } break; |
“location” needs the second option after the dot and gets something from the location object, for example the hash, like this: location.hash | 3029 3030 3031 3032 3033 case 'location': var temp = window.location[sourcesplit[1]]; break; |
“val” will get the value of the element: | 3037 3038 3039 3040 3041 3042 3043 3044 3045 case 'val': default: var temp = $(this).val(); } values.push(temp); }); }); |
If there’s a third option supplied with the source, for example css.height.max, we use that to calculate the final valus from all values in the array. If the fird option isn’t supplied, we just take the first value. | 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 if (sourcesplit[2] != undefined){ var value = ''; switch(sourcesplit[2]){ case 'max': value = Math.max.apply(Math, values); break; case 'min': value = Math.min.apply(Math, values); break; case 'sum': value = values.reduce(function(a,b){return a+b;}); break; case 'avg': value = values.reduce(function(a,b){return a+b;}) / values.length; break; } } else { var value = values[0]; } } else if (options.variable != ''){ var value = window[options.variable]; } } else { value = options.value; } |
In case we have a numeric value, there are a few options more we can apply. The accuracy option reduces the accuracy of the value down to this number. The min and max options limit the value to either a minimum or a maximum value. | 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 if (!isNaN(value) && parseInt(value) == value){ if (options.accuracy != ''){ value = Math.round(value / options.accuracy) * options.accuracy; } if (options.min != '' && value < options.min){ value = options.min; } if (options.max != '' && value > options.max){ value = options.max; } } |
If the condition option is set or the current value is a boolean, we have to decide if either the if option will be used (if supllied) or the value in the else option (if supllied). | 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 var doit; var rev = false; if (options.condition != ''){ doit = false; eval('if ('+options.condition.replace(/[^a-zA-Z 0-9#<>=.!']+/g, '')+') doit = true;'); } else { if (value === false){ doit = false; rev = true; } else { doit = true; } } |
Next we add some logic that either fires the true or false event in case our value changes. To make this possible, we store the value in the “global” commandkeys array entry for the current command call. | 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 if (commandkeys[options.commandkey]['condition'] == undefined || commandkeys[options.commandkey]['condition'] != doit){ if (doit){ plugin.triggerEvent('true', $(el), options); } else { plugin.triggerEvent('false', $(el), options); } commandkeys[options.commandkey]['condition'] = doit; } if (rev){ doit = true; } |
Use the if or else value if supplied: | 3140 3141 3142 3143 3144 3145 3146 if (!doit && options['else'] != ''){ doit = true; value = options['else']; } else if (doit && options['if'] != ''){ doit = true; value = options['if']; } |
Time to use the value to set something, but only if the condition wasn’t false: | 3150 if (doit){ |
The math option lets us do some additional calculation on our value: | 3154 3155 3156 if (options.math != ''){ eval('value = '+options.math.replace(/[^a-zA-Z 0-9+-*/.]+/g, '')+';'); } |
Do we have to trigger some additional events? | 3160 3161 3162 3163 3164 3165 3166 3167 3168 if (options.trigger == 'yes'){ if (commandkeys[options.commandkey]['triggervalue'] == undefined || commandkeys[options.commandkey]['triggervalue'] != value){ if (commandkeys[options.commandkey]['triggervalue'] !== undefined){ plugin.triggerEvent('notvalue'+commandkeys[options.commandkey]['triggervalue'], $(el), options); } plugin.triggerEvent('value'+value, $(el), options); commandkeys[options.commandkey]['triggervalue'] = value; } } |
The mode option defines what we have to do with our value. There are quite a few options. The attr and css modes take a second option that is separated with a dot. | 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 var modesplit = options.mode.split('.'); switch(modesplit[0]){ case 'text': el.text(value); break; case 'html': el.html(value); break; case 'val': el.val(value); break; case 'attr': el.attr(modesplit[1], value); break; case 'css': if (modesplit[1] == 'display'){ if ($.trim(value) == '' || $.trim(value) == 0 || !value){ value = 'none'; } else { if (modesplit[2] !== undefined){ value = modesplit[2]; } } } |
CSS values can be animated if needed: | 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 if (options.speed > 0){ var style = {}; style[modesplit[1]] = value; el.animate(style, options.speed, options.easing); } else { el.css(modesplit[1], value); } break; case 'none': break; default: |
The default behavior is to call a custom function if one exits with that name: | 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 if (modesplit[0] != undefined){ var fn = window[modesplit[0]]; if(typeof fn === 'function') { fn(value,el); } } } } } |
Do we have to set an interval? | 3227 3228 3229 3230 3231 3232 3233 3234 3235 if (options.interval != -1){ window.setTimeout( function() { binding(el, options); }, options.interval); } }; return command; }()); |
Accordion CommandThe accordion command creates a content navigation that acts like an accordion. | 3243 plugin.commands.accordion = (function(){ |
Create an object that contains all of our data and functionality. | 3247 var command = {}; |
This are the command defaults: | 3251 3252 3253 3254 3255 3256 plugin.addCommandDefaults('accordion', { 'active': 1, 'animation': 'slide', 'speed': 250, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3260 3261 3262 command.execute = function($that, options){ var s = plugin.settings; |
First try to find out which kind of HTML elements are used to structure the data: | 3266 3267 3268 var containerTag = plugin.findElementTag($that, '>', 'max', 'div'); var titleTag = plugin.findElementTag($that, '> '+containerTag+' >', 0, 'h3'); var contentTag = plugin.findElementTag($that, '> '+containerTag+' >', 1, 'div'); |
Next we need to create an array that contains all the titles and content (yes, this is so similar to the tabs command, that even the array is called “tabs”): | |
task: Can we save code if we combine this one and the tab command? They are very similar! | |
3275 3276 3277 3278 3279 3280 3281 var tabs = []; $that.children(containerTag).each( function(){ tabs.push({ 'title': $(this).children(titleTag).detach(), 'content': $(this).children(contentTag).detach() }); }); | |
Prepare the original element so that we can add the navigation: | 3285 3286 3287 3288 3289 $that.html(''); var $tabnav = $('<ul/>', { }).appendTo($that); var current = 1; if (options.active == 0) current = -1; |
Loop through each element and create the correct data structure with all events and animations: | 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 $.each( tabs, function(index, value){ var $litemp = $('<li/>', { }).append(value.title).css('cursor', 'pointer').appendTo($tabnav); if (options.active-1 == index){ $litemp.append(value.content).children(titleTag).addClass(s.activeClass); current = index; } else { $litemp.append(value.content.hide()); } $litemp.find('> '+titleTag).on( 'click', function(e){ if (index != current){ plugin.triggerEvent('showentry showentry'+(index+1), $that, options); $tabnav.find('> li > '+titleTag).removeClass(s.activeClass); $(this).addClass(s.activeClass); if (options.animation == 'slide'){ $tabnav.find('> li:nth-child('+(current+1)+') > '+contentTag).slideUp(options.speed, options.easing); $tabnav.find('> li:nth-child('+(index+1)+') > '+contentTag).slideDown(options.speed, options.easing); } else { $tabnav.find('> li:nth-child('+(current+1)+') > '+contentTag).hide(); $tabnav.find('> li:nth-child('+(index+1)+') > '+contentTag).show(); } current = index; } else { plugin.triggerEvent('hideentry hideentry'+(index+1), $that, options); $(this).removeClass(s.activeClass).next().slideUp(options.speed, options.easing); current = -1; } }); }); }; |
Add local functions and variables here … | 3330 3331 3332 return command; }()); |
Template CommandThe template command implements a simple templating engine. | 3340 plugin.commands.template = (function(){ |
Create an object that contains all of our data and functionality. | 3344 3345 3346 var command = {}; command.templates = {}; |
This are the command defaults: | 3350 3351 3352 3353 3354 3355 plugin.addCommandDefaults('template', { 'action': 'set', 'name': 'template', 'dynamic': 'no', 'addhtml': '+' }); |
The execute function is launched whenever this command is executed: | 3359 3360 3361 command.execute = function($that, options){ var s = plugin.settings; |
Apply a template or define a new one? | 3365 3366 3367 if (options.action == 'apply'){ $el = $that; |
Do we have to apply the template to more than one element? | 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 if (options.children != undefined && options.children != ''){ $el = $that.children(options.children); var cnt = 0; $el.each( function(){ cnt++; applyTemplate($(this), options, cnt, $el.length); }); } else { applyTemplate($that, options); } |
If this is a dynamic template, we need to create the add div that acts like a button and adds a new element with the correct options: | 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 if (options.dynamic == 'yes'){ var $addDiv = $('<a/>', { 'class': s.prefix+'-'+type+'-add' }).html(options.addhtml).on( 'click', function(){ $el = $($that.get(0)); var cnt = $el.children(options.children).length + 1; $el.find('.if-entry-last').hide(); applyTemplate($('<'+options.children+'/>').appendTo($el), options, cnt, cnt); plugin.triggerEvent('added', $that, options); }).insertAfter($that); } } else { |
Templates are stored in a “global” plugin array: | 3409 3410 3411 if (command.templates[options.name] == undefined){ command.templates[options.name] = []; } |
Define the dynamic variables: | 3415 3416 3417 3418 3419 if (options.vars == undefined){ var vars = []; } else { var vars = options.vars.split(s.delimiter); } |
Add the template to the “global” array: | 3423 3424 3425 3426 3427 command.templates[options.name] = { 'template': $that.detach(), 'vars': vars }; } }; |
applyTemplateThe applyTemplate function is used by the template command. It adds the template with all it’s options to the suoplied element. | 3434 var applyTemplate = function($el, options, cnt, entries){ |
Loop through each template variable, find the correct element inside the supplied content element, init each of the elements in case there are any jKit commands on them and finally store the value or HTML in an array. | 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 var content = {}; $.each( command.templates[options.name].vars, function(i,v){ var $subEls = $el.find('.'+v); plugin.init($subEls); if ($subEls.val() != ''){ content[v] = $subEls.val(); } else { content[v] = $subEls.html(); } }); |
Now add the template to the container element: | 3453 $el.html(command.templates[options.name].template.clone().show()); |
Hide all elements that have an if-entry-x class. We later show them again if needed. | 3457 $el.find('[class^="if-entry-"]').hide(); |
Rename dynamic attributes so that we don’t get dublicate ids: | 3461 renameDynamicAttributes($el, cnt); |
Add the content and show hidden elements if needed: | 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 $.each( command.templates[options.name].vars, function(i,v){ var $subEl = $el.find('.'+v); if ($subEl.is("input") || $subEl.is("select") || $subEl.is("textarea")){ $subEl.val(content[v]); } else { $subEl.html(content[v]); } if (content[v] == undefined && $el.find('.if-'+v).length > 0){ $el.find('.if-'+v).remove(); } if (cnt == 1) $el.find('.if-entry-first').show(); if (cnt == entries) $el.find('.if-entry-last').show(); $el.find('.if-entry-nr-'+cnt).show(); }); }; |
renameDynamicAttributesThe renameDynamicAttributes function is used by the plugin.applyTemplate function. It’s used to rename attributes on dynamic elements so that we get unique elements. | 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 var renameDynamicAttributes = function($el, cnt){ $el.find('[class^="dynamic-"]').each( function(){ var $subEl = $(this); var classList = $(this).attr('class').split(/s+/); $.each( classList, function(i,v){ var attribute = v.substr(8); if (attribute != '' && $subEl.attr(attribute)){ var currentAttr = $subEl.attr(attribute); var pos = currentAttr.lastIndexOf('_'); if (pos > -1){ currentAttr = currentAttr.substr(0,pos); } $subEl.attr(attribute, currentAttr+'_'+cnt); } }); }); }; return command; }()); |
Tabs CommandThe tabs command is used to create a tab navigation of different content elements. | 3530 plugin.commands.tabs = (function(){ |
Create an object that contains all of our data and functionality. | 3534 var command = {}; |
This are the command defaults: | 3538 3539 3540 3541 3542 3543 plugin.addCommandDefaults('tabs', { 'active': 1, 'animation': 'none', 'speed': 250, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3547 3548 3549 command.execute = function($that, options){ var s = plugin.settings; |
First try to find out which kind of HTML elements are used to structure the data: | 3553 3554 3555 var containerTag = plugin.findElementTag($that, '>', 'max', 'div'); var titleTag = plugin.findElementTag($that, '> '+containerTag+' >', 0, 'h3'); var contentTag = plugin.findElementTag($that, '> '+containerTag+' >', 1, 'div'); |
Next we need to create an array the contains all the tab titles and content: | 3559 3560 3561 3562 var tabs = []; $that.children(containerTag).each( function(){ tabs.push({ 'title': $(this).children(titleTag).html(), 'content': $(this).children(contentTag).detach() }); }); |
Prepare the original element so that we can add the navigation: | 3566 3567 $that.html(''); var $tabnav = $('<ul/>', { }).appendTo($that); |
We need a jQuery element right now but can only set it after the following loop has finished: | 3571 3572 3573 var $tabcontent = $; $.each( tabs, function(index, value){ |
Create a list element and add it to the tab naviagtion: | 3577 var $litemp = $('<li/>', { }).html(value.title).css('cursor', 'pointer').appendTo($tabnav); |
Is this tab active? If yes, add the “active” class: | 3581 3582 3583 if (options.active-1 == index){ $litemp.addClass(s.activeClass); } |
Create a callback for each list and fire it on the click event: | |
task: Was there a reason for this callback variable? Can’t we just use an anonymos function inside the event? | |
3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 var callback = function(){ plugin.triggerEvent('showentry showentry'+(index+1), $that, options); $tabcontent.jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ $(this).remove(); $tabcontent = tabs[index].content.appendTo($that).hide(); $tabcontent.jKit_effect(true, options.animation, options.speed, options.easing); }); $tabnav.find('li').removeClass(s.activeClass); $tabnav.find('li:nth-child('+(index+1)+')').addClass(s.activeClass); }; $litemp.on( 'click ', function(){ callback(); }); }); | |
Do we have to display an initial content or do we start without a tab selected? | 3610 3611 3612 3613 3614 if (tabs[options.active-1] != undefined){ $tabcontent = tabs[options.active-1].content.appendTo($that); } }; |
Add local functions and variables here … | 3618 3619 3620 return command; }()); |
Key CommandThe key command let’s us create hotkeys for links. If thge link has an onclick attribute, we fire that one, if not, we’re just going to open the href, either as a popup or inside the same window, whatever the target attribute tells us. | 3630 plugin.commands.key = (function(){ |
Create an object that contains all of our data and functionality. | 3634 var command = {}; |
This are the command defaults: | 3638 plugin.addCommandDefaults('key', {}); |
The execute function is launched whenever this command is executed: | 3642 3643 3644 command.execute = function($that, options){ if (options.code != undefined){ |
First we need to add the event handling for this keycode to the element … | 3648 plugin.addKeypressEvents($that, options.code); |
Because only now we can listen to it: | 3652 3653 3654 3655 3656 $that.on( options.code, function(){ if ($that.attr('onclick') !== undefined){ $that.click(); } else { if ($that.attr('target') !== undefined && $that.attr('target') == '_blank'){ |
Sadly we can’t open pages in a new tab or regular window, so we have to open it in a popup instead: | 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 window.open($that.attr('href'), '_blank', false); } else { window.location.href = $that.attr('href'); } } if (options.macro != undefined) plugin.applyMacro($that, options.macro); plugin.triggerEvent('pressed', $that, options); }); } }; return command; }()); |
Scroll CommandThe scroll command let’s us scroll smoothly to an anchor on the page or if the HREF attribute is empty, we just scroll to the top. | 3683 plugin.commands.scroll = (function(){ |
Create an object that contains all of our data and functionality. | 3687 var command = {}; |
This are the command defaults: | 3691 3692 3693 3694 3695 plugin.addCommandDefaults('scroll', { 'speed': 500, 'dynamic': 'yes', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3699 3700 3701 3702 3703 command.execute = function($that, options){ $that.click(function() { plugin.triggerEvent('clicked', $that, options); |
Get the position of our target element: | 3707 3708 3709 3710 3711 if ($(this).attr("href") == ''){ var ypos = 0; } else { var ypos = $($that.attr("href")).offset().top; } |
The dynamic option changes the scroll animation duration based on the distance between us and the target element: | 3716 3717 3718 if (options.dynamic == 'yes'){ options.speed = Math.abs($(document).scrollTop() - ypos) / 1000 * options.speed; } |
Finally animate the scrollTop of the whole HTML page to scroll inside the current window: | 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 $('html, body').animate({ scrollTop: ypos+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('complete', $that, options); }); return false; }); }; return command; }()); |
Form CommandThe form command can convert a regular web form into an ajax submitted form. Additionally it adds various validation options. | 3742 plugin.commands.form = (function(){ |
Create an object that contains all of our data and functionality. | 3746 var command = {}; |
This are the command defaults: | 3750 3751 3752 plugin.addCommandDefaults('form', { 'validateonly': 'no' }); |
The execute function is launched whenever this command is executed: | 3756 3757 3758 command.execute = function($that, options){ var s = plugin.settings; |
Add a hidden field that will contain a list of required fileds so that our PHP script can check against them. | 3763 3764 3765 3766 3767 $that.append('<input type="hidden" name="'+s.prefix+'-requireds" id="'+s.prefix+'-requireds">'); if (options.error != undefined) options.formerror = options.error; var requireds = []; |
Add an on submit event so that we can do our work before the form is being submitted: | 3771 $that.on('submit', function() { |
Create an error array and remove all error nodes previously set: | 3775 3776 var errors = []; $(this).find('span.'+s.errorClass).remove(); |
Parse the validation commands: | |
task: Can’t we use the default parsing here so that we save code and get all features? | |
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 $(this).find("*[rel^=jKit], *["+s.dataAttribute+"]").each( function(){ var rel = $(this).attr('rel'); var data = $(this).attr(s.dataAttribute); if (data != undefined){ var start = data.indexOf('['); var end = data.indexOf(']'); var optionstring = data.substring(start+1, end); } else { var start = rel.indexOf('['); var end = rel.indexOf(']'); var optionstring = rel.substring(start+1, end); } var options = plugin.parseOptions(optionstring); var type = options.type; var elerror = false; var required = false; if (options.required == undefined) options.required = false; | |
Check if this form element is required and if yes, check if there is something entered: | 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 if (options.required == 'true'){ if ($(this).val() == ''){ elerror = true; errors.push( { 'element': $(this), 'error': 'required' } ); } required = true; if ($.inArray($(this).attr('name'), requireds) == -1){ requireds.push($(this).attr('name')); } } |
Check if we really have to go through all validation checks: | 3820 if ((required || $(this).val() != '') || options.type == 'group'){ |
Is this a valid email? | 3823 3824 3825 3826 if (options.type == 'email' && !$.fn.jKit_emailCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'email' } ); } |
Is this a valid url (http:// or https://)? | 3829 3830 3831 3832 if (options.type == 'url' && !$.fn.jKit_urlCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'url' } ); } |
Is this a valid date? | 3835 3836 3837 3838 if (options.type == 'date' && !$.fn.jKit_dateCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'date' } ); } |
Is this date older than some other date? | 3841 3842 3843 3844 if (options.type == 'date' && (new Date($(this).val()).getTime() <= new Date($(options.older).val()).getTime()) ){ elerror = true; errors.push( { 'element': $(this), 'error': 'older' } ); } |
Is this date younger than some other date? | 3847 3848 3849 3850 if (options.type == 'date' && (new Date($(this).val()).getTime() >= new Date($(options.younger).val()).getTime()) ){ elerror = true; errors.push( { 'element': $(this), 'error': 'younger' } ); } |
Is this a valid time? | 3853 3854 3855 3856 if (options.type == 'time' && !$.fn.jKit_timeCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'time' } ); } |
Is this a valid phone number? | 3859 3860 3861 3862 if (options.type == 'phone' && !$.fn.jKit_phoneCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'phone' } ); } |
Is this a float? | 3865 3866 3867 3868 if (options.type == 'float' && isNaN($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'float' } ); } |
Is this a int? | 3871 3872 3873 3874 if (options.type == 'int' && parseInt($(this).val()) != $(this).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'int' } ); } |
min (numeric)? | 3877 3878 3879 3880 if ((options.type == 'int' || options.type == 'float') && options.min != undefined && $(this).val() < options.min && options.type != 'group'){ elerror = true; errors.push( { 'element': $(this), 'error': 'min' } ); } |
max (numeric)? | 3883 3884 3885 3886 if ((options.type == 'int' || options.type == 'float') && options.max != undefined && $(this).val() > options.max && options.type != 'group'){ elerror = true; errors.push( { 'element': $(this), 'error': 'max' } ); } |
Is this bigger than x (numeric)? | 3889 3890 3891 3892 if ((options.type == 'int' || options.type == 'float') && options.bigger != undefined && $(this).val() > $(options.bigger).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'bigger' } ); } |
Is this smaller than x (numeric)? | 3895 3896 3897 3898 if ((options.type == 'int' || options.type == 'float') && options.smaller != undefined && $(this).val() < $(options.smaller).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'smaller' } ); } |
min (length)? | 3901 3902 3903 3904 if ((options.type != 'int' && options.type != 'float') && options.min != undefined && $(this).val().length < options.min && options.type != 'group'){ elerror = true; errors.push( { 'element': $(this), 'error': 'minlength' } ); } |
max (length)? | 3907 3908 3909 3910 if ((options.type != 'int' && options.type != 'float') && options.max != undefined && $(this).val().length > options.max && options.type != 'group'){ elerror = true; errors.push( { 'element': $(this), 'error': 'maxlength' } ); } |
Is the length of the entered string exactly the specified value? | 3913 3914 3915 3916 if (options.length != undefined && $(this).val().length != options.length){ elerror = true; errors.push( { 'element': $(this), 'error': 'length' } ); } |
Is this longer than x (length)? | 3919 3920 3921 3922 if ((options.type != 'int' && options.type != 'float') && options.longer != undefined && $(this).val().length > $(options.longer).val().length){ elerror = true; errors.push( { 'element': $(this), 'error': 'longer' } ); } |
Is this shorter than x (length)? | 3925 3926 3927 3928 if ((options.type != 'int' && options.type != 'float') && options.shorter != undefined && $(this).val().length < $(options.shorter).val().length){ elerror = true; errors.push( { 'element': $(this), 'error': 'shorter' } ); } |
Check password strength (0=bad, 100=perfect)? | 3931 3932 3933 3934 if (options.strength != undefined && $.fn.jKit_passwordStrength($(this).val()) < options.strength){ elerror = true; errors.push( { 'element': $(this), 'error': 'strength' } ); } |
Is this the same as x? | 3937 3938 3939 3940 if (options.same != undefined && $(this).val() != $(options.same).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'same' } ); } |
Is this different than x? | 3943 3944 3945 3946 if (options.different != undefined && $(this).val() != $(options.different).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'different' } ); } |
Has this file the correct extension? | 3949 3950 3951 3952 3953 3954 3955 3956 3957 if (options.type == 'extension'){ var opts = options.options.split(s.delimiter); var filesplit = $(this).val().split('.'); var ext = filesplit[filesplit.length-1]; if ($.inArray(ext,opts) == -1) { elerror = true; errors.push( { 'element': $(this), 'error': 'ext' } ); } } |
Is the correct amount of elements checked in this group? | 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 if (options.type == 'group'){ if (options.min != undefined || options.max != undefined){ var checked = 0; $(this).children('input[type=checkbox][checked]').each( function(){ checked++; }); if ((options.min != undefined && options.min > checked) || (options.max != undefined && checked > options.max)){ elerror = true; errors.push( { 'element': $(this), 'error': 'group' } ); } } else { if ($(this).find("input[name='"+options.name+"']:checked").val() == undefined){ elerror = true; errors.push( { 'element': $(this), 'error': 'group' } ); } } } |
Call a custom function that checks this field: | 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 if (options.type == 'custom' && options.checkfunction != undefined){ var fn = window[options.checkfunction]; if(typeof fn === 'function') { if ( !fn( $(this).val() ) ){ elerror = true; errors.push( { 'element': $(this), 'error': 'custom' } ); } } } } |
Display and error if anything didn’t validate correctly: | 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 if (elerror){ if (options.error != undefined){ $(this).after('<span class="'+s.errorClass+'">'+options.error+'</span>'); } $(this).addClass(s.errorClass); } else { $(this).removeClass(s.errorClass); } }); |
No errors? Than go on … | 4006 if (errors.length == 0){ |
If this form doesn’t use an ajax submit, than just fire the “complete” event: | 4010 4011 4012 4013 4014 if (options.validateonly == "yes"){ plugin.triggerEvent('complete', $that, options); return true; |
This is an ajax submit: | 4018 4019 4020 4021 4022 4023 4024 } else { var action = $(this).attr('action'); $that.removeClass(s.errorClass); if (options.success == undefined) options.success = 'Your form has been sent.'; |
Put all the required fields, comma separated, into the hidden field: | 4028 $that.find('input#'+s.prefix+'-requireds').val(requireds.join(s.delimiter)); |
Post send the serialized data to our form script: | 4032 4033 $.post(action, $that.serialize(), function(data, textStatus, jqXHR) { $that.find('.'+s.errorClass).hide(); |
Check if everything got through correctly: | 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 if (data.sent != undefined && data.sent == true){ if (options.success.charAt(0) == '#'){ $that.html($(options.success).show()); } else { $that.html('<p class="'+s.successClass+'">'+options.success+'</p>'); } plugin.triggerEvent('complete', $that, options); if (options.macro != undefined) plugin.applyMacro($that, options.macro); } else { for (x in data.error){ var field = data.error[x]; $that.find('*[name='+field+']').addClass(s.errorClass).after('<span class="'+s.errorClass+'">'+options.error+'</span>'); } plugin.triggerEvent('error', $that, options); } |
Something didn’t really work. Is there even a compatible form script? Show error: | 4055 4056 4057 4058 }).error(function(xhr, ajaxOptions, thrownError){ alert(thrownError); $that.append('<span class="'+s.errorClass+'">There was an error submitting the form: Error Code '+xhr.status+'</span>'); }); |
Return false so that the browser doesn’t submit the form himself: | 4062 4063 4064 4065 4066 return false; } } else { |
Do we have to display an error for the whole form? | 4070 4071 4072 4073 4074 $that.addClass(s.errorClass); if (options.formerror != undefined){ $that.append('<span class="'+s.errorClass+'">'+options.formerror+'</span>'); } plugin.triggerEvent('error', $that, options); |
Return false so that the browser doesn’t submit the form himself: | 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 return false; } }); }; return command; }()); |
Ajax CommandThe ajax command can do a few thing. The normal use case is a link that loads some extra content through an ajax call on click. But the command can be used to lazy load images, too. | 4095 plugin.commands.ajax = (function(){ |
Create an object that contains all of our data and functionality. | 4099 var command = {}; |
This are the command defaults: | 4103 4104 4105 4106 4107 4108 plugin.addCommandDefaults('ajax', { 'animation': 'slide', 'speed': 250, 'easing': 'linear', 'when': 'click' }); |
The execute function is launched whenever this command is executed: | 4112 4113 4114 command.execute = function($that, options){ var s = plugin.settings; |
If the href option is set, take it from the option, if not, take it from our element: | 4118 4119 4120 4121 4122 4123 4124 if (options.href != undefined && options.href != ''){ var href = options.href; } else { var href = $that.attr('href'); } if (options.when == 'load' || options.when == 'viewport'){ |
If the option when is **load*, than we’re just loading the content: | 4128 4129 4130 4131 if (options.when == 'load'){ $that.load(href, function(){ plugin.triggerEvent('complete', $that, options); }); |
If it’s viewport, we’re going to wait till the content enters the viewport before we load the content or the image (lazy load), whatever our options say: | 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 } else { var myInterval = setInterval(function(){ if ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport){ if (options.src != undefined){ $that.attr('src', options.src); plugin.triggerEvent('complete', $that, options); } else { $that.load(href, function(){ plugin.triggerEvent('complete', $that, options); }); } window.clearInterval(myInterval); } },100); } |
This is our default use case, load the content on click: | 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 } else { $that.on('click', function(){ loadAndReplace(href, options, $that); return false; }); } }; var loadAndReplace = function(href, options, $el){ |
Create an unique temporary id we can use to store and access our loaded content. | 4167 var tempid = plugin.settings.prefix+'_ajax_temp_'+$.fn.jKit_getUnixtime(); |
Hide the affected element: | 4171 $(options.element).jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ |
Prepare the current element and create a div we use to store the loaded content: | 4175 4176 4177 4178 4179 $(options.element).html(''); jQuery('<div/>', { id: tempid }).appendTo('body'); |
Load the content from the supplied url and tell jQuery which element we need from it: | 4183 $('#'+tempid).load(href+' '+options.element, function() { |
Add the content from our temporary div to our real element and initialize the content in case there are an jKit commands on it: | 4188 4189 $(options.element).html( $('#'+tempid+' '+options.element).html() ); plugin.init($(options.element)); |
Trigger some stuff and show the content we just added: | 4193 4194 4195 4196 4197 plugin.triggerEvent('complete', $el, options); $(options.element).jKit_effect(true, options.animation, options.speed, options.easing); if (options.macro != undefined) plugin.applyMacro($(options.element), options.macro); |
Remove our temporary item: | 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 $('#'+tempid).remove(); }); }); }; return command; }()); |
Command TemplateThis is a template for commands. It should be used as a starting point to create new commands. | 4218 plugin.commands.hide = (function(){ |
Create an object that contains all of our data and functionality. | 4222 var command = {}; |
This are the command defaults: | 4226 4227 4228 4229 4230 4231 plugin.addCommandDefaults('hide', { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 command.execute = function($that, options){ $that.jKit_effect(false, options.animation, options.speed, options.easing, options.delay, function(){ plugin.triggerEvent('complete', $that, options); }); }; return command; }()); |
Fontsize CommandThe fontsize command can be used to change the size of text. It can be limited to specific elements. You can even use it to change other CSS related sizes, for example the width of an element, with the style option. | 4254 plugin.commands.fontsize = (function(){ |
Create an object that contains all of our data and functionality. | 4258 var command = {}; |
This are the command defaults: | 4262 4263 4264 4265 4266 4267 4268 plugin.addCommandDefaults('fontsize', { 'steps': 2, 'min': 6, 'max': 72, 'affected': 'p', 'style': 'font-size' }); |
The execute function is launched whenever this command is executed: | 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 command.execute = function($that, options){ $that.on( 'click', function(){ $element.find(options.affected).each( function(){ var newsize = parseInt($(this).css(options.style)) + parseInt(options.steps); if (newsize >= parseInt(options.min) && newsize <= parseInt(options.max) ){ $(this).css(options.style, newsize ); } }); plugin.triggerEvent('changed', $that, options); return false; }); }; return command; }()); |
Remove CommandThe remove command is used to completely remove the element from the DOM. | 4303 plugin.commands.remove = (function(){ |
Create an object that contains all of our data and functionality. | 4307 var command = {}; |
This are the command defaults: | 4311 4312 4313 plugin.addCommandDefaults('remove', { 'delay': 0 }); |
The execute function is launched whenever this command is executed: | 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 command.execute = function($that, options){ $that.delay(options.delay).hide(0, function(){ $that.remove(); plugin.triggerEvent('complete', $that, options); }); }; return command; }()); |
Loop CommandThe loop command does the sam thing as the showandhide command, but repeats itself again, and again … actually, pretty much forever. Oh, and lease don’t use it as a blink tag!!! | 4336 plugin.commands.loop = (function(){ |
Create an object that contains all of our data and functionality. | 4340 var command = {}; |
This are the command defaults: | 4344 4345 4346 4347 4348 4349 4350 4351 4352 plugin.addCommandDefaults('loop', { 'speed1': 500, 'speed2': 500, 'duration1': 2000, 'duration2': 2000, 'easing1': 'linear', 'easing2': 'linear', 'animation': 'fade' }); |
The execute function is launched whenever this command is executed: | 4356 4357 4358 command.execute = function($that, options){ loop($that.hide(), options); }; |
The local loop function is used by the loop the command and basically just shows and hides and element and than starts the next interval. | 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 var loop = function($that, options){ if ((windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus) && ($that.jKit_inViewport() || !$that.jKit_inViewport && plugin.settings.ignoreViewport)){ plugin.triggerEvent('show', $that, options); $that.jKit_effect(true, options.animation, options.speed1, options.easing1, options.duration1, function(){ plugin.triggerEvent('hide', $that, options); $that.jKit_effect(false, options.animation, options.speed2, options.easing2, options.duration2, loop($that, options)); }); } else { window.setTimeout( function() { loop($that, options); }, 100); } }; return command; }()); |
Ticker CommandThe ticker command goes through each item of a list and reveals the item one character at a time. | 4390 plugin.commands.ticker = (function(){ |
Create an object that contains all of our data and functionality. | 4394 var command = {}; |
This are the command defaults: | 4398 4399 4400 4401 4402 plugin.addCommandDefaults('ticker', { 'speed': 100, 'delay': 2000, 'loop': 'yes' }); |
The execute function is launched whenever this command is executed: | 4406 4407 4408 command.execute = function($that, options){ var containerTag = plugin.findElementTag($that, '>', 'max', 'li'); |
Create an array with objects that contain all useful information of a single ticker item: | 4412 4413 4414 4415 4416 4417 4418 4419 4420 var messages = []; $that.find(containerTag).each( function(){ messages.push({ 'href': $(this).find('a').attr('href'), 'target': $(this).find('a').attr('target'), 'text': $(this).text() }); }); |
Replace the target element with a DIV and start the ticker function: | 4424 4425 4426 4427 4428 var $newThat = $('<div/>'); $that.replaceWith($newThat); window.setTimeout( function() { ticker($newThat, options, messages, 0, 0); }, 0); }; |
The ticker function runs the ticker. | 4432 var ticker = function($el, options, messages, currentmessage, currentchar){ |
The stopped variable is used in case the ticker isn’t looped: | 4436 var stopped = false; |
We only run the ticker animation if the element is inside the viewport and the window in focus: | 4440 4441 4442 4443 if ((windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus) && ($el.jKit_inViewport() || !$el.jKit_inViewport() && plugin.settings.ignoreViewport)){ var timer = options.speed; currentchar++; |
Check if we’re at the end of the current ticker message. If yes, start with the next message: | 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 if (currentchar > messages[currentmessage].text.length){ timer = options.delay; currentmessage++; if (currentmessage >= messages.length){ if (options.loop == 'yes' && messages.length > 1){ currentmessage = 0; } else { stopped = true; } } if (!stopped){ setTimeout( function(){ plugin.triggerEvent('showentry showentry'+(currentmessage+1), $el, options); }, timer); currentchar = 0; } |
We are still on the same message, so just display the current amaount of characters, either inside a link or as text: | 4471 4472 4473 4474 4475 4476 4477 4478 } else { if (messages[currentmessage].href != undefined){ $el.html('<a href="'+messages[currentmessage].href+'" target="'+messages[currentmessage].target+'">'+messages[currentmessage].text.substr(0,currentchar)+'</a>'); } else { $el.html(messages[currentmessage].text.substr(0,currentchar)); } } } |
Set a timeout that starts the next step: | 4482 4483 4484 4485 4486 4487 4488 4489 4490 if (!stopped){ window.setTimeout( function() { ticker($el, options, messages, currentmessage, currentchar); }, timer); } }; return command; }()); |
Carousel CommandThe carousel command is used to display a subset of elements like a carousel, new one in, old one out. | 4498 plugin.commands.carousel = (function(){ |
Create an object that contains all of our data and functionality. | 4502 var command = {}; |
This are the command defaults: | 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 plugin.addCommandDefaults('carousel', { 'autoplay': "yes", 'limit': 5, 'animation': 'grow', 'speed': 250, 'easing': 'linear', 'interval': 5000, 'prevhtml': '<', 'nexthtml': '>' }); |
The execute function is launched whenever this command is executed: | 4519 4520 4521 4522 4523 command.execute = function($that, options){ var s = plugin.settings; var cnt = 0; |
First hide all elements that are over our limit of elements we want to show: | 4527 4528 4529 4530 4531 4532 $that.children().each( function(){ cnt++; if (cnt > options.limit){ $(this).hide(); } }); |
Add our prev and next button elements so the user can control the carousel: | 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 var $prevdiv = $('<a/>', { 'class': s.prefix+'-carousel-prev' }).html(options.prevhtml).on( 'click left', function(){ carousel($that, options, 'prev'); }).insertAfter($that); var $nextdiv = $('<a/>', { 'class': s.prefix+'-carousel-next' }).html(options.nexthtml).on( 'click right', function(){ carousel($that, options, 'next'); }).insertAfter($that); |
Add some additional keyboard events: | 4550 4551 plugin.addKeypressEvents($prevdiv, 'left'); plugin.addKeypressEvents($nextdiv, 'right'); |
Start autoplay if needed: | 4555 4556 4557 4558 4559 if (options.autoplay == 'yes'){ window.setTimeout( function() { carousel($that, options); }, options.interval); } }; |
The carousel function moves the carousel either one forward, or one backward. | 4564 carousel = function($el, options, dir){ |
Every manual interaction stops the autoplay: | 4568 4569 4570 if (dir != undefined){ options.autoplay = false; } |
Only run the carousel if we’re inside the viewport and the window has focus: | 4574 if ((windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus) && ($el.jKit_inViewport() || !$el.jKit_inViewport() && plugin.settings.ignoreViewport)){ |
Check if we’re in the middle of an animation: | 4578 4579 4580 4581 4582 4583 var isAnimated = false; $el.children().each( function(){ if ( $(this).is(':animated') ) { isAnimated = true; } }); |
We only move the carousel if it isn’t animating right now: | 4587 if (!isAnimated) { |
What number is the last element? | 4591 var pos = Math.min(options.limit, $el.children().length); |
Step one forward: | 4595 4596 4597 4598 4599 4600 4601 4602 if (dir == 'next' || dir == undefined) { plugin.triggerEvent('shownext', $el, options); $el.children(':first-child').jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ $el.append($el.children(':nth-child(1)')); $el.children(':nth-child('+pos+')').jKit_effect(true, options.animation, options.speed, options.easing, 0); }); |
Step one backward: | 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 } else if (dir == 'prev') { plugin.triggerEvent('showprev', $el, options); $el.children(':nth-child('+pos+')').jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ $el.prepend( $el.children(':last-child') ); $el.children(':first-child').jKit_effect(true, options.animation, options.speed, options.easing, 0); }); } } |
Is autoplay is on? Than set the interval: | 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 if (options.autoplay == 'yes'){ window.setTimeout( function() { carousel($el, options); }, options.interval); } } else { window.setTimeout( function() { carousel($el, options); }, options.interval); } }; return command; }()); |
Paginate CommandThe paginate command lets you create paginated content. | 4640 plugin.commands.paginate = (function(){ |
Create an object that contains all of our data and functionality. | 4644 var command = {}; |
This are the command defaults: | 4648 4649 4650 4651 4652 4653 4654 4655 4656 plugin.addCommandDefaults('paginate', { 'limit': '25', 'by': 'node', 'container': '', 'animation': 'none', 'speed': 250, 'easing': 'linear', 'pos': 'after' }); |
The execute function is launched whenever this command is executed: | 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 command.execute = function($that, options){ var s = plugin.settings; if (options.container != ''){ var $container = $that.find(options.container); } else { var $container = $that; } if ($that.attr('id') !== undefined){ var paginateid = s.prefix+'-paginate-'+$that.attr('id'); } else { var paginateid = s.prefix+'-paginate-uid-'+(++uid); } var pages = []; var page = []; |
Paginate has two ways to operate, either by node count or by actual element height in pixels. In the node mode we put a specific amount of DOM nodes into each entry of the pages array. In the height mode we actually measure the height of each element and only put DOM nodes into the current page that actually fit into the maximum height the user has set. | 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 if (options.by == 'node'){ var cnt = 1; $container.children().each( function(){ cnt++; page.push($(this).detach()); if (cnt > Number(options.limit)){ cnt = 1; pages.push(page); page = []; } }); } else { var height = 0; $container.children().each( function(){ height += $(this).outerHeight(); if (height > Number(options.limit)){ height = $(this).outerHeight(); if (page.length > 0){ pages.push(page); } page = []; } page.push($(this).detach()); }); } if (page.length > 0){ pages.push(page); } if (pages.length > 1){ |
Now as we have the pages set up correctly and we actually have more than one, it’s time to create the output DOM structure. The main element always gets the page data and the actuall pagination is an unordered list we insert after that element. | 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 var $pagination = $('<ul/>', { 'id': paginateid, 'class': s.prefix+'-pagination' }); $.each( pages, function(i,v){ var $pnav = $('<li/>').html(i+1).on( 'click', function(){ plugin.triggerEvent('showpage showpage'+(i+1), $that, options); $pagination.find('li').removeClass(s.activeClass); $(this).addClass(s.activeClass); $container.jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ $container.html(''); $.each(v, function(index, value){ value.clone().appendTo($container); }); $container.jKit_effect(true, options.animation, options.speed, options.easing, 0); }); }); if (i == 0){ $pnav.addClass(s.activeClass); } $pnav.appendTo($pagination); }); if (options.pos == 'after'){ $pagination.insertAfter($that); } else { $pagination.insertBefore($that); } $container.html(''); $.each(pages[0], function(index, value){ value.clone().appendTo($container); }); } }; |
Add local functions and variables here … | 4778 4779 4780 return command; }()); |
Summary CommandThe summary command creates a summary on specific content, for example the headers in a content div. The summary itself is either a linked list or a dropdown with automated events. | 4788 plugin.commands.summary = (function(){ |
Create an object that contains all of our data and functionality. | 4792 var command = {}; |
This are the command defaults: | 4796 4797 4798 4799 4800 4801 4802 4803 plugin.addCommandDefaults('summary', { 'what': '', 'linked': 'yes', 'from': '', 'scope': 'children', 'style': 'ul', 'indent': 'no' }); |
The execute function is launched whenever this command is executed: | 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 command.execute = function($that, options){ var s = plugin.settings; var output = ''; var jumpid = ''; var pre = '' if (options.scope == 'children'){ pre = '> '; } if (options.what == 'headers'){ options.what = ':header'; } $(options.from).find(pre+options.what).each( function(){ var $current = $(this); |
If we’re using all headers for our summary, than we have to do some extra work to get them indented correctly. | 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 var space = ''; if (options.what == ':header' && options.indent == 'yes'){ var tag = $current.prop('tagName'); if (tag.length == 2 && tag[1] != ''){ var spaces = tag[1]-1; for (var i=1; i<=spaces;i++){ space += ' '; } } } |
A summary can either be linked or just text: | 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 if (options.linked == 'yes'){ if ($current.attr('id') !== undefined){ var id = $current.attr('id'); } else { var id = s.prefix+'-uid-'+(++uid); $current.attr('id', id); } if (window.location.hash == '#'+id){ jumpid = id; } if (options.style == 'select'){ output += '<option value="'+id+'">'+space+$(this).text()+'</option>'; } else { output += '<li><a href="#'+id+'">'+space+$(this).text()+'</a></li>'; } } else { if (options.style == 'select'){ output += '<option value="">'+space+$(this).text()+'</option>'; } else { output += '<li>'+space+$(this).text()+'</li>'; } } }); if (output != ''){ $that.html('<'+options.style+'>'+output+'</'+options.style+'>'); |
In case this is a dropdown summary that is linked, we have to manually add an event on change so we can jump to the anchors as needed: | 4878 4879 4880 4881 4882 4883 if (options.style == 'select' && options.linked == 'yes'){ $that.find('select').on( 'change', function(){ window.location.hash = '#'+$(this).val(); $(this).blur(); }); } |
And lastly if we create a select and have detected a hash, we need to set that select to the correct value and jump to the correct element: | 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 if (options.style == 'select' && options.linked == 'yes' && jumpid != ''){ $that.find('select').val(jumpid); if ($that.find('#'+jumpid).offset() !== undefined){ var ypos = $that.find('#'+jumpid).offset().top; $('html, body').css({ scrollTop: ypos+'px' }); } } } }; return command; }()); |
Gallery CommandThe gallery command takes a bunch of images and creates a gallery out of it. | 4913 plugin.commands.gallery = (function(){ |
Create an object that contains all of our data and functionality. | 4917 var command = {}; |
This are the command defaults: | 4921 4922 4923 4924 4925 4926 4927 4928 4929 plugin.addCommandDefaults('gallery', { 'active': 1, 'event': 'click', 'showcaptions': 'yes', 'animation': 'none', 'speed': 500, 'easing': 'linear', 'lightbox': 'no' }); |
The execute function is launched whenever this command is executed: | 4933 4934 4935 4936 command.execute = function($that, options){ var s = plugin.settings; var type = 'gallery'; |
First get all images into an array: | 4940 var images = $that.children(); |
Now put the active image only into the original element: | 4944 $that.html($that.children(':nth-child('+options.active+')').clone()); |
In case we need additional lightbox functionality, add it: | 4948 4949 4950 if (options.lightbox == 'yes'){ plugin.executeCommand($that.find('img'), 'lightbox', {}); } |
Create the element that will contain the thumbnails and insert it after the gallery: | 4954 4955 4956 var $thumbdiv = $('<div/>', { id: s.prefix+'-'+$that.attr('id')+'-'+type+'-thumbs' }).addClass(s.prefix+'-'+type+'-thumbs').insertAfter($that); |
In case we want to show image captions, create an element for it: | 4960 4961 4962 4963 4964 if (options.showcaptions == 'yes'){ var $captiondiv = $('<div/>', { id: s.prefix+'-'+$that.attr('id')+'-'+type+'-captions' }).addClass(s.prefix+'-'+type+'-captions').text($(images[options.active-1]).attr('title')).insertAfter($that); } |
Now loop through all images and add them to the thumbnail div. Add the correct events and animations to each of them and optionally the lightbox functionality. | 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 $.each( images, function(index, value){ if (options.event != 'click' && options.lightbox == 'yes'){ plugin.executeCommand($(value), 'lightbox', { 'group': s.prefix+'-'+$that.attr('id')+'-'+type }); } if (options.active-1 == index){ $(value).addClass(s.activeClass); } $(value) .on( options.event, function() { plugin.triggerEvent('hideentry', $that, options); $that.jKit_effect(false, options.animation, options.speed, options.easing, 0, function(){ $that.find('img').attr('src', $(value).attr('src')); if (options.lightbox == 'yes'){ plugin.executeCommand($that.find('img').unbind('click'), 'lightbox', {}); } plugin.triggerEvent('showentry showentry'+(index+1), $that, options); $that.jKit_effect(true, options.animation, options.speed, options.easing, 0); $thumbdiv.find('img').removeClass(s.activeClass); $(value).addClass(s.activeClass); if (options.showcaptions == 'yes'){ $captiondiv.text($(value).attr('title')); } }); }) .css({ 'cursor': 'pointer' }) .appendTo($thumbdiv); }); }; return command; }()); |
Background CommandThe background command adds an image to the background that is scaled to the full width and height of the window, either skewed or just zoomed. | 5019 plugin.commands.background = (function(){ |
Create an object that contains all of our data and functionality. | 5023 var command = {}; |
This are the command defaults: | 5027 5028 5029 plugin.addCommandDefaults('background', { 'distort': 'no' }); |
The execute function is launched whenever this command is executed: | 5033 5034 5035 command.execute = function($that, options){ var s = plugin.settings; |
Create a background element with a negative z-index that is scaled to the full size of the window: | 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 var $bg = $('<div/>', { id: s.prefix+'-background' }).css({ 'position': 'fixed', 'right': '0px', 'top': '0px', 'overflow': 'hidden', 'z-index': '-1', 'width': $(window).width(), 'height': $(window).height() }).appendTo('body'); $bg.append($that); var ow = $that.attr('width'); var oh = $that.attr('height'); |
Do the correct scaling of the image: | 5058 scaleFit($bg, $that, ow, oh, options.distort); |
Rescale the image in case the window size changes: | 5062 5063 5064 5065 5066 5067 $(window).resize(function() { scaleFit($bg, $that, ow, oh, options.distort); plugin.triggerEvent('resized', $that, options); }); }; |
The scaleFit function calculates the correct with, height of the image relative to the window and the correct position inside that window based on those dimensions. | 5073 scaleFit = function(bg, element, originalWidth, originalHeight, distort){ |
First set some basic values. We basically just scale the image to the full width and height of the window. | 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 var w = $(window).width(); var h = $(window).height(); bg.css({ 'width': w+'px', 'height': h+'px' }); var top = 0; var left = 0; |
If we don’t want to distort the image, we now have to do some additional calculations: | 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 if (distort == 'no'){ var imgRatio = originalWidth / originalHeight; var screenRatio = w / h; if (imgRatio > screenRatio){ w = h * imgRatio; left = (w - $(window).width()) / 2 * -1; } else { h = w / imgRatio; top = (h - $(window).height()) / 2 * -1; } } element.css({ 'position': 'fixed', 'top': top+'px', 'left': left+'px', 'width': w+'px', 'height': h+'px' }); }; return command; }()); |
Command TemplateThis is a template for commands. It should be used as a starting point to create new commands. | 5125 plugin.commands.live = (function(){ |
Create an object that contains all of our data and functionality. | 5129 var command = {}; |
This are the command defaults: | 5133 5134 5135 plugin.addCommandDefaults('live', { 'interval': 60 }); |
The execute function is launched whenever this command is executed: | 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 command.execute = function($that, options){ if ($that.attr('src') !== undefined) { window.setInterval( function() { updateSrc($that, options); plugin.triggerEvent('reloaded', $that, options); }, options.interval*1000); } }; |
The updateSrc function changes the src url in a way that forces the browser to reload the src from the server. | 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 var updateSrc = function($el, options){ if ((windowhasfocus || !windowhasfocus && plugin.settings.ignoreFocus) && ($el.jKit_inViewport() || !$el.jKit_inViewport() && plugin.settings.ignoreViewport)){ var srcSplit = $el.attr('src').split('?'); $el.attr('src', srcSplit[0]+'?t='+$.fn.jKit_getUnixtime()); } }; return command; }()); |
Lightbox CommandThe lightbox command can be used to overlay a bigger version of an image on click, content in an overlayed iframe or to display a modal dialog box above the content. | 5176 plugin.commands.lightbox = (function(){ |
Create an object that contains all of our data and functionality. | 5180 5181 5182 var command = {}; var lightboxes = {}; |
This are the command defaults: | 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 plugin.addCommandDefaults('lightbox', { 'speed': 500, 'opacity': 0.7, 'clearance': 200, 'closer': 'x', 'next': '>', 'prev': '<', 'modal': 'no', 'width': '', 'height': '', 'titleHeight': 20, 'group': '' }); |
The execute function is launched whenever this command is executed: | 5202 5203 5204 5205 command.execute = function($that, options){ var s = plugin.settings; var type = 'lightbox'; |
First we need to find out what the source is we’re going to display in the lightbox. If the href is set, we take that one, if not we check the src attribute and if that’s not set, we check if the element has a background image: | 5211 5212 5213 5214 5215 5216 var src = ''; if ($that.attr('href') !== undefined) src = $that.attr('href'); if (src == '' && $that.attr('src') !== undefined) src = $that.attr('src'); if (src == '' && $that.css('background-image') !== undefined){ src = $that.css('background-image').replace('"','').replace('"','').replace('url(','').replace(')',''); } |
In case we didn’t find a source, we just ignore this command: | 5220 if (src != ''){ |
A lightbox can be part of a group of lightbox content, for example to display a gallery of image. To achive this feature, we’re using an array that is set on plugin init and available thoughout the whole plugin. | 5226 5227 5228 5229 5230 5231 if (options.group != ''){ if (lightboxes[options.group] == undefined){ lightboxes[options.group] = []; } lightboxes[options.group].push($that); } |
A lightbox will always open on click: | 5235 5236 5237 $that.on( 'click', function() { plugin.triggerEvent('clicked', $that, options); |
If this is not a modal window, we have to create an overlay that darkens the whole content: | 5242 5243 5244 5245 5246 5247 if (options.modal == 'no'){ var $overlay = $('<div/>', { id: s.prefix+'-'+type+'-bg', 'class': s.prefix+'-'+type+'-closer '+s.prefix+'-'+type+'-el' }).fadeTo(options.speed, options.opacity).appendTo('body'); } |
We need another DIV for the content that’s placed right above the overlay: | 5251 5252 5253 5254 var $content = $('<div/>', { id: s.prefix+'-'+type+'-content', 'class': s.prefix+'-'+type+'-el' }).fadeTo(0,0.01).appendTo('body'); |
iOS devices need a small hack to display the content correctly in case the page is scrolled: | 5259 if ($.fn.jKit_iOS()) $content.css('top', $(window).scrollTop()+'px'); |
If there’s a fixed width or height set in the options, we have to overwrite the default css values and fix the alignement: | 5264 5265 5266 5267 5268 5269 5270 5271 if (options.width != ''){ $content.css({ 'width': options.width }); $content.css({ 'left': (($(window).width() - $content.outerWidth()) / 2) + 'px' }); } if (options.height != ''){ $content.css({ 'height': options.height }); $content.css({ 'top': (($(window).height() - $content.outerHeight()) / 2) + 'px' }); } |
Time to create the DOM nodes that contain the navigational elements and close button: | 5275 5276 5277 5278 5279 5280 5281 5282 var $nav = $('<div/>', { id: s.prefix+'-'+type+'-nav', 'class': s.prefix+'-'+type+'-el' }).hide().fadeTo(options.speed, 1).appendTo('body'); var $closer = $('<span/>', { 'class': s.prefix+'-'+type+'-closer' }).html(options.closer).prependTo($nav); |
The navigational element has to be placed based on the content element: | 5286 5287 5288 5289 5290 5291 var offset = $content.offset(); $nav.css({ 'top': (offset.top-options.titleHeight-$(window).scrollTop())+'px', 'left': (offset.left+$content.outerWidth()-$nav.width())+'px' }); |
In case this one is part of a group, we need to create the navigation and bind all the needed events to it. Both, the left and the right navigation isn’t always needed, so we have to check for those cases, as well. | 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 if (options.group != ''){ var $next = $('<span/>', { id: s.prefix+'-'+type+'-nav-next' }).prependTo($nav); var $prev = $('<span/>', { id: s.prefix+'-'+type+'-nav-prev' }).prependTo($nav); plugin.addKeypressEvents($next, 'right'); plugin.addKeypressEvents($prev, 'left'); if (lightboxes[options.group][lightboxes[options.group].length-1] != $that){ $next.html(options.next).on( 'click right', function(){ $.each(lightboxes[options.group], function(i,v){ if (v == $that){ $('.'+plugin.settings.prefix+'-'+type+'-el').fadeTo(options.speed, 0, function(){ $(this).remove(); }); lightboxes[options.group][i+1].click(); } }); }); } if (lightboxes[options.group][0] != $that){ $prev.html(options.prev).on( 'click left', function(){ $.each(lightboxes[options.group], function(i,v){ if (v == $that){ $('.'+plugin.settings.prefix+'-'+type+'-el').fadeTo(options.speed, 0, function(){ $(this).remove(); }); lightboxes[options.group][i-1].click(); } }); }); } } |
The last element we have to create and poistion corrently is the optional content title: | 5337 5338 5339 5340 5341 5342 5343 5344 $title = $('<div/>', { id: s.prefix+'-'+type+'-title', 'class': s.prefix+'-'+type+'-el' }).css({ 'top': (offset.top-options.titleHeight-$(window).scrollTop())+'px', 'left': (offset.left)+'px', 'width': $content.width()+'px' }).hide().text($that.attr('title')).fadeTo(options.speed, 1).appendTo('body'); |
Because IE is a stupid browser and doesn’t fire the load element correctly in older versions if the image is already in the cash, we have to force load a new version of the image: | 5349 5350 5351 if (!$.support.leadingWhitespace){ src = src+ "?" + new Date().getTime(); } |
Time to load the image or iframe content. The little trick here is to always try to load an image, even if there isn’t one supplied, because this way we can use the error callback to find out if we actually have an image or not. As soon as the load event has fired, we can get the width an height and will be able to calculate all the placement and scaling information we need. | 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 var img = new Image(); $(img) .load(function () { var scalex = ($(this).outerWidth() + options.clearance) / $(window).width(); var scaley = ($(this).outerHeight() + options.clearance) / $(window).height(); var scale = Math.max(scalex,scaley); if (scale > 1){ var oh = $(this).height(); $(this).width($(this).width() / scale); $(this).height(oh / scale); } var xmargin = ( $(window).width() - $(this).outerWidth() ) / 2; var ymargin = ( $(window).height() - $(this).outerHeight() ) / 2; $content .width($(this).width()) .height($(this).height()) .css({ 'left': xmargin+'px', 'top': ymargin+'px' }) .fadeTo(options.speed, 1); $(this).hide().fadeTo(options.speed, 1); if ($that.attr('title') != ''){ $title.css({ 'top': (ymargin-options.titleHeight)+'px', 'left': xmargin+'px', 'width': $(this).width()+'px' }); } $nav.css({ 'top': (ymargin-options.titleHeight)+'px', 'left': (xmargin+$content.outerWidth()-$nav.width())+'px' }); }) .attr('src', src) .appendTo($content) .error(function(){ $content.html('<iframe id="'+s.prefix+'-'+type+'-iframe" src="'+src+'" style="border:none;width:100%;height:100%"></iframe>').fadeTo(options.speed, 1); }); |
And finally, we make our closing button functional: | 5404 5405 5406 5407 5408 $('.'+s.prefix+'-'+type+'-closer').click(function(){ $('.'+s.prefix+'-'+type+'-el').fadeTo(options.speed, 0, function(){ $(this).remove(); }); }); |
Return false so that we stay on the current page: | 5412 5413 5414 5415 5416 5417 5418 return false; }); } }; |
The closeLightbox function is used to close the active lightbox programmatically from inside the lightbox content. | 5423 5424 5425 5426 5427 5428 5429 5430 5431 plugin.closeLightbox = function(){ $('.'+plugin.settings.prefix+'-lightbox-el').fadeTo('fast', 0, function(){ $(this).remove(); }); }; return command; }()); |
Menu CommandThe menu command adds some additional features to a CSS based menu. | 5439 plugin.commands.menu = (function(){ |
Create an object that contains all of our data and functionality. | 5443 var command = {}; |
This are the command defaults: | 5447 5448 5449 plugin.addCommandDefaults('menu', { 'autoactive': 'no' }); |
The execute function is launched whenever this command is executed: | 5453 5454 5455 command.execute = function($that, options){ var s = plugin.settings; |
Add an active class to the menu link that matches the current page url: | 5459 5460 5461 5462 5463 5464 5465 5466 5467 if (options.autoactive == 'yes'){ var path = window.location.toString().split('#')[0].split("/"); $that.find("a").filter(function() { return $(this).attr("href") == path[path.length-1]; }).addClass(s.activeClass); } |
Add mouseover events and a click event for touch devices: | 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 $that.find("li").hover(function(){ $(this).addClass("hover"); $('ul:first',this).css('visibility', 'visible'); }, function(){ $(this).removeClass("hover"); $('ul:first',this).css('visibility', 'hidden'); }).on( 'click', function(){ $(this).addClass("hover"); $('ul:first',this).css('visibility', 'visible'); }); }; return command; }()); |
Start the plugin by running the initialization function: | 5500 5501 5502 plugin.init(); }; |
jQuery Plugin FunctionsThe following functions act as jQuery plugins. | |
jKit_effectThe jKit_effect plugin function is used by all kind of jKit commands that perform animations. | 5514 $.fn.jKit_effect = function(show, type, speed, easing, delay, fn){ |
This is a real jQuery plugin, so make sure chaining works: | 5518 return this.each(function() { |
Do we have to call a callback function? If not, just create an empty one: | 5522 if (fn == undefined) fn = function(){}; |
If we didn’t set a delay, set the delay variable to zero: | 5526 if (delay == undefined) delay = 0; |
We now have all we need, so run the animation we need: | 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 if (type == 'fade'){ if (show){ $(this).delay(delay).fadeTo(speed, 1.0, easing, fn); } else { $(this).delay(delay).fadeTo(speed, 0, easing, fn); } } else if (type == 'slide'){ if (show){ $(this).delay(delay).slideDown(speed, easing, fn); } else { $(this).delay(delay).slideUp(speed, easing, fn); } } else if (type == 'none'){ if (show){ $(this).delay(delay).show(); } else { $(this).delay(delay).hide(); } fn(); } else { if (show){ $(this).delay(delay).show(speed, easing, fn); } else { $(this).delay(delay).hide(speed, easing, fn); } } }); }; |
jKit_getUnixtimeThe jKit_getUnixtime plugin function returns an unix timestamp based on the current date. | 5564 5565 5566 5567 5568 $.fn.jKit_getUnixtime = function(){ var now = new Date; var unixtime_ms = now.getTime(); return parseInt(unixtime_ms / 1000); }; |
jKit_arrayShuffleThe jKit_arrayShuffle plugin function is used to shuffle an array randomly. | 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 $.fn.jKit_arrayShuffle = function(arr){ var tmp, rand; for(var i =0; i < arr.length; i++){ rand = Math.floor(Math.random() * arr.length); tmp = arr[i]; arr[i] = arr[rand]; arr[rand] = tmp; } return arr; }; |
jKit_stringOccurrencesThe jKit_stringOccurrences plugin function is used to count the times a string is found inside another string. | 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 $.fn.jKit_stringOccurrences = function(string, substring){ var n = 0; var pos = 0; while (true){ pos = string.indexOf(substring, pos); if (pos != -1) { n++; pos += substring.length; } else { break; } } return (n); }; |
jKit_emailCheckThe jKit_emailCheck plugin function is used by the validation command to check if an email address is valid. | 5616 5617 5618 5619 $.fn.jKit_emailCheck = function(string){ var filter = /^[a-z0-9._-]+@([a-z0-9_-]+.)+[a-z]{2,6}$/i; return filter.test(string); }; |
jKit_urlCheckThe jKit_urlCheck plugin function is used by the validation command to check if an url is valid. | 5627 5628 5629 5630 $.fn.jKit_urlCheck = function(string){ var filter = /^(?:(ftp|http|https)://)?(?:[w-]+.)+[a-z]{2,6}$/i; return filter.test(string); }; |
jKit_dateCheckThe jKit_dateCheck plugin function is used by the validation command to check if the date string is valid. | 5638 5639 5640 5641 $.fn.jKit_dateCheck = function(string){ var filter = /^[0-9]{2}.[0-9]{2}.[0-9]{2}$/i; return filter.test(string); }; |
jKit_timeCheckThe jKit_timeCheck plugin function is used by the validation command to check if the time string is valid. | 5649 5650 5651 5652 $.fn.jKit_timeCheck = function(string){ var filter = /^[0-9]{1,2}:[0-9]{2}$/i; return filter.test(string); }; |
jKit_phoneCheckThe jKit_phoneCheck plugin function is used by the validation command to check if the phone string is valid. | 5660 5661 5662 5663 $.fn.jKit_phoneCheck = function(string){ var filter = /^(+|0)[d ]+(-d*)?d$/; return filter.test(string); }; |
jKit_passwordStrengthThe jKit_passwordStrength plugin function is used by the validation command to check if the password strength is good enough. The function calculates a score from 0 to 100 based on various checks. | 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 $.fn.jKit_passwordStrength = function(passwd){ var intScore = 0 if (passwd.length < 5){ intScore = intScore + 5; } else if (passwd.length > 4 && passwd.length < 8){ intScore = intScore + 15; } else if (passwd.length >= 8){ intScore = intScore + 30; } if (passwd.match(/[a-z]/)) intScore = intScore + 5; if (passwd.match(/[A-Z]/)) intScore = intScore + 10; if (passwd.match(/d+/)) intScore = intScore + 10; if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/)) intScore = intScore + 10; if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) intScore = intScore + 10; if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) intScore = intScore + 10; if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) intScore = intScore + 5; if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) intScore = intScore + 5; if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) intScore = intScore + 5; return intScore; }; |
jKit_getAttributesThe jKit_getAttributes plugin function returns an array with all attributes that are set on a specific DOM node. | 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 $.fn.jKit_getAttributes = function(){ return this.each(function() { var map = {}; var attributes = $(this)[0].attributes; var aLength = attributes.length; for (var a = 0; a < aLength; a++) { map[attributes[a].name.toLowerCase()] = attributes[a].value; } return map; }); }; |
jKit_setAttributesThe jKit_setAttributes plugin function creates a set of supplied attributes on an emelemnt. | 5721 5722 5723 5724 5725 5726 5727 5728 5729 $.fn.jKit_setAttributes = function(attr){ return this.each(function() { $.each( attr, function(i,v){ try { $(this).attr(String(i),String(v)); } catch(err) {} }); }); }; |
jKit_iOSThe jKit_iOS plugin function checks the user agent if the current device runs iOS. | 5736 5737 5738 $.fn.jKit_iOS = function(){ return navigator.userAgent.match(/(iPod|iPhone|iPad)/i); }; |
jKit_belowTheFoldThe jKit_belowTheFold plugin function checks if the supplied element is below the page fold. | 5745 5746 5747 5748 $.fn.jKit_belowTheFold = function(){ var fold = $(window).height() + $(window).scrollTop(); return fold <= $(this).offset().top; }; |
jKit_aboveTheTopThe jKit_aboveTheTop plugin function checks if the supplied element is above the top of the currently visible part of the page. | 5755 5756 5757 5758 $.fn.jKit_aboveTheTop = function(){ var top = $(window).scrollTop(); return top >= $(this).offset().top + $(this).height(); }; |
jKit_rightOfScreenThe jKit_rightOfScreen plugin function checks if the supplied element is right from the current voiewport. | 5765 5766 5767 5768 $.fn.jKit_rightOfScreen = function(){ var fold = $(window).width() + $(window).scrollLeft(); return fold <= $(this).offset().left; }; |
jKit_leftOfScreenThe jKit_leftOfScreen plugin function checks if the supplied element is left from the current voiewport. | 5775 5776 5777 5778 $.fn.jKit_leftOfScreen = function(){ var left = $(window).scrollLeft(); return left >= $(this).offset().left + $(this).width(); }; |
jKit_inViewportThe jKit_inViewport plugin function checks if the supplied element is inside the viewport. | 5785 5786 5787 $.fn.jKit_inViewport = function(){ return !$(this).jKit_belowTheFold() && !$(this).jKit_aboveTheTop() && !$(this).jKit_rightOfScreen() && !$(this).jKit_leftOfScreen(); }; |
jKitThe jKit function registers jKit as a jQuery plugin. | 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 $.fn.jKit = function(options, moreoptions) { return this.each(function() { var plugin = new $.jKit(this, options, moreoptions); $(this).data('jKit', plugin); }); }; })(jQuery); |