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 1388 1389 1390 1391 plugin.addCommandDefaults('tooltip', { 'text': '', 'content': '', 'color': '#fff', 'background': '#000', 'classname': '', 'follow': 'no', 'event': 'mouse', 'yoffset': 20 }); |
The execute function is launched whenever this command is executed: | 1395 1396 1397 1398 command.execute = function($that, options){ var s = plugin.settings; var visible = false; |
Create the tooltip div if it doesn’t already exist: | 1402 1403 1404 1405 1406 1407 1408 1409 1410 if ($('div#'+s.prefix+'-tooltip').length == 0){ $('<div/>', { id: s.prefix+'-tooltip' }) .css('position', 'absolute') .hide().appendTo('body'); } $tip = $('div#'+s.prefix+'-tooltip'); |
Get the text from the DOM node, title or alt attribute if it isn’t set in the options: | 1414 1415 1416 1417 1418 1419 if (options.content != ''){ options.text = $(options.content).html(); } else { if (options.text == '') options.text = $.trim($that.attr('title')); if (options.text == '') options.text = $.trim($that.attr('alt')); } |
Display the tooltip on mouseenter or focus: | 1423 1424 1425 1426 1427 1428 1429 1430 1431 var onevent = 'mouseenter'; var offevent = 'mouseleave click'; if (options.event == 'focus'){ onevent = 'focus'; offevent = 'blur'; } $that.on(onevent, function(e){ |
Has this tooltip custom styling either by class or by supplying color values? | 1435 1436 1437 1438 1439 1440 1441 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 }); } if (options.event == 'focus'){ |
Set the position based on the element that came into focus: | 1445 1446 1447 $tip.css({ 'top': $that.offset().top+$that.outerHeight(), 'left': $that.offset().left }); } else { |
Correctly position the tooltip based on the mouse position: | 1451 $tip.css('top', (e.pageY+options.yoffset)).css('left', e.pageX); |
Fix the tooltip position so that we don’t get tooltips we can’t read because their outside the window: | 1456 1457 1458 1459 1460 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: | 1464 1465 1466 1467 1468 $tip.stop(true, true).fadeIn(200); plugin.triggerEvent('open', $that, options); visible = true; |
Fade out the tooltip on mouseleave: | 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 }).on(offevent, function(e){ var speed = 200; if ($tip.is(':animated')){ speed = 0; } $tip.stop(true, true).fadeOut(speed, function(){ visible = false; }); plugin.triggerEvent('closed', $that, options); }); |
If the “follow” option is “true”, we let the tooltip follow the mouse: | 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 if (options.follow == 'yes'){ $('body').on('mousemove', function(e){ if (visible){ $tip.css('top', (e.pageY+options.yoffset-$(window).scrollTop())).css('left', e.pageX); } }); } }; return command; }()); |
Show CommandThe show command is used to reveal an element, animated or not. | 1508 plugin.commands.show = (function(){ |
Create an object that contains all of our data and functionality. | 1512 var command = {}; |
This are the command defaults: | 1516 1517 1518 1519 1520 1521 plugin.addCommandDefaults('show', { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 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. | 1543 plugin.commands.swap = (function(){ |
Create an object that contains all of our data and functionality. | 1547 var command = {}; |
This are the command defaults: | 1551 1552 1553 1554 plugin.addCommandDefaults('swap', { 'versions': '_off,_on', 'attribute': 'src' }); |
The execute function is launched whenever this command is executed: | 1558 1559 1560 1561 1562 1563 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: | 1567 1568 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: | 1572 1573 1574 if (options.attribute == 'src'){ $('<img/>')[0].src = replacement; } |
Finally, add the two event handlers with the swapping code: | 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 $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. | 1604 plugin.commands.limit = (function(){ |
Create an object that contains all of our data and functionality. | 1608 var command = {}; |
This are the command defaults: | 1612 1613 1614 1615 1616 1617 1618 1619 plugin.addCommandDefaults('limit', { 'elements': 'children', 'count': 5, 'animation': 'none', 'speed': 250, 'easing': 'linear', 'endstring': '...' }); |
The execute function is launched whenever this command is executed: | 1623 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: | 1628 1629 1630 1631 1632 1633 1634 1635 1636 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: | 1640 1641 1642 } else { var newtext = $that.text().substr(0,options.count); |
Add an endstring if needed: | 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 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. | 1665 plugin.commands.lorem = (function(){ |
Create an object that contains all of our data and functionality. | 1669 var command = {}; |
This are the command defaults: | 1673 1674 1675 1676 1677 plugin.addCommandDefaults('lorem', { 'paragraphs': 0, 'length': '', 'random': 'no' }); |
The execute function is launched whenever this command is executed: | 1681 command.execute = function($that, options){ |
The lorem ipsum text: | 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 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? | 1699 1700 1701 if (options.random == "yes"){ lorem = $.fn.jKit_arrayShuffle(lorem); } |
Add a specific number of paragraphs: | 1705 1706 1707 1708 1709 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: | 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 } 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. | 1743 plugin.commands.plugin = (function(){ |
Create an object that contains all of our data and functionality. | 1747 var command = {}; |
This are the command defaults: | 1751 1752 1753 plugin.addCommandDefaults('plugin', { 'script': '' }); |
The execute function is launched whenever this command is executed: | 1757 1758 1759 command.execute = function($that, options){ var s = plugin.settings; |
First check if this is a plugin we registered on plugin init: | 1763 1764 1765 1766 1767 1768 1769 1770 1771 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: | 1775 $.ajaxSetup({ cache: true }); |
1779 if (options.script != undefined){ | |
Load the script from the server: | 1783 $.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: | 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 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: | 1803 1804 1805 1806 1807 1808 1809 $.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. | 1818 plugin.commands.split = (function(){ |
Create an object that contains all of our data and functionality. | 1822 var command = {}; |
This are the command defaults: | 1826 1827 1828 1829 1830 1831 plugin.addCommandDefaults('split', { 'separator': '', 'container': 'span', 'before': '', 'after': '' }); |
The execute function is launched whenever this command is executed: | 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 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. | 1859 plugin.commands.random = (function(){ |
Create an object that contains all of our data and functionality. | 1863 var command = {}; |
This are the command defaults: | 1867 1868 1869 1870 plugin.addCommandDefaults('random', { 'count': 1, 'remove': 'yes' }); |
The execute function is launched whenever this command is executed: | 1874 1875 1876 1877 command.execute = function($that, options){ var childs = $that.children().size(); var shownrs = []; |
Create an array of index numbers of our randomly selected elements: | 1881 1882 1883 1884 1885 1886 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: | 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 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. | 1915 plugin.commands.api = (function(){ |
Create an object that contains all of our data and functionality. | 1919 var command = {}; |
This are the command defaults: | 1923 1924 1925 1926 1927 1928 1929 plugin.addCommandDefaults('api', { 'format': 'json', 'value': '', 'url': '', 'interval': -1, 'template': '' }); |
The execute function is launched whenever this command is executed: | 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 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: | 1947 1948 1949 1950 1951 1952 1953 1954 1955 $.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: | 1959 if (options.template != '' && plugin.commands.template !== undefined){ |
First we add the template HTML to our element: | 1963 $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: | 1967 1968 1969 1970 1971 1972 $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: | 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 $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: | 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 } 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: | 2004 2005 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: | 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 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! | 2031 plugin.commands.replace = (function(){ |
Create an object that contains all of our data and functionality. | 2035 var command = {}; |
This are the command defaults: | 2039 2040 2041 2042 2043 plugin.addCommandDefaults('replace', { 'modifier': 'g', 'search': '', 'replacement': '' }); |
The execute function is launched whenever this command is executed: | 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 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. | 2065 plugin.commands.sort = (function(){ |
Create an object that contains all of our data and functionality. | 2069 var command = {}; |
This are the command defaults: | 2073 2074 2075 2076 2077 2078 plugin.addCommandDefaults('sort', { 'what': 'text', 'by': '', 'start': 0, 'end': 0 }); |
The execute function is launched whenever this command is executed: | 2082 2083 2084 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: | 2088 2089 2090 2091 2092 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: | 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 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. | 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 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: | 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 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. | 2202 plugin.commands.parallax = (function(){ |
Create an object that contains all of our data and functionality. | 2206 var command = {}; |
This are the command defaults: | 2210 2211 2212 2213 2214 2215 plugin.addCommandDefaults('parallax', { 'strength': 5, 'axis': 'x', 'scope': 'global', 'detect': 'mousemove' }); |
The execute function is launched whenever this command is executed: | 2219 2220 2221 2222 2223 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. | 2229 2230 2231 2232 2233 2234 2235 if (options.detect == 'scroll'){ var $capture = $(window); } else if (options.scope == 'global'){ var $capture = $(document); } else { var $capture = $that; } |
Set the correct event: | 2239 $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: | 2244 2245 if ((windowhasfocus || !windowhasfocus && s.ignoreFocus) && ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport)){ var cnt = 1; |
Get either the scroll or the mouse position: | 2249 2250 2251 2252 2253 2254 2255 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: | 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 $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. | 2291 plugin.commands.zoom = (function(){ |
Create an object that contains all of our data and functionality. | 2295 var command = {}; |
This are the command defaults: | 2299 2300 2301 2302 2303 plugin.addCommandDefaults('zoom', { 'scale': 2, 'speed': 150, 'lightbox': 'no' }); |
The execute function is launched whenever this command is executed: | 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 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: | 2342 2343 2344 2345 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: | 2349 2350 2351 2352 2353 $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: | 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 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) | 2376 plugin.commands.partially = (function(){ |
Create an object that contains all of our data and functionality. | 2380 var command = {}; |
This are the command defaults: | 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 plugin.addCommandDefaults('partially', { 'height': 200, 'text': 'more ...', 'speed': 250, 'easing': 'linear', 'on': 'mouseover', 'area': '', 'alphaon': 0.9, 'alphaoff': 0 }); |
The execute function is launched whenever this command is executed: | 2397 2398 2399 command.execute = function($that, options){ var s = plugin.settings; |
First store the original height, we need it later. | 2403 var originalHeight = $that.height(); |
Only add the magic is we need, in other words, if the lement is higher than our maximum height: | 2407 if (originalHeight > options.height){ |
We can only add our more div if it’s relatively positioned, so force that one on it: | 2411 $that.css('position', 'relative'); |
Create the more div: | 2415 2416 2417 2418 2419 var $morediv = $('<div/>') .addClass(s.prefix+'-morediv') .appendTo($that) .html(options.text) .css( { width: $that.outerWidth()+'px', opacity: options.alphaon }); |
Add the event handlers and animations: | 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 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'; } |
If the area option is set to “morediv”, we add the event handler only onto the more div and don’t block the content inside the main element from receiving events. | 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 if (options.area == 'morediv'){ $area = $morediv; } else { $area = $that; } $that.css({ 'height': options.height+'px', 'overflow': 'hidden' }); $area.on( openEvent+' down', function() { if ($that.height() < originalHeight){ $morediv.fadeTo(options.speed, options.alphaoff); $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, options.alphaon); $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. | 2475 plugin.commands.showandhide = (function(){ |
Create an object that contains all of our data and functionality. | 2479 var command = {}; |
This are the command defaults: | 2483 2484 2485 2486 2487 2488 2489 plugin.addCommandDefaults('showandhide', { 'delay': 0, 'speed': 500, 'duration': 10000, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 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. | 2513 plugin.commands.filter = (function(){ |
Create an object that contains all of our data and functionality. | 2517 var command = {}; |
This are the command defaults: | 2521 2522 2523 2524 2525 2526 2527 2528 2529 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: | 2533 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. | 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 $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: | 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 $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. | 2575 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. | 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 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? | 2594 2595 2596 2597 2598 if (options.global == 'yes'){ $container = $('body'); } else { $container = $el; } |
Loop through all affected elements and check if they have to be displayed or not. | 2602 $container.find(options.affected).each( function(){ |
First create a few cashes to speed up the following loop through the filter selections: | 2606 2607 2608 2609 2610 2611 2612 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: | 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 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: | 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 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: | 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 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. | 2665 plugin.commands.slideshow = (function(){ |
Create an object that contains all of our data and functionality. | 2669 var command = {}; |
This are the command defaults: | 2673 2674 2675 2676 2677 2678 2679 2680 plugin.addCommandDefaults('slideshow', { 'shuffle': 'no', 'interval': 3000, 'speed': 250, 'animation': 'fade', 'easing': 'linear', 'on': '' }); |
The execute function is launched whenever this command is executed: | 2684 command.execute = function($that, options){ |
Get all slides: | 2688 var slides = $that.children(); |
If needed, shuffle the slides into a random order: | 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 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. | 2708 2709 2710 2711 $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. | 2716 2717 2718 2719 2720 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: | 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 $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: | 2744 2745 2746 2747 2748 2749 $.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. | 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 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. | 2795 plugin.commands.cycle = (function(){ |
Create an object that contains all of our data and functionality. | 2799 var command = {}; |
This are the command defaults: | 2803 2804 2805 2806 2807 2808 plugin.addCommandDefaults('cycle', { 'what': 'class', 'where': 'li', 'scope': 'children', 'sequence': 'odd,even' }); |
The execute function is launched whenever this command is executed: | 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 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: | 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 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. | 2863 plugin.commands.binding = (function(){ |
Create an object that contains all of our data and functionality. | 2867 var command = {}; |
This are the command defaults: | 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 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': '', 'applyto': '', 'delay': 0 }); |
The execute function is launched whenever this command is executed: | 2894 2895 2896 2897 2898 command.execute = function($that, options){ window.setTimeout( function() { binding($that, options); }, options.delay); }; |
The binding function connects different things to other things. It’s a really powerfull function with many options. | 2903 var binding = function(el, options){ |
Only run the code if the window has focus: | 2907 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. | 2912 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: | 2917 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: | 2922 2923 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: | 2927 2928 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. | 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 var $v; if (v == 'this'){ $v = (el); } else if (v == 'parent'){ $v = $(el).parent(); } else { var vsplit = v.split('.'); if (vsplit.length == 1){ $v = $(vsplit[0]); } else if (vsplit[0] == 'each'){ $v = el.find(vsplit[1]); } else if (vsplit[0] == 'children') { $v = el.children(vsplit[1]); } } |
A jQuery selector string can match more than one string, so run through all of them: | 2953 $v.each( function(){ |
The source option defines from where exactly we get our value. There are quite a few options. | 2958 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. | 2963 2964 2965 2966 2967 2968 2969 2970 2971 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: | 2975 2976 2977 2978 2979 case 'html': var temp = $(this).html(); break; |
“text” will get the putre text of the element: | 2983 2984 2985 2986 2987 case 'text': var temp = $(this).text(); break; |
“attr” will get a specific attribute that is specified after the dot, for example attr.id: | 2992 2993 2994 2995 2996 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. | 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 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: | 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 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. | 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 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: | 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 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 | 3104 3105 3106 3107 3108 case 'location': var temp = window.location[sourcesplit[1]]; break; |
“val” will get the value of the element: | 3112 3113 3114 3115 3116 3117 3118 3119 3120 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. | 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 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. | 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 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). | 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 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. | 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 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: | 3215 3216 3217 3218 3219 3220 3221 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: | 3225 if (doit){ |
The math option lets us do some additional calculation on our value: | 3229 3230 3231 if (options.math != ''){ eval('value = '+options.math.replace(/[^a-zA-Z 0-9+-*/.]+/g, '')+';'); } |
Do we have to trigger some additional events? | 3235 3236 3237 3238 3239 3240 3241 3242 3243 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; } } |
Do we have to apply the result to specified DOM nodes or the default source element? | 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 var $els = el; if (options.applyto != ''){ var applysplit = options.applyto.split('.'); if (applysplit.length == 1){ $els = $(applysplit[0]); } else if (applysplit[0] == 'each'){ $els = el.find(applysplit[1]); } else if (applysplit[0] == 'children') { $els = el.children(applysplit[1]); } } $els.each( function(){ var $el = $(this); |
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. | 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 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: | 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 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: | 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 if (modesplit[0] != undefined){ var fn = window[modesplit[0]]; if(typeof fn === 'function') { fn(value,$el); } } } }); } } |
Do we have to set an interval? | 3327 3328 3329 3330 3331 3332 3333 3334 3335 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. | 3343 plugin.commands.accordion = (function(){ |
Create an object that contains all of our data and functionality. | 3347 var command = {}; |
This are the command defaults: | 3351 3352 3353 3354 3355 3356 plugin.addCommandDefaults('accordion', { 'active': 1, 'animation': 'slide', 'speed': 250, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3360 3361 3362 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: | 3366 3367 3368 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! | |
3375 3376 3377 3378 3379 3380 3381 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: | 3385 3386 3387 3388 3389 $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: | 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 $.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 … | 3430 3431 3432 return command; }()); |
Template CommandThe template command implements a simple templating engine. | 3440 plugin.commands.template = (function(){ |
Create an object that contains all of our data and functionality. | 3444 3445 3446 var command = {}; command.templates = {}; |
This are the command defaults: | 3450 3451 3452 3453 3454 3455 plugin.addCommandDefaults('template', { 'action': 'set', 'name': 'template', 'dynamic': 'no', 'addhtml': '+' }); |
The execute function is launched whenever this command is executed: | 3459 3460 3461 command.execute = function($that, options){ var s = plugin.settings; |
Apply a template or define a new one? | 3465 3466 3467 if (options.action == 'apply'){ $el = $that; |
Do we have to apply the template to more than one element? | 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 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: | 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 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: | 3509 3510 3511 if (command.templates[options.name] == undefined){ command.templates[options.name] = []; } |
Define the dynamic variables: | 3515 3516 3517 3518 3519 if (options.vars == undefined){ var vars = []; } else { var vars = options.vars.split(s.delimiter); } |
Add the template to the “global” array: | 3523 3524 3525 3526 3527 command.templates[options.name] = { 'template': $that.detach(), 'vars': vars }; } }; |
The applyTemplate function is used by the template command. It adds the template with all it’s options to the suoplied element. | 3532 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. | 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 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: | 3551 $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. | 3555 $el.find('[class^="if-entry-"]').hide(); |
Rename dynamic attributes so that we don’t get dublicate ids: | 3559 renameDynamicAttributes($el, cnt); |
Add the content and show hidden elements if needed: | 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 $.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(); }); }; |
The renameDynamicAttributes function is used by the plugin.applyTemplate function. It’s used to rename attributes on dynamic elements so that we get unique elements. | 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 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. | 3626 plugin.commands.tabs = (function(){ |
Create an object that contains all of our data and functionality. | 3630 var command = {}; |
This are the command defaults: | 3634 3635 3636 3637 3638 3639 plugin.addCommandDefaults('tabs', { 'active': 1, 'animation': 'none', 'speed': 250, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3643 3644 3645 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: | 3649 3650 3651 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: | 3655 3656 3657 3658 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: | 3662 3663 $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: | 3667 3668 3669 var $tabcontent = $; $.each( tabs, function(index, value){ |
Create a list element and add it to the tab naviagtion: | 3673 var $litemp = $('<li/>', { }).html(value.title).css('cursor', 'pointer').appendTo($tabnav); |
Is this tab active? If yes, add the “active” class: | 3677 3678 3679 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? | |
3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 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? | 3706 3707 3708 3709 3710 if (tabs[options.active-1] != undefined){ $tabcontent = tabs[options.active-1].content.appendTo($that); } }; |
Add local functions and variables here … | 3714 3715 3716 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. | 3726 plugin.commands.key = (function(){ |
Create an object that contains all of our data and functionality. | 3730 var command = {}; |
This are the command defaults: | 3734 plugin.addCommandDefaults('key', {}); |
The execute function is launched whenever this command is executed: | 3738 3739 3740 command.execute = function($that, options){ if (options.code != undefined){ |
First we need to add the event handling for this keycode to the element … | 3744 plugin.addKeypressEvents($that, options.code); |
Because only now we can listen to it: | 3748 3749 3750 3751 3752 $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: | 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 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. | 3779 plugin.commands.scroll = (function(){ |
Create an object that contains all of our data and functionality. | 3783 var command = {}; |
This are the command defaults: | 3787 3788 3789 3790 3791 3792 plugin.addCommandDefaults('scroll', { 'speed': 500, 'dynamic': 'yes', 'easing': 'linear', 'offset': 0 }); |
The execute function is launched whenever this command is executed: | 3796 3797 3798 3799 3800 command.execute = function($that, options){ $that.click(function() { plugin.triggerEvent('clicked', $that, options); |
Get the position of our target element: | 3804 3805 3806 3807 3808 3809 3810 if ($(this).attr("href") == ''){ var ypos = 0; } else { var ypos = $($that.attr("href")).offset().top; } ypos = ypos + parseInt(options.offset); |
The dynamic option changes the scroll animation duration based on the distance between us and the target element: | 3815 3816 3817 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: | 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 $('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. | 3841 plugin.commands.form = (function(){ |
Create an object that contains all of our data and functionality. | 3845 var command = {}; |
This are the command defaults: | 3849 3850 3851 plugin.addCommandDefaults('form', { 'validateonly': 'no' }); |
The execute function is launched whenever this command is executed: | 3855 3856 3857 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. | 3862 3863 3864 3865 3866 $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: | 3870 $that.on('submit', function() { |
Create an error array and remove all error nodes previously set: | 3874 3875 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? | |
3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 $(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: | 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 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: | 3919 if ((required || $(this).val() != '') || options.type == 'group'){ |
Is this a valid email? | 3922 3923 3924 3925 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://)? | 3928 3929 3930 3931 if (options.type == 'url' && !$.fn.jKit_urlCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'url' } ); } |
Is this a valid date? | 3934 3935 3936 3937 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? | 3940 3941 3942 3943 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? | 3946 3947 3948 3949 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? | 3952 3953 3954 3955 if (options.type == 'time' && !$.fn.jKit_timeCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'time' } ); } |
Is this a valid phone number? | 3958 3959 3960 3961 if (options.type == 'phone' && !$.fn.jKit_phoneCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'phone' } ); } |
Is this a float? | 3964 3965 3966 3967 if (options.type == 'float' && isNaN($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'float' } ); } |
Is this a int? | 3970 3971 3972 3973 if (options.type == 'int' && parseInt($(this).val()) != $(this).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'int' } ); } |
min (numeric)? | 3976 3977 3978 3979 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)? | 3982 3983 3984 3985 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)? | 3988 3989 3990 3991 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)? | 3994 3995 3996 3997 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)? | 4000 4001 4002 4003 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)? | 4006 4007 4008 4009 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? | 4012 4013 4014 4015 if (options.length != undefined && $(this).val().length != options.length){ elerror = true; errors.push( { 'element': $(this), 'error': 'length' } ); } |
Is this longer than x (length)? | 4018 4019 4020 4021 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)? | 4024 4025 4026 4027 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)? | 4030 4031 4032 4033 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? | 4036 4037 4038 4039 if (options.same != undefined && $(this).val() != $(options.same).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'same' } ); } |
Is this different than x? | 4042 4043 4044 4045 if (options.different != undefined && $(this).val() != $(options.different).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'different' } ); } |
Has this file the correct extension? | 4048 4049 4050 4051 4052 4053 4054 4055 4056 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? | 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 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: | 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 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: | 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 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 … | 4105 if (errors.length == 0){ |
If this form doesn’t use an ajax submit, than just fire the “complete” event: | 4109 4110 4111 4112 4113 if (options.validateonly == "yes"){ plugin.triggerEvent('complete', $that, options); return true; |
This is an ajax submit: | 4117 4118 4119 4120 4121 4122 4123 } 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: | 4127 $that.find('input#'+s.prefix+'-requireds').val(requireds.join(s.delimiter)); |
Post send the serialized data to our form script: | 4131 4132 $.post(action, $that.serialize(), function(data, textStatus, jqXHR) { $that.find('.'+s.errorClass).hide(); |
Check if everything got through correctly: | 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 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: | 4154 4155 4156 4157 }).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: | 4161 4162 4163 4164 4165 return false; } } else { |
Do we have to display an error for the whole form? | 4169 4170 4171 4172 4173 $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: | 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 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. | 4194 plugin.commands.ajax = (function(){ |
Create an object that contains all of our data and functionality. | 4198 var command = {}; |
This are the command defaults: | 4202 4203 4204 4205 4206 4207 plugin.addCommandDefaults('ajax', { 'animation': 'slide', 'speed': 250, 'easing': 'linear', 'when': 'click' }); |
The execute function is launched whenever this command is executed: | 4211 4212 4213 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: | 4217 4218 4219 4220 4221 4222 4223 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: | 4227 4228 4229 4230 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: | 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 } 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: | 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 } 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. | 4266 var tempid = plugin.settings.prefix+'_ajax_temp_'+$.fn.jKit_getUnixtime(); |
Hide the affected element: | 4270 $(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: | 4274 4275 4276 4277 4278 $(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: | 4282 $('#'+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: | 4287 4288 $(options.element).html( $('#'+tempid+' '+options.element).html() ); plugin.init($(options.element)); |
Trigger some stuff and show the content we just added: | 4292 4293 4294 4295 4296 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: | 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 $('#'+tempid).remove(); }); }); }; return command; }()); |
Command TemplateThis is a template for commands. It should be used as a starting point to create new commands. | 4317 plugin.commands.hide = (function(){ |
Create an object that contains all of our data and functionality. | 4321 var command = {}; |
This are the command defaults: | 4325 4326 4327 4328 4329 4330 plugin.addCommandDefaults('hide', { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 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. | 4353 plugin.commands.fontsize = (function(){ |
Create an object that contains all of our data and functionality. | 4357 var command = {}; |
This are the command defaults: | 4361 4362 4363 4364 4365 4366 4367 plugin.addCommandDefaults('fontsize', { 'steps': 2, 'min': 6, 'max': 72, 'affected': 'p', 'style': 'font-size' }); |
The execute function is launched whenever this command is executed: | 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 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. | 4402 plugin.commands.remove = (function(){ |
Create an object that contains all of our data and functionality. | 4406 var command = {}; |
This are the command defaults: | 4410 4411 4412 plugin.addCommandDefaults('remove', { 'delay': 0 }); |
The execute function is launched whenever this command is executed: | 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 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!!! | 4435 plugin.commands.loop = (function(){ |
Create an object that contains all of our data and functionality. | 4439 var command = {}; |
This are the command defaults: | 4443 4444 4445 4446 4447 4448 4449 4450 4451 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: | 4455 4456 4457 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. | 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 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. | 4489 plugin.commands.ticker = (function(){ |
Create an object that contains all of our data and functionality. | 4493 var command = {}; |
This are the command defaults: | 4497 4498 4499 4500 4501 plugin.addCommandDefaults('ticker', { 'speed': 100, 'delay': 2000, 'loop': 'yes' }); |
The execute function is launched whenever this command is executed: | 4505 4506 4507 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: | 4511 4512 4513 4514 4515 4516 4517 4518 4519 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: | 4523 4524 4525 4526 4527 var $newThat = $('<div/>'); $that.replaceWith($newThat); window.setTimeout( function() { ticker($newThat, options, messages, 0, 0); }, 0); }; |
The ticker function runs the ticker. | 4531 var ticker = function($el, options, messages, currentmessage, currentchar){ |
The stopped variable is used in case the ticker isn’t looped: | 4535 var stopped = false; |
We only run the ticker animation if the element is inside the viewport and the window in focus: | 4539 4540 4541 4542 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: | 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 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: | 4570 4571 4572 4573 4574 4575 4576 4577 } 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: | 4581 4582 4583 4584 4585 4586 4587 4588 4589 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. | 4597 plugin.commands.carousel = (function(){ |
Create an object that contains all of our data and functionality. | 4601 var command = {}; |
This are the command defaults: | 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 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: | 4618 4619 4620 4621 4622 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: | 4626 4627 4628 4629 4630 4631 $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: | 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 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: | 4649 4650 plugin.addKeypressEvents($prevdiv, 'left'); plugin.addKeypressEvents($nextdiv, 'right'); |
Start autoplay if needed: | 4654 4655 4656 4657 4658 if (options.autoplay == 'yes'){ window.setTimeout( function() { carousel($that, options); }, options.interval); } }; |
The carousel function moves the carousel either one forward, or one backward. | 4663 carousel = function($el, options, dir){ |
Every manual interaction stops the autoplay: | 4667 4668 4669 if (dir != undefined){ options.autoplay = false; } |
Only run the carousel if we’re inside the viewport and the window has focus: | 4673 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: | 4677 4678 4679 4680 4681 4682 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: | 4686 if (!isAnimated) { |
What number is the last element? | 4690 var pos = Math.min(options.limit, $el.children().length); |
Step one forward: | 4694 4695 4696 4697 4698 4699 4700 4701 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: | 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 } 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: | 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 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. | 4739 plugin.commands.paginate = (function(){ |
Create an object that contains all of our data and functionality. | 4743 var command = {}; |
This are the command defaults: | 4747 4748 4749 4750 4751 4752 4753 4754 4755 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: | 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 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. | 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 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. | 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 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 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 … | 4877 4878 4879 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. | 4887 plugin.commands.summary = (function(){ |
Create an object that contains all of our data and functionality. | 4891 var command = {}; |
This are the command defaults: | 4895 4896 4897 4898 4899 4900 4901 4902 plugin.addCommandDefaults('summary', { 'what': '', 'linked': 'yes', 'from': '', 'scope': 'children', 'style': 'ul', 'indent': 'no' }); |
The execute function is launched whenever this command is executed: | 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 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. | 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 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: | 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 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: | 4977 4978 4979 4980 4981 4982 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: | 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 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. | 5012 plugin.commands.gallery = (function(){ |
Create an object that contains all of our data and functionality. | 5016 var command = {}; |
This are the command defaults: | 5020 5021 5022 5023 5024 5025 5026 5027 5028 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: | 5032 5033 5034 5035 command.execute = function($that, options){ var s = plugin.settings; var type = 'gallery'; |
First get all images into an array: | 5039 var images = $that.children(); |
Now put the active image only into the original element: | 5043 $that.html($that.children(':nth-child('+options.active+')').clone()); |
In case we need additional lightbox functionality, add it: | 5047 5048 5049 if (options.lightbox == 'yes'){ plugin.executeCommand($that.find('img'), 'lightbox', {}); } |
Create the element that will contain the thumbnails and insert it after the gallery: | 5053 5054 5055 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: | 5059 5060 5061 5062 5063 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. | 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 $.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. | 5118 plugin.commands.background = (function(){ |
Create an object that contains all of our data and functionality. | 5122 var command = {}; |
This are the command defaults: | 5126 5127 5128 plugin.addCommandDefaults('background', { 'distort': 'no' }); |
The execute function is launched whenever this command is executed: | 5132 5133 5134 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: | 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 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: | 5157 scaleFit($bg, $that, ow, oh, options.distort); |
Rescale the image in case the window size changes: | 5161 5162 5163 5164 5165 5166 $(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. | 5172 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. | 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 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: | 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 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. | 5224 plugin.commands.live = (function(){ |
Create an object that contains all of our data and functionality. | 5228 var command = {}; |
This are the command defaults: | 5232 5233 5234 plugin.addCommandDefaults('live', { 'interval': 60 }); |
The execute function is launched whenever this command is executed: | 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 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. | 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 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. | 5275 plugin.commands.lightbox = (function(){ |
Create an object that contains all of our data and functionality. | 5279 5280 5281 var command = {}; var lightboxes = {}; |
This are the command defaults: | 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 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: | 5301 5302 5303 5304 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: | 5310 5311 5312 5313 5314 5315 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: | 5319 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. | 5325 5326 5327 5328 5329 5330 if (options.group != ''){ if (lightboxes[options.group] == undefined){ lightboxes[options.group] = []; } lightboxes[options.group].push($that); } |
A lightbox will always open on click: | 5334 5335 5336 $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: | 5341 5342 5343 5344 5345 5346 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: | 5350 5351 5352 5353 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: | 5358 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: | 5363 5364 5365 5366 5367 5368 5369 5370 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: | 5374 5375 5376 5377 5378 5379 5380 5381 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: | 5385 5386 5387 5388 5389 5390 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. | 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 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: | 5436 5437 5438 5439 5440 5441 5442 5443 $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: | 5448 5449 5450 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. | 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 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: | 5503 5504 5505 5506 5507 $('.'+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: | 5511 5512 5513 5514 5515 5516 5517 return false; }); } }; |
The closeLightbox function is used to close the active lightbox programmatically from inside the lightbox content. | 5522 5523 5524 5525 5526 5527 5528 5529 5530 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. | 5538 plugin.commands.menu = (function(){ |
Create an object that contains all of our data and functionality. | 5542 var command = {}; |
This are the command defaults: | 5546 5547 5548 plugin.addCommandDefaults('menu', { 'autoactive': 'no' }); |
The execute function is launched whenever this command is executed: | 5552 5553 5554 command.execute = function($that, options){ var s = plugin.settings; |
Add an active class to the menu link that matches the current page url: | 5558 5559 5560 5561 5562 5563 5564 5565 5566 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: | 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 $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: | 5599 5600 5601 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. | 5613 $.fn.jKit_effect = function(show, type, speed, easing, delay, fn){ |
This is a real jQuery plugin, so make sure chaining works: | 5617 return this.each(function() { |
Do we have to call a callback function? If not, just create an empty one: | 5621 if (fn == undefined) fn = function(){}; |
If we didn’t set a delay, set the delay variable to zero: | 5625 if (delay == undefined) delay = 0; |
We now have all we need, so run the animation we need: | 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 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. | 5663 5664 5665 5666 5667 $.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. | 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 $.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. | 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 $.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. | 5715 5716 5717 5718 $.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. | 5726 5727 5728 5729 $.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. | 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 $.fn.jKit_dateCheck = function(string){ return $.fn.jKit_regexTests(string, [ /^[0-9]{2}.[0-9]{2}.[0-9]{2}$/i, // 01.01.12 /^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2}$/i, // 1.1.12 /^[0-9]{1,2}.[0-9]{1,2}.[0-9]{4}$/i, // 1.1.2023 /^[0-9]{2}.[0-9]{2}.[0-9]{4}$/i, // 01.01.2023 /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/i, // 2023-01-01 /^[0-9]{2}/[0-9]{2}/[0-9]{4}$/i // 01/01/2023 ]); }; |
jKit_timeCheckThe jKit_timeCheck plugin function is used by the validation command to check if the time string is valid. | 5756 5757 5758 5759 5760 5761 5762 5763 $.fn.jKit_timeCheck = function(string){ return $.fn.jKit_regexTests(string, [ /^[0-9]{1,2}:[0-9]{2}$/i, // 1:59 /^[0-9]{1,2}:[0-9]{2}:[0-9]{2}$/i // 1:59:59 ]); }; |
jKit_phoneCheckThe jKit_phoneCheck plugin function is used by the validation command to check if the phone string is valid. | 5771 5772 5773 5774 5775 5776 5777 5778 5779 $.fn.jKit_phoneCheck = function(string){ return $.fn.jKit_regexTests(string, [ /^(+|0)([d ])+(0|(0))+[d ]+(-d*)?d$/, // +41 (0)76 123 45 67 /^(+|0)[d ]+(-d*)?d$/, // +41 142-124-23 /^(((((d{3}))|(d{3}-))d{3}-d{4})|(+?d{2}((-| )d{1,8}){1,5}))(( x| ext)d{1,5}){0,1}$/ // NAND and int formats ]); }; |
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. | 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 $.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_regexTestsThe jKit_regexTests plugin function is mainly used by the validation commands to test for different patterns. The first argument is the string to test, the second contains an array of all patterns to test and the third is a boolean that can be set to true if all patterns need to be found. | 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 $.fn.jKit_regexTests = function(string, tests, checkall){ if (checkall === undefined) checkall = false; var matches = 0; for (var x in tests){ if ( tests[x].test(string) ) matches++; } return (checkall && matches == tests.length) || (!checkall && matches > 0); }; |
jKit_getAttributesThe jKit_getAttributes plugin function returns an array with all attributes that are set on a specific DOM node. | 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 $.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. | 5858 5859 5860 5861 5862 5863 5864 5865 5866 $.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. | 5873 5874 5875 $.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. | 5882 5883 5884 5885 $.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. | 5892 5893 5894 5895 $.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. | 5902 5903 5904 5905 $.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. | 5912 5913 5914 5915 $.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. | 5922 5923 5924 $.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. | 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 $.fn.jKit = function(options, moreoptions) { return this.each(function() { var plugin = new $.jKit(this, options, moreoptions); $(this).data('jKit', plugin); }); }; })(jQuery); |