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; |
Define some info variables that can be read with the special info command: | 110 111 plugin.version = '1.2.16'; plugin.inc = []; |
Create an object for the plugin settings: | 115 plugin.settings = {}; |
Create an opject to store all jKit command implementations | 119 plugin.commands = {}; |
Array to stor all command execution so that we can find out if something was already executed | 123 plugin.executions = {}; |
And while were’re at it, cache the DOM element: | 127 128 var $element = $(element), element = element; |
In case we are just applying a single command, we need to take the options from the moreoptions parameter: | 132 133 134 135 136 137 138 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: | 142 143 144 145 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): | 149 150 151 152 153 154 155 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. | 170 plugin.init = function($el){ |
In case this function is called without a specific DOM node, use the plugins main DOM element: | 174 if ($el == undefined) $el = $element; |
Extend the plugin defaults with the applied options: | 178 179 180 181 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: | 185 186 187 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. | 193 194 195 $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): | 199 200 201 202 203 204 205 206 207 208 209 var rel = $(this).attr('rel'); var data = plugin.getDataCommands($(this)); if (data != ''){ 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: | 213 $.each( relsplit, function(index, value){ |
First convert all the escaped characters into internal jKit strings. Later we convert them back and unescape them. | 217 218 219 220 221 222 223 224 225 226 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: | 230 if (s.macros[value] != undefined) value = s.macros[value]; |
Now it’s time to parse the options: | 234 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: | 238 239 240 241 242 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: | 246 247 248 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: | 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 } 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 if (options.type == 'info'){ var output = 'jKit version: '+plugin.version+'n'; output += 'Included commands: '+plugin.inc.join(', ')+'n'; console.log(output); console.log($el); } 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: | 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 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:
| 310 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. | 316 317 318 319 320 321 322 323 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: | 328 329 330 331 332 333 334 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: | 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 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: | 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 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. | 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 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); } } } }); } }); }); } }; |
getDataCommandsThe getDataCommands function returns all jKit data element values that have to be executed. They can be spread over multiple attributes with different values for different element sizes (responsive):
| 423 424 425 426 427 428 429 430 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 458 459 460 461 462 463 plugin.getDataCommands = function($el){ var s = plugin.settings; var el = $el.get(0); var commands = ''; for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){ var attr = attrs.item(i).nodeName; var attrsplit = attr.split('-'); if ( attrsplit[0] + '-' + attrsplit[1] == s.dataAttribute ){ if (attrsplit.length > 2){ if (attrsplit[4] !== undefined && attrsplit[4] == 'height'){ var size = $el.height(); } else { var size = $el.width(); } if ( attrsplit[2] !== undefined && attrsplit[3] !== undefined && ( (attrsplit[2] == 'gt' && size > parseInt(attrsplit[3])) || (attrsplit[2] == 'lt' && size < parseInt(attrsplit[3])) ) ){ commands += $el.attr(attr); } } else { commands += $el.attr(attr); } } } return commands; } |
applyMacroThe applyMacro function lets us execute predefined macros. | 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 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):
| 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 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. | 530 531 532 533 534 535 536 537 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. | 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 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. | 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 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. | 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 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. | 692 693 694 695 696 697 698 699 700 701 702 703 704 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. | 710 plugin.executeCommand = function(that, type, options){ |
First create a few shortcuts: | 714 715 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. | 720 721 722 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! | 726 if ($.isArray(plugin.commands[type])){ |
Craete an entry in the command queue with the current element and options: | 730 731 732 733 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: | 737 738 739 740 741 742 743 744 745 746 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. | 752 753 754 if (data.indexOf('plugin.commands.') !== -1){ var queue = plugin.commands[type]; eval(data); |
Now execute all commands in our queue: | 758 759 760 761 762 763 764 765 766 $.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. | 770 771 772 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. | 779 $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) | 783 784 785 786 787 788 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: | 792 793 794 options = plugin.addDefaults(type, options); $.each( options, function(i,v){ |
Convert jKit’s special escaping strings to their regular characters: | 798 799 800 801 802 803 804 805 806 807 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): | 811 812 813 814 815 816 817 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: | 821 822 823 824 825 826 827 828 829 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: | 836 837 838 839 840 841 842 843 844 845 846 847 848 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:
| 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 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: | 883 defaults.commands[c] = d; |
And trigger the loaded event for this command (command.name.loaded) so everyone knows that this command is ready: | 887 888 889 $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. | 897 plugin.addKeypressEvents = function($el, code){ |
Check first if key navigations aren’t globally switched off: | 901 if (plugin.settings.keyNavigation){ |
Listen to the documents keydown event: | 905 $(document).keydown(function(e){ |
Only add the event if this isn’t a textaream, select or text input: | 909 if ( this !== e.target && (/textarea|select/i.test( e.target.nodeName ) || e.target.type === "text") ) return; |
Map keycodes to their identifiers: | 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 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: | 969 970 971 972 973 for(var i=48; i<=90; i++){ keys[i] = String.fromCharCode(i).toLowerCase(); } if ($.inArray(e.which, keys)){ |
Add special keys: | 977 978 979 980 981 982 983 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: | 987 988 989 990 991 992 993 994 995 996 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. | 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 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. | 1036 plugin.commands.encode = (function(){ |
Create an object that contains all of our data and functionality. | 1040 var command = {}; |
This are the command defaults: | 1044 1045 1046 1047 plugin.addCommandDefaults('encode', { 'format': 'code', 'fix': 'yes' }); |
The execute function is launched whenever this command is executed: | 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 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. | 1114 plugin.commands.chart = (function(){ |
Create an object that contains all of our data and functionality. | 1118 var command = {}; |
This are the command defaults: | 1122 1123 1124 1125 1126 1127 plugin.addCommandDefaults('chart', { 'max': 0, 'delaysteps': 100, 'speed': 500, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 1131 1132 1133 command.execute = function($that, options){ var s = plugin.settings; |
First get the main label from the THEAD and the main element id: | 1137 1138 var label = $that.find('thead > tr > th.label').text(); var id = $that.attr('id'); |
Now get all data column labels from the THEAD | 1142 1143 1144 1145 1146 1147 1148 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! | |
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 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: | 1171 1172 1173 if (options.max > 0 && max < options.max){ max = options.max; } |
Time to construct our chart element: | 1177 1178 1179 1180 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. | 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 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: | 1225 1226 1227 $that.replaceWith($chart); }; |
Add local functions and variables here … | 1231 1232 1233 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. | 1242 plugin.commands.animation = (function(){ |
Create an object that contains all of our data and functionality. | 1246 var command = {}; |
This are the command defaults: | 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 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: | 1263 1264 1265 command.execute = function($that, options){ var s = plugin.settings; |
First check if this is a CSS animation: | 1269 if (options.to != ''){ |
If the from option is set, we first have to set the initial CSS: | 1273 1274 1275 if (options.from != ''){ $that.css( plugin.cssFromString(options.from) ); } |
use setTimeout to delay the animation, even if the delay is zero: | 1279 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. | |
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 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: | 1304 1305 1306 1307 1308 1309 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. | 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 $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: | 1348 $that.html(frames[0].el); |
And now start the animation: | 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 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: | 1366 1367 $.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: | 1372 1373 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: | 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 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: | 1403 1404 1405 1406 1407 1408 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? | 1412 1413 1414 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: | 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 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. | 1439 plugin.commands.tooltip = (function(){ |
Create an object that contains all of our data and functionality. | 1443 var command = {}; |
This are the command defaults: | 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 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: | 1460 1461 1462 1463 command.execute = function($that, options){ var s = plugin.settings; var visible = false; |
Create the tooltip div if it doesn’t already exist: | 1467 1468 1469 1470 1471 1472 1473 1474 1475 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: | 1479 1480 1481 1482 1483 1484 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: | 1488 1489 1490 1491 1492 1493 1494 1495 1496 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? | 1500 1501 1502 1503 1504 1505 1506 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: | 1510 1511 1512 $tip.css({ 'top': $that.offset().top+$that.outerHeight(), 'left': $that.offset().left }); } else { |
Correctly position the tooltip based on the mouse position: | 1516 $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: | 1521 1522 1523 1524 1525 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: | 1529 1530 1531 1532 1533 $tip.stop(true, true).fadeIn(200); plugin.triggerEvent('open', $that, options); visible = true; |
Fade out the tooltip on mouseleave: | 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 }).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: | 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 if (options.follow == 'yes'){ $('body').on('mousemove', function(e){ if (visible){ $tip.css('top', (e.pageY+options.yoffset)).css('left', e.pageX); } }); } }; return command; }()); |
Show CommandThe show command is used to reveal an element, animated or not. | 1573 plugin.commands.show = (function(){ |
Create an object that contains all of our data and functionality. | 1577 var command = {}; |
This are the command defaults: | 1581 1582 1583 1584 1585 1586 plugin.addCommandDefaults('show', { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 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. | 1608 plugin.commands.swap = (function(){ |
Create an object that contains all of our data and functionality. | 1612 var command = {}; |
This are the command defaults: | 1616 1617 1618 1619 plugin.addCommandDefaults('swap', { 'versions': '_off,_on', 'attribute': 'src' }); |
The execute function is launched whenever this command is executed: | 1623 1624 1625 1626 1627 1628 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: | 1632 1633 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: | 1637 1638 1639 if (options.attribute == 'src'){ $('<img/>')[0].src = replacement; } |
Finally, add the two event handlers with the swapping code: | 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 $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. | 1669 plugin.commands.limit = (function(){ |
Create an object that contains all of our data and functionality. | 1673 var command = {}; |
This are the command defaults: | 1677 1678 1679 1680 1681 1682 1683 1684 plugin.addCommandDefaults('limit', { 'elements': 'children', 'count': 5, 'animation': 'none', 'speed': 250, 'easing': 'linear', 'endstring': '...' }); |
The execute function is launched whenever this command is executed: | 1688 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: | 1693 1694 1695 1696 1697 1698 1699 1700 1701 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: | 1705 1706 1707 } else { var newtext = $that.text().substr(0,options.count); |
Add an endstring if needed: | 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 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. | 1730 plugin.commands.lorem = (function(){ |
Create an object that contains all of our data and functionality. | 1734 var command = {}; |
This are the command defaults: | 1738 1739 1740 1741 1742 plugin.addCommandDefaults('lorem', { 'paragraphs': 0, 'length': '', 'random': 'no' }); |
The execute function is launched whenever this command is executed: | 1746 command.execute = function($that, options){ |
The lorem ipsum text: | 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 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? | 1764 1765 1766 if (options.random == "yes"){ lorem = $.fn.jKit_arrayShuffle(lorem); } |
Add a specific number of paragraphs: | 1770 1771 1772 1773 1774 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: | 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 } 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. | 1808 plugin.commands.plugin = (function(){ |
Create an object that contains all of our data and functionality. | 1812 var command = {}; |
This are the command defaults: | 1816 1817 1818 plugin.addCommandDefaults('plugin', { 'script': '' }); |
The execute function is launched whenever this command is executed: | 1822 1823 1824 command.execute = function($that, options){ var s = plugin.settings; |
First check if this is a plugin we registered on plugin init: | 1828 1829 1830 1831 1832 1833 1834 1835 1836 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: | 1840 $.ajaxSetup({ cache: true }); |
1844 if (options.script != undefined){ | |
Load the script from the server: | 1848 $.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: | 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 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: | 1868 1869 1870 1871 1872 1873 1874 $.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. | 1883 plugin.commands.split = (function(){ |
Create an object that contains all of our data and functionality. | 1887 var command = {}; |
This are the command defaults: | 1891 1892 1893 1894 1895 1896 plugin.addCommandDefaults('split', { 'separator': '', 'container': 'span', 'before': '', 'after': '' }); |
The execute function is launched whenever this command is executed: | 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 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. | 1924 plugin.commands.random = (function(){ |
Create an object that contains all of our data and functionality. | 1928 var command = {}; |
This are the command defaults: | 1932 1933 1934 1935 plugin.addCommandDefaults('random', { 'count': 1, 'remove': 'yes' }); |
The execute function is launched whenever this command is executed: | 1939 1940 1941 1942 command.execute = function($that, options){ var childs = $that.children().size(); var shownrs = []; |
Create an array of index numbers of our randomly selected elements: | 1946 1947 1948 1949 1950 1951 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: | 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 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. | 1980 plugin.commands.api = (function(){ |
Create an object that contains all of our data and functionality. | 1984 var command = {}; |
This are the command defaults: | 1988 1989 1990 1991 1992 1993 1994 plugin.addCommandDefaults('api', { 'format': 'json', 'value': '', 'url': '', 'interval': -1, 'template': '' }); |
The execute function is launched whenever this command is executed: | 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 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: | 2012 2013 2014 2015 2016 2017 2018 2019 2020 $.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: | 2024 if (options.template != '' && plugin.commands.template !== undefined){ |
First we add the template HTML to our element: | 2028 $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: | 2032 2033 2034 2035 2036 2037 $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: | 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 $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: | 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 } 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: | 2069 2070 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: | 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 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! | 2096 plugin.commands.replace = (function(){ |
Create an object that contains all of our data and functionality. | 2100 var command = {}; |
This are the command defaults: | 2104 2105 2106 2107 2108 plugin.addCommandDefaults('replace', { 'modifier': 'g', 'search': '', 'replacement': '' }); |
The execute function is launched whenever this command is executed: | 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 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. | 2130 plugin.commands.sort = (function(){ |
Create an object that contains all of our data and functionality. | 2134 var command = {}; |
This are the command defaults: | 2138 2139 2140 2141 2142 2143 plugin.addCommandDefaults('sort', { 'what': 'text', 'by': '', 'start': 0, 'end': 0 }); |
The execute function is launched whenever this command is executed: | 2147 2148 2149 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: | 2153 2154 2155 2156 2157 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: | 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 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. | 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 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: | 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 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; }()); |
Respond CommandThe respond command can helps you create better responsive websites, especially if it’s built modularly. It makes it possible to use something similar to “Element Queries”. | 2266 plugin.commands.respond = (function(){ |
Create an object that contains all of our data and functionality. | 2270 var command = {}; |
This are the command defaults: | 2274 plugin.addCommandDefaults('respond', {}); |
The execute function is launched whenever this command is executed: | 2278 command.execute = function($that, options){ |
Onlyx run the command if the width option is set: | 2282 if (options.width != undefined){ |
Split the string into an array that contain all widths, sorted from the smallest to the biggest: | 2286 2287 2288 2289 var widths = options.width.split(','); widths.sort( function(a,b){ return parseInt(a)-parseInt(b); }); |
Now execute and bind the setClasses function: | 2293 2294 2295 2296 2297 2298 2299 2300 setClasses($that, widths); $(window).resize(function(){ setClasses($that, widths); }); } }; |
The setClasses function sets the ^correct class based on the elements width. | 2304 var setClasses = function($that, widths){ |
Set some initial variables: | 2308 2309 var w = $that.width(); var responseClass = ''; |
Find out which class (if any) we have to set: | 2313 2314 2315 2316 2317 for(var x in widths){ if (parseInt(widths[x]) < w){ responseClass = plugin.settings.prefix+'-respond-'+widths[x]; } } |
Get all currently set classes and remove them from the element: | 2321 2322 2323 2324 2325 2326 2327 if ($that.attr('class') == undefined){ var classList = []; } else { var classList = $that.attr('class').split(/s+/); } $that.removeClass(); |
Add all needed classes back to the element together with the respond class: | 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 for(var x in classList){ if (classList[x].indexOf(plugin.settings.prefix+'-respond') == -1){ $that.addClass(classList[x]); } } $that.addClass(responseClass); }; 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. | 2352 plugin.commands.parallax = (function(){ |
Create an object that contains all of our data and functionality. | 2356 var command = {}; |
This are the command defaults: | 2360 2361 2362 2363 2364 2365 plugin.addCommandDefaults('parallax', { 'strength': 5, 'axis': 'x', 'scope': 'global', 'detect': 'mousemove' }); |
The execute function is launched whenever this command is executed: | 2369 2370 2371 2372 2373 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. | 2379 2380 2381 2382 2383 2384 2385 if (options.detect == 'scroll'){ var $capture = $(window); } else if (options.scope == 'global'){ var $capture = $(document); } else { var $capture = $that; } |
Set the correct event: | 2389 $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: | 2394 2395 if ((windowhasfocus || !windowhasfocus && s.ignoreFocus) && ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport)){ var cnt = 1; |
Get either the scroll or the mouse position: | 2399 2400 2401 2402 2403 2404 2405 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: | 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 $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. | 2441 plugin.commands.zoom = (function(){ |
Create an object that contains all of our data and functionality. | 2445 var command = {}; |
This are the command defaults: | 2449 2450 2451 2452 2453 plugin.addCommandDefaults('zoom', { 'scale': 2, 'speed': 150, 'lightbox': 'no' }); |
The execute function is launched whenever this command is executed: | 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 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(); var $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: | 2492 2493 2494 2495 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: | 2499 2500 2501 2502 2503 $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: | 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 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) | 2526 plugin.commands.partially = (function(){ |
Create an object that contains all of our data and functionality. | 2530 var command = {}; |
This are the command defaults: | 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 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: | 2547 2548 2549 command.execute = function($that, options){ var s = plugin.settings; |
First store the original height, we need it later. | 2553 var originalHeight = $that.height(); |
Only add the magic is we need, in other words, if the lement is higher than our maximum height: | 2557 if (originalHeight > options.height){ |
We can only add our more div if it’s relatively positioned, so force that one on it: | 2561 $that.css('position', 'relative'); |
Create the more div: | 2565 2566 2567 2568 2569 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: | 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 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. | 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 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. | 2625 plugin.commands.showandhide = (function(){ |
Create an object that contains all of our data and functionality. | 2629 var command = {}; |
This are the command defaults: | 2633 2634 2635 2636 2637 2638 2639 plugin.addCommandDefaults('showandhide', { 'delay': 0, 'speed': 500, 'duration': 10000, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 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. | 2663 plugin.commands.filter = (function(){ |
Create an object that contains all of our data and functionality. | 2667 var command = {}; |
This are the command defaults: | 2671 2672 2673 2674 2675 2676 2677 2678 2679 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: | 2683 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. | 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 $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: | 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 $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. | 2725 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. | 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 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? | 2744 2745 2746 2747 2748 if (options.global == 'yes'){ $container = $('body'); } else { $container = $el; } |
Loop through all affected elements and check if they have to be displayed or not. | 2752 $container.find(options.affected).each( function(){ |
First create a few cashes to speed up the following loop through the filter selections: | 2756 2757 2758 2759 2760 2761 2762 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: | 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 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: | 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 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: | 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 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. | 2815 plugin.commands.slideshow = (function(){ |
Create an object that contains all of our data and functionality. | 2819 var command = {}; |
This are the command defaults: | 2823 2824 2825 2826 2827 2828 2829 2830 plugin.addCommandDefaults('slideshow', { 'shuffle': 'no', 'interval': 3000, 'speed': 250, 'animation': 'fade', 'easing': 'linear', 'on': '' }); |
The execute function is launched whenever this command is executed: | 2834 command.execute = function($that, options){ |
Get all slides: | 2838 var slides = $that.children(); |
If needed, shuffle the slides into a random order: | 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 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. | 2858 2859 2860 2861 $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. | 2866 2867 2868 2869 2870 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: | 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 $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: | 2894 2895 2896 2897 2898 2899 $.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. | 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 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. | 2945 plugin.commands.cycle = (function(){ |
Create an object that contains all of our data and functionality. | 2949 var command = {}; |
This are the command defaults: | 2953 2954 2955 2956 2957 2958 plugin.addCommandDefaults('cycle', { 'what': 'class', 'where': 'li', 'scope': 'children', 'sequence': 'odd,even' }); |
The execute function is launched whenever this command is executed: | 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 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: | 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 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. | 3013 plugin.commands.binding = (function(){ |
Create an object that contains all of our data and functionality. | 3017 var command = {}; |
This are the command defaults: | 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 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: | 3044 3045 3046 3047 3048 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. | 3053 var binding = function(el, options){ |
Only run the code if the window has focus: | 3057 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. | 3062 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: | 3067 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: | 3072 3073 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: | 3077 3078 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. | 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 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: | 3103 $v.each( function(){ |
The source option defines from where exactly we get our value. There are quite a few options. | 3108 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. | 3113 3114 3115 3116 3117 3118 3119 3120 3121 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: | 3125 3126 3127 3128 3129 case 'html': var temp = $(this).html(); break; |
“text” will get the putre text of the element: | 3133 3134 3135 3136 3137 case 'text': var temp = $(this).text(); break; |
“attr” will get a specific attribute that is specified after the dot, for example attr.id: | 3142 3143 3144 3145 3146 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. | 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 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: | 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 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. | 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 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: | 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 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 | 3254 3255 3256 3257 3258 case 'location': var temp = window.location[sourcesplit[1]]; break; |
“val” will get the value of the element: | 3262 3263 3264 3265 3266 3267 3268 3269 3270 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. | 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 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. | 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 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). | 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 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. | 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 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: | 3365 3366 3367 3368 3369 3370 3371 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: | 3375 if (doit){ |
The math option lets us do some additional calculation on our value: | 3379 3380 3381 if (options.math != ''){ eval('value = '+options.math.replace(/[^a-zA-Z 0-9+-*/.]+/g, '')+';'); } |
Do we have to trigger some additional events? | 3385 3386 3387 3388 3389 3390 3391 3392 3393 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? | 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 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. | 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 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: | 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 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: | 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 if (modesplit[0] != undefined){ var fn = window[modesplit[0]]; if(typeof fn === 'function') { fn(value,$el); } } } }); } } |
Do we have to set an interval? | 3477 3478 3479 3480 3481 3482 3483 3484 3485 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. | 3493 plugin.commands.accordion = (function(){ |
Create an object that contains all of our data and functionality. | 3497 var command = {}; |
This are the command defaults: | 3501 3502 3503 3504 3505 3506 plugin.addCommandDefaults('accordion', { 'active': 1, 'animation': 'slide', 'speed': 250, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3510 3511 3512 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: | 3516 3517 3518 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! | |
3525 3526 3527 3528 3529 3530 3531 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: | 3535 3536 3537 3538 3539 $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: | 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 $.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 … | 3580 3581 3582 return command; }()); |
Template CommandThe template command implements a simple templating engine. | 3590 plugin.commands.template = (function(){ |
Create an object that contains all of our data and functionality. | 3594 3595 3596 var command = {}; command.templates = {}; |
This are the command defaults: | 3600 3601 3602 3603 3604 3605 plugin.addCommandDefaults('template', { 'action': 'set', 'name': 'template', 'dynamic': 'no', 'addhtml': '+' }); |
The execute function is launched whenever this command is executed: | 3609 3610 3611 command.execute = function($that, options){ var s = plugin.settings; |
Apply a template or define a new one? | 3615 3616 3617 if (options.action == 'apply'){ $el = $that; |
Do we have to apply the template to more than one element? | 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 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: | 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 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: | 3659 3660 3661 if (command.templates[options.name] == undefined){ command.templates[options.name] = []; } |
Define the dynamic variables: | 3665 3666 3667 3668 3669 if (options.vars == undefined){ var vars = []; } else { var vars = options.vars.split(s.delimiter); } |
Add the template to the “global” array: | 3673 3674 3675 3676 3677 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. | 3682 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. | 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 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: | 3701 $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. | 3705 $el.find('[class^="if-entry-"]').hide(); |
Rename dynamic attributes so that we don’t get dublicate ids: | 3709 renameDynamicAttributes($el, cnt); |
Add the content and show hidden elements if needed: | 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 $.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. | 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 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. | 3776 plugin.commands.tabs = (function(){ |
Create an object that contains all of our data and functionality. | 3780 var command = {}; |
This are the command defaults: | 3784 3785 3786 3787 3788 3789 plugin.addCommandDefaults('tabs', { 'active': 1, 'animation': 'none', 'speed': 250, 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 3793 3794 3795 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: | 3799 3800 3801 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: | 3805 3806 3807 3808 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: | 3812 3813 $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: | 3817 3818 3819 var $tabcontent = $; $.each( tabs, function(index, value){ |
Create a list element and add it to the tab naviagtion: | 3823 var $litemp = $('<li/>', { }).html(value.title).css('cursor', 'pointer').appendTo($tabnav); |
Is this tab active? If yes, add the “active” class: | 3827 3828 3829 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? | |
3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 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? | 3856 3857 3858 3859 3860 if (tabs[options.active-1] != undefined){ $tabcontent = tabs[options.active-1].content.appendTo($that); } }; |
Add local functions and variables here … | 3864 3865 3866 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. | 3876 plugin.commands.key = (function(){ |
Create an object that contains all of our data and functionality. | 3880 var command = {}; |
This are the command defaults: | 3884 plugin.addCommandDefaults('key', {}); |
The execute function is launched whenever this command is executed: | 3888 3889 3890 command.execute = function($that, options){ if (options.code != undefined){ |
First we need to add the event handling for this keycode to the element … | 3894 plugin.addKeypressEvents($that, options.code); |
Because only now we can listen to it: | 3898 3899 3900 3901 3902 $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: | 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 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. | 3929 plugin.commands.scroll = (function(){ |
Create an object that contains all of our data and functionality. | 3933 var command = {}; |
This are the command defaults: | 3937 3938 3939 3940 3941 3942 plugin.addCommandDefaults('scroll', { 'speed': 500, 'dynamic': 'yes', 'easing': 'linear', 'offset': 0 }); |
The execute function is launched whenever this command is executed: | 3946 3947 3948 3949 3950 command.execute = function($that, options){ $that.click(function() { plugin.triggerEvent('clicked', $that, options); |
Get the position of our target element: | 3954 3955 3956 3957 3958 3959 3960 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: | 3965 3966 3967 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: | 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 $('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. | 3991 plugin.commands.form = (function(){ |
Create an object that contains all of our data and functionality. | 3995 var command = {}; |
This are the command defaults: | 3999 4000 4001 plugin.addCommandDefaults('form', { 'validateonly': 'no' }); |
The execute function is launched whenever this command is executed: | 4005 4006 4007 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. | 4012 4013 4014 4015 4016 $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: | 4020 $that.on('submit', function() { |
Create an error array and remove all error nodes previously set: | 4024 4025 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? | |
4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 $(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: | 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 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: | 4069 if ((required || $(this).val() != '') || options.type == 'group'){ |
Is this a valid email? | 4072 4073 4074 4075 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://)? | 4078 4079 4080 4081 if (options.type == 'url' && !$.fn.jKit_urlCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'url' } ); } |
Is this a valid date? | 4084 4085 4086 4087 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? | 4090 4091 4092 4093 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? | 4096 4097 4098 4099 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? | 4102 4103 4104 4105 if (options.type == 'time' && !$.fn.jKit_timeCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'time' } ); } |
Is this a valid phone number? | 4108 4109 4110 4111 if (options.type == 'phone' && !$.fn.jKit_phoneCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'phone' } ); } |
Is this a float? | 4114 4115 4116 4117 if (options.type == 'float' && isNaN($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'float' } ); } |
Is this a int? | 4120 4121 4122 4123 if (options.type == 'int' && parseInt($(this).val()) != $(this).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'int' } ); } |
min (numeric)? | 4126 4127 4128 4129 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)? | 4132 4133 4134 4135 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)? | 4138 4139 4140 4141 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)? | 4144 4145 4146 4147 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)? | 4150 4151 4152 4153 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)? | 4156 4157 4158 4159 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? | 4162 4163 4164 4165 if (options.length != undefined && $(this).val().length != options.length){ elerror = true; errors.push( { 'element': $(this), 'error': 'length' } ); } |
Is this longer than x (length)? | 4168 4169 4170 4171 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)? | 4174 4175 4176 4177 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)? | 4180 4181 4182 4183 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? | 4186 4187 4188 4189 if (options.same != undefined && $(this).val() != $(options.same).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'same' } ); } |
Is this different than x? | 4192 4193 4194 4195 if (options.different != undefined && $(this).val() != $(options.different).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'different' } ); } |
Has this file the correct extension? | 4198 4199 4200 4201 4202 4203 4204 4205 4206 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? | 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 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: | 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 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: | 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 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 … | 4255 if (errors.length == 0){ |
If this form doesn’t use an ajax submit, than just fire the “complete” event: | 4259 4260 4261 4262 4263 if (options.validateonly == "yes"){ plugin.triggerEvent('complete', $that, options); return true; |
This is an ajax submit: | 4267 4268 4269 4270 4271 4272 4273 } 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: | 4277 $that.find('input#'+s.prefix+'-requireds').val(requireds.join(s.delimiter)); |
Post send the serialized data to our form script: | 4281 4282 $.post(action, $that.serialize(), function(data, textStatus, jqXHR) { $that.find('.'+s.errorClass).hide(); |
Check if everything got through correctly: | 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 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: | 4304 4305 4306 4307 }).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: | 4311 4312 4313 4314 4315 return false; } } else { |
Do we have to display an error for the whole form? | 4319 4320 4321 4322 4323 $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: | 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 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. | 4344 plugin.commands.ajax = (function(){ |
Create an object that contains all of our data and functionality. | 4348 var command = {}; |
This are the command defaults: | 4352 4353 4354 4355 4356 4357 plugin.addCommandDefaults('ajax', { 'animation': 'slide', 'speed': 250, 'easing': 'linear', 'when': 'click' }); |
The execute function is launched whenever this command is executed: | 4361 4362 4363 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: | 4367 4368 4369 4370 4371 4372 4373 if (options.href != undefined && options.href != ''){ var href = options.href; } else { var href = $that.attr('href'); } if (options.when == 'load' || options.when == 'viewport' || options.when == 'shown'){ |
If the option when is **load*, than we’re just loading the content: | 4377 4378 4379 4380 if (options.when == 'load'){ $that.load(href, function(){ plugin.triggerEvent('complete', $that, options); }); |
If it’s viewport or shown, we’re going to wait till the content enters the viewport or is being shown (think resonsive) before we load the content or the image (lazy load), whatever our options say: | 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 } else { var myInterval = setInterval(function(){ if ( (options.when == 'viewport' && ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport)) || (options.when == 'shown' && $that.css('display') != 'none') ){ if (options.src != undefined){ $that.attr('src', options.src); plugin.triggerEvent('complete', $that, options); } else { $that.load(href, function(){ plugin.init($that); plugin.triggerEvent('complete', $that, options); }); } window.clearInterval(myInterval); } },100); } |
This is our default use case, load the content on click: | 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 } 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. | 4417 var tempid = plugin.settings.prefix+'_ajax_temp_'+$.fn.jKit_getUnixtime(); |
Hide the affected element: | 4421 $(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: | 4425 4426 4427 4428 4429 $(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: | 4433 $('#'+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: | 4438 4439 $(options.element).html( $('#'+tempid+' '+options.element).html() ); plugin.init($(options.element)); |
Trigger some stuff and show the content we just added: | 4443 4444 4445 4446 4447 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: | 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 $('#'+tempid).remove(); }); }); }; return command; }()); |
Command TemplateThis is a template for commands. It should be used as a starting point to create new commands. | 4468 plugin.commands.hide = (function(){ |
Create an object that contains all of our data and functionality. | 4472 var command = {}; |
This are the command defaults: | 4476 4477 4478 4479 4480 4481 plugin.addCommandDefaults('hide', { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }); |
The execute function is launched whenever this command is executed: | 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 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. | 4504 plugin.commands.fontsize = (function(){ |
Create an object that contains all of our data and functionality. | 4508 var command = {}; |
This are the command defaults: | 4512 4513 4514 4515 4516 4517 4518 plugin.addCommandDefaults('fontsize', { 'steps': 2, 'min': 6, 'max': 72, 'affected': 'p', 'style': 'font-size' }); |
The execute function is launched whenever this command is executed: | 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 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. | 4553 plugin.commands.remove = (function(){ |
Create an object that contains all of our data and functionality. | 4557 var command = {}; |
This are the command defaults: | 4561 4562 4563 plugin.addCommandDefaults('remove', { 'delay': 0 }); |
The execute function is launched whenever this command is executed: | 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 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!!! | 4586 plugin.commands.loop = (function(){ |
Create an object that contains all of our data and functionality. | 4590 var command = {}; |
This are the command defaults: | 4594 4595 4596 4597 4598 4599 4600 4601 4602 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: | 4606 4607 4608 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. | 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 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. | 4640 plugin.commands.ticker = (function(){ |
Create an object that contains all of our data and functionality. | 4644 var command = {}; |
This are the command defaults: | 4648 4649 4650 4651 4652 plugin.addCommandDefaults('ticker', { 'speed': 100, 'delay': 2000, 'loop': 'yes' }); |
The execute function is launched whenever this command is executed: | 4656 4657 4658 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: | 4662 4663 4664 4665 4666 4667 4668 4669 4670 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: | 4674 4675 4676 4677 4678 var $newThat = $('<div/>'); $that.replaceWith($newThat); window.setTimeout( function() { ticker($newThat, options, messages, 0, 0); }, 0); }; |
The ticker function runs the ticker. | 4682 var ticker = function($el, options, messages, currentmessage, currentchar){ |
The stopped variable is used in case the ticker isn’t looped: | 4686 var stopped = false; |
We only run the ticker animation if the element is inside the viewport and the window in focus: | 4690 4691 4692 4693 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: | 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 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: | 4721 4722 4723 4724 4725 4726 4727 4728 } 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: | 4732 4733 4734 4735 4736 4737 4738 4739 4740 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. | 4748 plugin.commands.carousel = (function(){ |
Create an object that contains all of our data and functionality. | 4752 var command = {}; |
This are the command defaults: | 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 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: | 4769 4770 4771 4772 4773 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: | 4777 4778 4779 4780 4781 4782 $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: | 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 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: | 4800 4801 plugin.addKeypressEvents($prevdiv, 'left'); plugin.addKeypressEvents($nextdiv, 'right'); |
Start autoplay if needed: | 4805 4806 4807 4808 4809 if (options.autoplay == 'yes'){ window.setTimeout( function() { carousel($that, options); }, options.interval); } }; |
The carousel function moves the carousel either one forward, or one backward. | 4814 carousel = function($el, options, dir){ |
Every manual interaction stops the autoplay: | 4818 4819 4820 if (dir != undefined){ options.autoplay = false; } |
Only run the carousel if we’re inside the viewport and the window has focus: | 4824 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: | 4828 4829 4830 4831 4832 4833 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: | 4837 if (!isAnimated) { |
What number is the last element? | 4841 var pos = Math.min(options.limit, $el.children().length); |
Step one forward: | 4845 4846 4847 4848 4849 4850 4851 4852 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: | 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 } 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: | 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 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. | 4890 plugin.commands.paginate = (function(){ |
Create an object that contains all of our data and functionality. | 4894 var command = {}; |
This are the command defaults: | 4898 4899 4900 4901 4902 4903 4904 4905 4906 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: | 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 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. | 4934 4935 4936 4937 4938 4939 4940 4941 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 4973 4974 4975 4976 4977 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. | 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 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 … | 5028 5029 5030 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. | 5038 plugin.commands.summary = (function(){ |
Create an object that contains all of our data and functionality. | 5042 var command = {}; |
This are the command defaults: | 5046 5047 5048 5049 5050 5051 5052 5053 plugin.addCommandDefaults('summary', { 'what': '', 'linked': 'yes', 'from': '', 'scope': 'children', 'style': 'ul', 'indent': 'no' }); |
The execute function is launched whenever this command is executed: | 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 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. | 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 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: | 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 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: | 5128 5129 5130 5131 5132 5133 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: | 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 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. | 5163 plugin.commands.gallery = (function(){ |
Create an object that contains all of our data and functionality. | 5167 var command = {}; |
This are the command defaults: | 5171 5172 5173 5174 5175 5176 5177 5178 5179 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: | 5183 5184 5185 5186 command.execute = function($that, options){ var s = plugin.settings; var type = 'gallery'; |
First get all images into an array: | 5190 var images = $that.children(); |
Now put the active image only into the original element: | 5194 $that.html($that.children(':nth-child('+options.active+')').clone()); |
In case we need additional lightbox functionality, add it: | 5198 5199 5200 if (options.lightbox == 'yes'){ plugin.executeCommand($that.find('img'), 'lightbox', {}); } |
Create the element that will contain the thumbnails and insert it after the gallery: | 5204 5205 5206 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: | 5210 5211 5212 5213 5214 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. | 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 $.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. | 5269 plugin.commands.background = (function(){ |
Create an object that contains all of our data and functionality. | 5273 var command = {}; |
This are the command defaults: | 5277 5278 5279 plugin.addCommandDefaults('background', { 'distort': 'no' }); |
The execute function is launched whenever this command is executed: | 5283 5284 5285 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: | 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 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: | 5308 scaleFit($bg, $that, ow, oh, options.distort); |
Rescale the image in case the window size changes: | 5312 5313 5314 5315 5316 5317 $(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. | 5323 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. | 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 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: | 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 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. | 5375 plugin.commands.live = (function(){ |
Create an object that contains all of our data and functionality. | 5379 var command = {}; |
This are the command defaults: | 5383 5384 5385 plugin.addCommandDefaults('live', { 'interval': 60 }); |
The execute function is launched whenever this command is executed: | 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 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. | 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 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. | 5426 plugin.commands.lightbox = (function(){ |
Create an object that contains all of our data and functionality. | 5430 5431 5432 var command = {}; var lightboxes = {}; |
This are the command defaults: | 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 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: | 5452 5453 5454 5455 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: | 5461 5462 5463 5464 5465 5466 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: | 5470 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. | 5476 5477 5478 5479 5480 5481 if (options.group != ''){ if (lightboxes[options.group] == undefined){ lightboxes[options.group] = []; } lightboxes[options.group].push($that); } |
A lightbox will always open on click: | 5485 5486 5487 $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: | 5492 5493 5494 5495 5496 5497 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: | 5501 5502 5503 5504 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: | 5509 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: | 5514 5515 5516 5517 5518 5519 5520 5521 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: | 5525 5526 5527 5528 5529 5530 5531 5532 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: | 5536 5537 5538 5539 5540 5541 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. | 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 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: | 5587 5588 5589 5590 5591 5592 5593 5594 $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: | 5599 5600 5601 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. | 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 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: | 5654 5655 5656 5657 5658 $('.'+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: | 5662 5663 5664 5665 5666 5667 5668 return false; }); } }; |
The closeLightbox function is used to close the active lightbox programmatically from inside the lightbox content. | 5673 5674 5675 5676 5677 5678 5679 5680 5681 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. | 5689 plugin.commands.menu = (function(){ |
Create an object that contains all of our data and functionality. | 5693 var command = {}; |
This are the command defaults: | 5697 5698 5699 plugin.addCommandDefaults('menu', { 'autoactive': 'no' }); |
The execute function is launched whenever this command is executed: | 5703 5704 5705 command.execute = function($that, options){ var s = plugin.settings; |
Add an active class to the menu link that matches the current page url: | 5709 5710 5711 5712 5713 5714 5715 5716 5717 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: | 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 $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; }()); |
Now as all included plugin commands are defined, we add the keys of them to the internal inc array so that the special info command can display them. | 5751 5752 5753 5754 5755 for (x in plugin.commands){ if (x != 'init'){ plugin.inc.push(x); } } |
Start the plugin by running the initialization function: | 5760 5761 5762 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. | 5774 $.fn.jKit_effect = function(show, type, speed, easing, delay, fn){ |
This is a real jQuery plugin, so make sure chaining works: | 5778 return this.each(function() { |
Do we have to call a callback function? If not, just create an empty one: | 5782 if (fn == undefined) fn = function(){}; |
If we didn’t set a delay, set the delay variable to zero: | 5786 if (delay == undefined) delay = 0; |
We now have all we need, so run the animation we need: | 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 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. | 5824 5825 5826 5827 5828 $.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. | 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 $.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. | 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 $.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. | 5876 5877 5878 5879 $.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. | 5887 5888 5889 5890 $.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. | 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 $.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. | 5917 5918 5919 5920 5921 5922 5923 5924 $.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. | 5932 5933 5934 5935 5936 5937 5938 5939 5940 $.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. | 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 $.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. | 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 $.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. | 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 $.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. | 6019 6020 6021 6022 6023 6024 6025 6026 6027 $.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. | 6034 6035 6036 $.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. | 6043 6044 6045 6046 $.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. | 6053 6054 6055 6056 $.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. | 6063 6064 6065 6066 $.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. | 6073 6074 6075 6076 $.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. | 6083 6084 6085 $.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. | 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 $.fn.jKit = function(options, moreoptions) { return this.each(function() { var plugin = new $.jKit(this, options, moreoptions); $(this).data('jKit', plugin); }); }; })(jQuery); |