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 prefix: 'jkit', dataAttribute: 'data-jkit', activeClass: 'active', errorClass: 'error', successClass: 'success', ignoreFocus: false, ignoreViewport: false, keyNavigation: true, touchNavigation: true, plugins: {}, replacements: {}, delimiter: ',', |
codeblock: macros | |
Now we set some default macros for often used command/parameter combinations: | 90 91 92 93 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. | 100 commands: { |
codeblock: command.template | |
104 105 106 107 108 109 'template': { 'action': 'set', 'name': 'template', 'dynamic': 'no', 'addhtml': '+' }, | |
codeblock: /command.template, command.lightbox | |
113 114 115 116 117 118 119 120 121 122 123 124 125 'lightbox': { 'speed': 500, 'opacity': 0.7, 'clearance': 200, 'closer': 'x', 'next': '>', 'prev': '<', 'modal': 'no', 'width': '', 'height': '', 'titleHeight': 20, 'group': '' }, | |
codeblock: /command.lightbox, command.scroll | |
129 130 131 132 133 'scroll': { 'speed': 500, 'dynamic': 'yes', 'easing': 'linear' }, | |
codeblock: /command.scroll, command.hide | |
137 138 139 140 141 142 'hide': { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }, | |
codeblock: /command.hide, command.remove | |
146 147 148 'remove': { 'delay': 0 }, | |
codeblock: /command.remove, command.show | |
152 153 154 155 156 157 'show': { 'delay': 0, 'speed': 500, 'animation': 'fade', 'easing': 'linear' }, | |
codeblock: /command.show, command.showandhide | |
161 162 163 164 165 166 167 'showandhide': { 'delay': 0, 'speed': 500, 'duration': 10000, 'animation': 'fade', 'easing': 'linear' }, | |
codeblock: /command.showandhide, command.loop | |
171 172 173 174 175 176 177 178 179 'loop': { 'speed1': 500, 'speed2': 500, 'duration1': 2000, 'duration2': 2000, 'easing1': 'linear', 'easing2': 'linear', 'animation': 'fade' }, | |
codeblock: /command.loop, command.random | |
183 184 185 186 'random': { 'count': 1, 'remove': 'yes' }, | |
codeblock: /command.random, command.partially | |
190 191 192 193 194 195 'partially': { 'height': 200, 'text': 'more ...', 'speed': 250, 'easing': 'linear' }, | |
codeblock: /command.partially, command.slideshow | |
199 200 201 202 203 204 205 206 'slideshow': { 'shuffle': 'no', 'interval': 3000, 'speed': 250, 'animation': 'fade', 'easing': 'linear', 'on': '' }, | |
codeblock: /command.slideshow, command.animation | |
210 211 212 213 214 215 216 217 218 219 'animation': { 'fps': 25, 'loop': 'no', 'from': '', 'to': '', 'speed': '500', 'easing': 'linear', 'delay': 0, 'on': '' }, | |
codeblock: /command.animation, command.gallery | |
223 224 225 226 227 228 229 230 231 'gallery': { 'active': 1, 'event': 'click', 'showcaptions': 'yes', 'animation': 'none', 'speed': 500, 'easing': 'linear', 'lightbox': 'no' }, | |
codeblock: /command.gallery, command.tabs | |
235 236 237 238 239 240 'tabs': { 'active': 1, 'animation': 'none', 'speed': 250, 'easing': 'linear' }, | |
codeblock: /command.tabs, command.accordion | |
244 245 246 247 248 249 'accordion': { 'active': 1, 'animation': 'slide', 'speed': 250, 'easing': 'linear' }, | |
codeblock: /command.accordion, command.carousel | |
253 254 255 256 257 258 259 260 261 262 'carousel': { 'autoplay': "yes", 'limit': 5, 'animation': 'grow', 'speed': 250, 'easing': 'linear', 'interval': 5000, 'prevhtml': '<', 'nexthtml': '>' }, | |
codeblock: /command.carousel, command.parallax | |
266 267 268 269 270 271 'parallax': { 'strength': 5, 'axis': 'x', 'scope': 'global', 'detect': 'mousemove' }, | |
codeblock: /command.parallax, command.form | |
275 276 277 'form': { 'validateonly': 'no' }, | |
codeblock: /command.form, command.plugin | |
281 282 283 'plugin': { 'script': '' }, | |
codeblock: /command.plugin, command.tooltip | |
287 288 289 290 291 292 'tooltip': { 'text': '', 'color': '#fff', 'background': '#000', 'classname': '' }, | |
codeblock: /command.tooltip, command.background | |
296 297 298 'background': { 'distort': 'no' }, | |
codeblock: /command.background, command.lorem | |
302 303 304 305 306 'lorem': { 'paragraphs': 0, 'length': '', 'random': 'no' }, | |
codeblock: /command.lorem, command.binding | |
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 'binding': { 'selector': '', 'source': 'val', 'variable': '', 'mode': 'text', 'interval': 100, 'math': '', 'condition': '', 'if': '', 'else': '', 'speed': 0, 'easing': 'linear', 'search': '', 'trigger': 'no', 'accuracy': '', 'min': '', 'max': '' }, | |
codeblock: /command.binding, command.limit | |
331 332 333 334 335 336 337 338 'limit': { 'elements': 'children', 'count': 5, 'animation': 'none', 'speed': 250, 'easing': 'linear', 'endstring': '...' }, | |
codeblock: /command.limit, command.chart | |
342 343 344 345 346 347 'chart': { 'max': 0, 'delaysteps': 100, 'speed': 500, 'easing': 'linear' }, | |
codeblock: /command.chart, command.encode | |
351 352 353 354 'encode': { 'format': 'code', 'fix': 'yes' }, | |
codeblock: /command.encode, command.split | |
358 359 360 361 362 363 'split': { 'separator': '', 'container': 'span', 'before': '', 'after': '' }, | |
codeblock: /command.split, command.live | |
367 368 369 'live': { 'interval': 60 }, | |
codeblock: /command.live, command.key | |
373 'key': {}, | |
codeblock: /command.key, command.ajax | |
377 378 379 380 381 382 'ajax': { 'animation': 'slide', 'speed': 250, 'easing': 'linear', 'when': 'click' }, | |
codeblock: /command.ajax, command.replace | |
386 387 388 389 390 'replace': { 'modifier': 'g', 'search': '', 'replacement': '' }, | |
codeblock: /command.replace, command.cycle | |
394 395 396 397 398 399 'cycle': { 'what': 'class', 'where': 'li', 'scope': 'children', 'sequence': 'odd,even' }, | |
codeblock: /command.cycle, command.fontsize | |
403 404 405 406 407 408 409 'fontsize': { 'steps': 2, 'min': 6, 'max': 72, 'affected': 'p', 'style': 'font-size' }, | |
codeblock: /command.fontsize, command.swap | |
413 414 415 416 'swap': { 'versions': '_off,_on', 'attribute': 'src' }, | |
codeblock: /command.swap, command.ticker | |
420 421 422 423 424 'ticker': { 'speed': 100, 'delay': 2000, 'loop': 'yes' }, | |
codeblock: /command.ticker, command.sort | |
428 429 430 431 432 433 'sort': { 'what': 'text', 'by': '', 'start': 0, 'end': 0 }, | |
codeblock: /command.sort, command.zoom | |
437 438 439 440 441 'zoom': { 'scale': 2, 'speed': 150, 'lightbox': 'no' }, | |
codeblock: /command.zoom, command.api | |
445 446 447 448 449 450 451 'api': { 'format': 'json', 'value': '', 'url': '', 'interval': -1, 'template': '' }, | |
codeblock: /command.api, command.filter | |
455 456 457 458 459 460 461 462 463 'filter': { 'by': 'class', 'affected': '', 'animation': 'slide', 'speed': 250, 'easing': 'linear', 'logic': 'and', 'global': 'no' }, | |
codeblock: /command.filter, command.summary | |
467 468 469 470 471 472 473 474 'summary': { 'what': '', 'linked': 'yes', 'from': '', 'scope': 'children', 'style': 'ul', 'indent': 'no' }, | |
codeblock: /command.summary, command.paginate | |
478 479 480 481 482 483 484 485 486 'paginate': { 'limit': '25', 'by': 'node', 'container': '', 'animation': 'none', 'speed': 250, 'easing': 'linear', 'pos': 'after' }, | |
codeblock: /command.paginate, command.menu | |
490 491 492 'menu': { 'autoactive': 'no' }, | |
codeblock: /command.menu | |
To make our code block funtionalllity not brake anything, we have to add an empty entry at the end: | 498 499 500 501 '':{} } }; |
Set an alias to this so that we can use it everywhere inside our plugin: | 505 var plugin = this; |
Create an object for the plugin settings: | 509 plugin.settings = {}; |
And while were’re at it, cache the DOM element: | 513 514 var $element = $(element), element = element; |
In case we are just applying a single command, we need to take the options from the moreoptions parameter: | 518 519 520 521 522 523 524 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: | 528 529 530 531 532 533 var startX, startY; var windowhasfocus = true; var uid = 0; var lightboxes = {}; var templates = {}; 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): | 537 538 539 540 541 542 543 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. | 558 plugin.init = function($el){ |
In case this function is called without a specific DOM node, use the plugins main DOM element: | 562 if ($el == undefined) $el = $element; |
Extend the plugin defaults with the applied options: | 566 567 568 569 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: | 573 574 575 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. | 581 582 583 $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): | 587 588 589 590 591 592 593 594 595 596 597 var rel = $(this).attr('rel'); var data = $(this).attr(s.dataAttribute); if (data != undefined){ rel = $.trim(data).substring(1); } else { rel = $.trim(rel).substring(5); } rel = rel.substring(0, rel.length-1); rel = rel.replace(/]s+[/g, "]["); relsplit = rel.split(']['); |
Now look at each command seperately: | 601 $.each( relsplit, function(index, value){ |
First convert all the escaped characters into internal jKit strings. Later we convert them back and unescape them. | 605 606 607 608 609 610 611 612 613 614 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: | 618 if (s.macros[value] != undefined) value = s.macros[value]; |
Now it’s time to parse the options: | 622 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: | 626 627 628 629 630 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: | 634 635 636 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: | 640 641 642 643 644 645 646 647 648 649 650 651 } else if (options.type == 'repeat' && relsplit[index-1] != undefined){ var prevoptions = plugin.parseOptions(relsplit[index-1]); $el.on( options.onevent, function(){ if (options.delay == undefined) options.delay = 0; setTimeout( function(){ plugin.executeCommand($(that), prevoptions.type, prevoptions); }, options.delay); }); } else { |
Looks like this isn’t one of the special use commands, so lets execute one of the regular ones. | |
If the targets option is set, we first have to find out to which target nodes we have to apply the command: | 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 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:
| 691 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. | 697 698 699 700 701 702 703 704 if (thisoptions.commandkey == undefined){ var id = $(v).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: | 709 710 711 712 713 714 715 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: | 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 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 we don’t have an event set, we execute it immediately: | 739 if (thisoptions.onevent === undefined){ |
Check if a command replacement for this command is available and if yes, call it. | 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 if (s.replacements[thisoptions.type] != undefined && typeof(s.replacements[thisoptions.type]) === "function"){ s.replacements[thisoptions.type].call(plugin, v, thisoptions.type, thisoptions); } else { plugin.executeCommand(v, thisoptions.type, thisoptions); } } }); } }); }); } }; |
applyMacroThe applyMacro function lets us execute predefined macros. | 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 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):
| 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 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. | 827 828 829 830 831 832 833 834 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. | 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 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. | 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 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. | 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 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 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. | 989 990 991 992 993 994 995 996 997 998 999 1000 1001 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. | 1007 1008 1009 1010 plugin.executeCommand = function(that, type, options){ var s = plugin.settings; var $that = $(that); |
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. | 1015 $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) | 1019 1020 1021 1022 1023 1024 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: | 1028 1029 1030 options = plugin.addDefaults(type, options); $.each( options, function(i,v){ |
Convert jKit’s special escaping strings to their regular characters: | 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 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): | 1047 1048 1049 1050 1051 1052 1053 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); } } }); |
CommandsDepending on the type of command, different actions are executed. | 1059 switch(type){ |
codeblock: command-paginate | |
Paginate CommandThe paginate command lets you create paginated content. | 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 case 'paginate': if (options.container != ''){ var $container = $that.find(options.container); } else { var $container = $that; } if ($that.attr('id') !== undefined){ var paginateid = s.prefix+'-'+type+'-'+$that.attr('id'); } else { var paginateid = s.prefix+'-'+type+'-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. | 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 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. | 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 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); }); } break; |
codeblock: /command-paginate, command-filter | |
Filter CommandThe filter command lets you filter DOM nodes based on some input. | 1189 case 'filter': |
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. | 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 $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); plugin.filterElements($that, options); } }); }); |
In case there’s already a filter value set, we need to trigger the filtering right now: | 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 $that.find('.jkit-filter').each( function(){ if ($.trim($(this).val()) != ''){ if (options.loader !== undefined) $(options.loader).show(); plugin.triggerEvent('clicked', $that, options); plugin.filterElements($that, options); return false; } }); break; |
codeblock: /command-paginate, command-summary | |
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. | 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 case 'summary': 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. | 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 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: | 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 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: | 1307 1308 1309 1310 1311 1312 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: | 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 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' }); } } } break; |
codeblock: /command-summary, command-api | |
API CommandThe API command lets you use JSON based API’s to display external data. Check the plugin.readAPI for how it’s done. | 1340 1341 1342 1343 1344 1345 1346 case 'api': if (options.url != ''){ plugin.readAPI($that, options); } break; |
codeblock: /command-api, command-zoom | |
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. | 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 case 'zoom': $that.parent().css('position', 'relative'); $that.on( 'mouseover', function(){ var pos = $that.position(); var height = $that.height(); var width = $that.width(); $zoom = $('<div/>', { 'class': s.prefix+'-'+type+'-overlay' }).css( { 'position': 'absolute', 'height': height+'px', 'width': width+'px', 'left': pos.left + 'px', 'top': pos.top + 'px', 'overflow': 'hidden', 'background-image': 'url('+$that.attr('src')+')', 'background-repeat': 'no-repeat', 'background-color': '#000', 'opacity': 0 }).on( 'mouseout', function(){ $zoom.fadeTo(options.speed, 0, function(){ $zoom.remove(); plugin.triggerEvent('zoomout', $that, options); }); }).mousemove(function(e){ |
Detect the mouse poition relative to the selected image: | 1389 1390 1391 1392 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: | 1396 1397 1398 1399 1400 $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: | 1404 1405 1406 1407 1408 1409 1410 if (options.lightbox == 'yes'){ plugin.executeCommand($zoom, 'lightbox', {}); } }); break; |
codeblock: /command-zoom, command-sort | |
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. | 1422 case 'sort': |
First we need to know the exact position of the current TH inside the heading TR, the index: | 1426 1427 1428 1429 1430 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: | 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 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. | 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 if ($that.hasClass(s.prefix+'-'+type+'-down')){ $that.parent().find('th').removeClass(s.prefix+'-'+type+'-down').removeClass(s.prefix+'-'+type+'-up'); $that.addClass(s.prefix+'-'+type+'-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+'-'+type+'-down').removeClass(s.prefix+'-'+type+'-up'); $that.addClass(s.prefix+'-'+type+'-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: | 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 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); }); break; |
codeblock: /command-sort, command-ticker | |
Ticker CommandThe ticker command goes through each item of a list and reveals the item one character at a time. | 1538 1539 1540 case 'ticker': var containerTag = plugin.findElementTag($that, '>', 'max', 'li'); |
Create an array with objects that contain all useful information of a single ticker item: | 1544 1545 1546 1547 1548 1549 1550 1551 1552 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: | 1556 1557 1558 1559 1560 var $newThat = $('<div/>'); $that.replaceWith($newThat); window.setTimeout( function() { plugin.ticker($newThat, options, messages, 0, 0); }, 0); break; |
codeblock: /command-ticker, command-swap | |
Swap CommandThe swap command replaces a DOM node attribute, for example an image, with another value on hover. | 1571 1572 1573 case 'swap': var versions = options.versions.split(s.delimiter); |
We have to store the original attributes value to swap the attribute back on mouseleave: | 1577 1578 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: | 1582 1583 1584 if (options.attribute == 'src'){ $('<img/>')[0].src = replacement; } |
Finally, add the two event handlers with the swapping code: | 1588 1589 1590 1591 1592 1593 1594 1595 1596 $that.mouseenter(function(){ $that.attr(options.attribute, replacement ); plugin.triggerEvent('active', $that, options); }).mouseleave(function(){ $that.attr(options.attribute, original ); plugin.triggerEvent('inactive', $that, options); }); break; |
codeblock: /command-swap, command-fontsize | |
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. | 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 case 'fontsize': $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; }); break; |
codeblock: /command-fontsize, command-fontsize | |
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. | 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 case 'cycle': 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: | 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 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; }); break; |
codeblock: /command-cycle, command-replace | |
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! | 1685 1686 1687 1688 1689 1690 case 'replace': var str = new RegExp(options.search, options.modifier); $that.html($that.html().replace(str,options.replacement)); break; |
codeblock: /command-replace, command-replace | |
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. | 1701 case 'ajax': |
If the href option is set, take it from the option, if not, take it from our element: | 1705 1706 1707 1708 1709 1710 1711 if (options.href != undefined && options.href != ''){ var href = options.href; } else { var href = $that.attr('href'); } if (options.when == 'load' || options.when == 'viewport'){ |
If the option when is **load*, than we’re just loading the content: | 1715 1716 1717 1718 if (options.when == 'load'){ $that.load(href, function(){ plugin.triggerEvent('complete', $that, options); }); |
If it’s viewport, we’re going to wait till the content enters the viewport before we load the content or the image (lazy load), whatever our options say: | 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 } else { var myInterval = setInterval(function(){ if ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport){ if (options.src != undefined){ $that.attr('src', options.src); plugin.triggerEvent('complete', $that, options); } else { $that.load(href, function(){ plugin.triggerEvent('complete', $that, options); }); } window.clearInterval(myInterval); } },100); } |
This is our default use case, load the content on click: | 1741 1742 1743 1744 1745 1746 1747 1748 } else { $that.on('click', function(){ plugin.loadAndReplace(href, options, $that); return false; }); } break; |
codeblock: /command-ajax, command-key | |
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. | 1761 1762 1763 case 'key': if (options.code != undefined){ |
First we need to add the event handling for this keycode to the element … | 1767 plugin.addKeypressEvents($that, options.code); |
Because only now we can listen to it: | 1771 1772 1773 1774 1775 $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: | 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 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); }); } break; |
codeblock: /command-key, command-live | |
Live CommandThe live command is very simple. All it does is reload the source of an image or iframe in a certain interval and making sure that it doesn’t load the cashed version. | 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 case 'live': if ($that.attr('src') !== undefined) { window.setInterval( function() { plugin.updateSrc($that, options); plugin.triggerEvent('reloaded', $that, options); }, options.interval*1000); } break; |
codeblock: /command-live, command-split | |
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. | 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 case 'split': 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); break; |
codeblock: /command-split, command-encode | |
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. | 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 case 'encode': switch(options.format) { case 'code': var src = $that.html(); if (options.fix == 'yes'){ src = plugin.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; } break; |
codeblock: /command-encode, command-chart | |
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. | 1878 case 'chart': |
First get the main label from the THEAD and the main element id: | 1882 1883 var label = $that.find('thead > tr > th.label').text(); var id = $that.attr('id'); |
Now get all data column labels from the THEAD | 1887 1888 1889 1890 1891 1892 1893 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! | |
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 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: | 1916 1917 1918 if (options.max > 0 && max < options.max){ max = options.max; } |
Time to construct our chart element: | 1922 1923 1924 1925 var $chart = $('<div/>', { id: id, 'class': s.prefix+'-'+type }); |
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. | 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 var steps = 0; var delay = 0; $.each(datalabels, function(i,v){ steps++; var $step = $('<div/>', { 'class': s.prefix+'-'+type+'-step' }).html('<label>'+v+'</label>').appendTo($chart); $.each( plots, function(i2,v2){ if (plots[i2].data[i] > 0){ var $plot = $('<div/>', { 'class': s.prefix+'-'+type+'-plot '+s.prefix+'-'+type+'-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+'-'+type+'-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: | 1970 1971 1972 $that.replaceWith($chart); break; |
codeblock: /command-chart, command-lightbox | |
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. | 1984 case '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: | 1990 1991 1992 1993 1994 1995 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: | 1999 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. | 2005 2006 2007 2008 2009 2010 if (options.group != ''){ if (lightboxes[options.group] == undefined){ lightboxes[options.group] = []; } lightboxes[options.group].push(that); } |
A lightbox will always open on click: | 2014 2015 2016 $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: | 2021 2022 2023 2024 2025 2026 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: | 2030 2031 2032 2033 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: | 2038 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: | 2043 2044 2045 2046 2047 2048 2049 2050 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: | 2054 2055 2056 2057 2058 2059 2060 2061 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: | 2065 2066 2067 2068 2069 2070 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. | 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 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: | 2116 2117 2118 2119 2120 2121 2122 2123 $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: | 2128 2129 2130 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. | 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 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: | 2183 2184 2185 2186 2187 $('.'+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: | 2191 2192 2193 2194 2195 2196 2197 return false; }); } break; |
codeblock: /command-lightbox, command-scroll | |
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. | 2208 2209 2210 2211 2212 case 'scroll': $that.click(function() { plugin.triggerEvent('clicked', $that, options); |
Get the position of our target element: | 2216 2217 2218 2219 2220 if ($(this).attr("href") == ''){ var ypos = 0; } else { var ypos = $($that.attr("href")).offset().top; } |
The dynamic option changes the scroll animation duration based on the distance between us and the target element: | 2225 2226 2227 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: | 2231 2232 2233 2234 2235 2236 2237 2238 2239 $('html, body').animate({ scrollTop: ypos+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('complete', $that, options); }); return false; }); break; |
codeblock: /command-scroll, command-hide | |
Hide CommandThe hide command is used to hide an element, animated or not. | 2249 2250 2251 2252 2253 2254 2255 case 'hide': $that.jKit_effect(false, options.animation, options.speed, options.easing, options.delay, function(){ plugin.triggerEvent('complete', $that, options); }); break; |
codeblock: /command-hide, command-remove | |
Remove CommandThe remove command is used to completely remove the element from the DOM. | 2266 2267 2268 2269 2270 2271 2272 2273 case 'remove': $that.delay(options.delay).hide(0, function(){ $that.remove(); plugin.triggerEvent('complete', $that, options); }); break; |
codeblock: /command-remove, command-show | |
Show CommandThe show command is used to reveal an element, animated or not. | 2283 2284 2285 2286 2287 2288 2289 case 'show': $that.hide().jKit_effect(true, options.animation, options.speed, options.easing, options.delay, function(){ plugin.triggerEvent('complete', $that, options); }); break; |
codeblock: /command-show, command-showandhide | |
Showandhide CommandThe showandhide command is used to reveal an element and than hide it again, animated or not. | 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 case 'showandhide': $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); }); }); break; |
codeblock: /command-showandhide, command-loop | |
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!!! | 2320 2321 2322 2323 2324 case 'loop': plugin.loop($that.hide(), options); break; |
codeblock: /command-loop, command-random | |
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. | 2336 2337 2338 2339 case 'random': var childs = $that.children().size(); var shownrs = []; |
Create an array of index numbers of our randomly selected elements: | 2343 2344 2345 2346 2347 2348 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: | 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 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++; }); break; |
codeblock: /command-random, command-partially | |
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) | 2378 case 'partially': |
First store the original height, we need it later. | 2382 var originalHeight = $that.height(); |
Only add the magic is we need, in other words, if the lement is higher than our maximum height: | 2386 if (originalHeight > options.height){ |
We can only add our more div if it’s relatively positioned, so force that one on it: | 2390 $that.css('position', 'relative'); |
Create the more div: | 2394 2395 2396 2397 2398 var $morediv = $('<div/>') .addClass(s.prefix+'-morediv') .appendTo(that) .html(options.text) .css( { width: $that.outerWidth()+'px', opacity: 0.9 }); |
Add the evnet handlers and animations: | 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 plugin.addKeypressEvents($that, 'down'); $that.css({ 'height': options.height+'px', 'overflow': 'hidden' }).on( 'mouseenter down', function() { $morediv.fadeTo(options.speed, 0); $that.animate({ 'height': originalHeight+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('open', $that, options); }); }).on( 'mouseleave up', function(){ $morediv.fadeTo(options.speed, 0.9); $that.animate({ 'height': options.height+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('closed', $that, options); }); }); |
For touch devices that don’t fire mouseover events, we have to add an additional click event: | 2418 2419 2420 2421 2422 2423 2424 2425 2426 $morediv.on('click', function(){ $that.animate({ 'height': originalHeight+'px' }, options.speed, options.easing, function(){ plugin.triggerEvent('closed', $that, options); }); }); } break; |
codeblock: /command-partially, command-slideshow | |
Slideshow CommandThe slideshow command is being used to create slideshows of either images or any other kind of HTML content. | 2437 case 'slideshow': |
Get all slides: | 2441 var slides = $that.children(); |
If needed, shuffle the slides into a random order: | 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 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. | 2461 2462 2463 2464 $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. | 2469 2470 2471 2472 2473 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: | 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 $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() { plugin.slideshow(slides, 0, $that, options); }, 0); } } else if (options.on == 'mouseover'){ if (!$.data($that, 'anim')){ $.data($that, 'anim', true); window.setTimeout( function() { plugin.slideshow(slides, 0, $that, options); }, 0); } } }); } else { |
No event is set, so we just run the slideshow right now: | 2497 2498 2499 2500 2501 2502 $.data($that, 'anim', true); window.setTimeout( function() { plugin.slideshow(slides, 0, $that, options); }, options.interval); } break; |
codeblock: /command-slideshow, command-carousel | |
Carousel CommandThe carousel command is used to display a subset of elements like a carousel, new one in, old one out. | 2513 2514 2515 case 'carousel': var cnt = 0; |
First hide all elements that are over our limit of elements we want to show: | 2519 2520 2521 2522 2523 2524 $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: | 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 var $prevdiv = $('<a/>', { 'class': s.prefix+'-'+type+'-prev' }).html(options.prevhtml).on( 'click left', function(){ plugin.carousel($that, options, 'prev'); }).insertAfter(that); var $nextdiv = $('<a/>', { 'class': s.prefix+'-'+type+'-next' }).html(options.nexthtml).on( 'click right', function(){ plugin.carousel($that, options, 'next'); }).insertAfter(that); |
Add some additional keyboard events: | 2542 2543 plugin.addKeypressEvents($prevdiv, 'left'); plugin.addKeypressEvents($nextdiv, 'right'); |
Start autoplay if needed: | 2547 2548 2549 2550 2551 if (options.autoplay == 'yes'){ window.setTimeout( function() { plugin.carousel($that, options); }, options.interval); } break; |
codeblock: /command-carousel, command-animation | |
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. | 2563 case 'animation': |
First check if this is a CSS animation: | 2567 if (options.to != ''){ |
If the from option is set, we first have to set the initial CSS: | 2571 2572 2573 if (options.from != ''){ $that.css( plugin.cssFromString(options.from) ); } |
use setTimeout to delay the animation, even if the delay is zero: | 2577 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. | |
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 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: | 2602 2603 2604 2605 2606 2607 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. | 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 $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: | 2646 $that.html(frames[0].el); |
And now start the animation: | 2650 2651 2652 2653 2654 window.setTimeout( function() { plugin.animation(frames, -1, $that, options); }, 0); } break; |
codeblock: /command-animation, command-gallery | |
Gallery CommandThe gallery command takes a bunch of images and creates a gallery out of it. | 2665 case 'gallery': |
First get all images into an array: | 2669 var images = $that.children(); |
Now put the active image only into the original element: | 2673 $that.html($that.children(':nth-child('+options.active+')').clone()); |
In case we need additional lightbox functionality, add it: | 2677 2678 2679 if (options.lightbox == 'yes'){ plugin.executeCommand($that.find('img'), 'lightbox', {}); } |
Create the element that will contain the thumbnails and insert it after the gallery: | 2683 2684 2685 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: | 2689 2690 2691 2692 2693 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. | 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 $.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); }); break; |
codeblock: /command-gallery, command-tabs | |
Tabs CommandThe tabs command is used to create a tab navigation of different content elements. | 2747 case 'tabs': |
First try to find out which kind of HTML elements are used to structure the data: | 2751 2752 2753 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: | 2757 2758 2759 2760 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: | 2764 2765 $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: | 2769 2770 2771 var $tabcontent = $; $.each( tabs, function(index, value){ |
Create a list element and add it to the tab naviagtion: | 2775 var $litemp = $('<li/>', { }).html(value.title).css('cursor', 'pointer').appendTo($tabnav); |
Is this tab active? If yes, add the “active” class: | 2779 2780 2781 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? | |
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 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? | 2808 2809 2810 2811 2812 if (tabs[options.active-1] != undefined){ $tabcontent = tabs[options.active-1].content.appendTo($that); } break; |
codeblock: /command-tabs, command-accordion | |
Accordion CommandThe accordion command creates a content navigation that acts like an accordion. | 2823 case 'accordion': |
First try to find out which kind of HTML elements are used to structure the data: | 2827 2828 2829 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! | |
2836 2837 2838 2839 2840 2841 2842 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: | 2846 2847 2848 2849 2850 $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: | 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 $.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; } }); }); break; |
codeblock: /command-accordion, command-parallax | |
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. | 2899 2900 2901 case 'parallax': 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. | 2907 2908 2909 2910 2911 2912 2913 if (options.detect == 'scroll'){ var $capture = $(window); } else if (options.scope == 'global'){ var $capture = $(document); } else { var $capture = $that; } |
Set the correct event: | 2917 $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: | 2922 2923 if ((windowhasfocus || !windowhasfocus && s.ignoreFocus) && ($that.jKit_inViewport() || !$that.jKit_inViewport() && s.ignoreViewport)){ var cnt = 1; |
Get either the scroll or the mouse position: | 2927 2928 2929 2930 2931 2932 2933 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: | 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 $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++; }); } }); break; |
codeblock: /command-parallax, command-menu | |
Menu CommandThe menu command adds some additional features to a CSS based menu. | 2968 case 'menu': |
Add an active class to the menu link that matches the current page url: | 2972 2973 2974 2975 2976 2977 2978 2979 2980 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: | 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 $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'); }); break; |
codeblock: /command-menu, command-form | |
Form CommandThe form command can convert a regular web form into an ajax submitted form. Additionally it adds various validation options. | 3012 case 'form': |
Add a hidden field that will contain a list of required fileds so that our PHP script can check against them. | 3017 3018 3019 3020 3021 $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: | 3025 $that.on('submit', function() { |
Create an error array and remove all error nodes previously set: | 3029 3030 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? | |
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 $(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: | 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 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: | 3074 if ((required || $(this).val() != '') || options.type == 'group'){ |
Is this a valid email? | 3077 3078 3079 3080 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://)? | 3083 3084 3085 3086 if (options.type == 'url' && !$.fn.jKit_urlCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'url' } ); } |
Is this a valid date? | 3089 3090 3091 3092 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? | 3095 3096 3097 3098 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? | 3101 3102 3103 3104 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? | 3107 3108 3109 3110 if (options.type == 'time' && !$.fn.jKit_timeCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'time' } ); } |
Is this a valid phone number? | 3113 3114 3115 3116 if (options.type == 'phone' && !$.fn.jKit_phoneCheck($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'phone' } ); } |
Is this a float? | 3119 3120 3121 3122 if (options.type == 'float' && isNaN($(this).val())){ elerror = true; errors.push( { 'element': $(this), 'error': 'float' } ); } |
Is this a int? | 3125 3126 3127 3128 if (options.type == 'int' && parseInt($(this).val()) != $(this).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'int' } ); } |
min (numeric)? | 3131 3132 3133 3134 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)? | 3137 3138 3139 3140 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)? | 3143 3144 3145 3146 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)? | 3149 3150 3151 3152 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)? | 3155 3156 3157 3158 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)? | 3161 3162 3163 3164 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? | 3167 3168 3169 3170 if (options.length != undefined && $(this).val().length != options.length){ elerror = true; errors.push( { 'element': $(this), 'error': 'length' } ); } |
Is this longer than x (length)? | 3173 3174 3175 3176 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)? | 3179 3180 3181 3182 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)? | 3185 3186 3187 3188 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? | 3191 3192 3193 3194 if (options.same != undefined && $(this).val() != $(options.same).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'same' } ); } |
Is this different than x? | 3197 3198 3199 3200 if (options.different != undefined && $(this).val() != $(options.different).val()){ elerror = true; errors.push( { 'element': $(this), 'error': 'different' } ); } |
Has this file the correct extension? | 3203 3204 3205 3206 3207 3208 3209 3210 3211 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? | 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 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: | 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 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: | 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 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 … | 3260 if (errors.length == 0){ |
If this form doesn’t use an ajax submit, than just fire the “complete” event: | 3264 3265 3266 3267 3268 if (options.validateonly == "yes"){ plugin.triggerEvent('complete', $that, options); return true; |
This is an ajax submit: | 3272 3273 3274 3275 3276 3277 3278 } 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: | 3282 $that.find('input#'+s.prefix+'-requireds').val(requireds.join(s.delimiter)); |
Post send the serialized data to our form script: | 3286 3287 $.post(action, $that.serialize(), function(data, textStatus, jqXHR) { $that.find('.'+s.errorClass).hide(); |
Check if everything got through correctly: | 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 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: | 3309 3310 3311 3312 }).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: | 3316 3317 3318 3319 3320 return false; } } else { |
Do we have to display an error for the whole form? | 3324 3325 3326 3327 3328 $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: | 3332 3333 3334 3335 3336 3337 return false; } }); break; |
codeblock: /command-form, command-plugin | |
Plugin CommandThe plugin command makes it possible to add jQuery plugins that can be used the same way as jKit commands. | 3348 case 'plugin': |
First check if this is a plugin we registered on plugin init: | 3352 3353 3354 3355 3356 3357 3358 3359 3360 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: | 3364 $.ajaxSetup({ cache: true }); |
3368 if (options.script != undefined){ | |
Load the script from the server: | 3372 $.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: | 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 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: | 3392 3393 3394 $.ajaxSetup({ cache: false }); break; |
codeblock: /command-plugin, command-tooltip | |
Tooltip CommandThe tooltip command displays additional information for an element on mouseover. | 3405 case 'tooltip': |
Create the tooltip div if it doesn’t already exist: | 3409 3410 3411 3412 3413 3414 3415 if ($('div#'+s.prefix+'-tooltip').length == 0){ $('<div/>', { id: s.prefix+'-'+type }).hide().appendTo('body'); } $tip = $('div#'+s.prefix+'-'+type); |
Display the tooltip on mouseenter: | 3419 $that.on('mouseenter', function(e){ |
Has this tooltip custom styling either by class or by supplying color values? | 3423 3424 3425 3426 3427 if (options.classname != ''){ $tip.html(options.text).removeClass().css({ 'background': '', 'color': '' }).addClass(options.classname); } else { $tip.html(options.text).removeClass().css({ 'background': options.background, 'color': options.color }); } |
Correctly position the tooltip based on the mouse position: | 3431 $tip.css('top', (e.pageY+15-$(window).scrollTop())).css('left', e.pageX); |
Fix the tooltip position so that we don’t get tooltips we can’t read because their outside the window: | 3436 3437 3438 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: | 3442 3443 3444 $tip.stop(true, true).fadeIn(200); plugin.triggerEvent('open', $that, options); |
Fade out the tooltip on mouseleave: | 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 }).on('mouseleave click', function(e){ var speed = 200; if ($tip.is(':animated')){ speed = 0; } $tip.stop(true, true).fadeOut(speed); plugin.triggerEvent('closed', $that, options); }); break; |
codeblock: /command-tooltip, command-background | |
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. | 3473 case 'background': |
Create a background element with a negative z-index that is scaled to the full size of the window: | 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 var $bg = $('<div/>', { id: s.prefix+'-'+type }).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: | 3496 plugin.scaleFit($bg, $that, ow, oh, options.distort); |
Rescale the image in case the window size changes: | 3500 3501 3502 3503 3504 3505 $(window).resize(function() { plugin.scaleFit($bg, $that, ow, oh, options.distort); plugin.triggerEvent('resized', $that, options); }); break; |
codeblock: /command-background, command-lorem | |
Lorem CommandThe lorem command adds lorem ipsum text or paragraphs to your element, very usefull for “work in progress” projects. | 3516 case 'lorem': |
The lorem ipsum text: | 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 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? | 3534 3535 3536 if (options.random == "yes"){ lorem = $.fn.jKit_arrayShuffle(lorem); } |
Add a specific number of paragraphs: | 3540 3541 3542 3543 3544 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: | 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 } 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); break; |
codeblock: /command-lorem, command-binding | |
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. | 3578 3579 3580 3581 3582 case 'binding': window.setTimeout( function() { plugin.binding($that, options); }, 0); break; |
codeblock: /command-binding, command-limit | |
Limit CommandThe limit command either limts the characters of a string or the elements inside a container by a set number. | 3593 case 'limit': |
Limit the number of elements. Set speed to zero if you want to hide them immediately or use an animation: | 3598 3599 3600 3601 3602 3603 3604 3605 3606 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: | 3610 3611 3612 } else { var newtext = $that.text().substr(0,options.count); |
Add an endstring if needed: | 3616 3617 3618 3619 3620 3621 3622 3623 if (newtext != $that.text()){ newtext = newtext.substr(0,newtext.length-options.endstring.length)+options.endstring; $that.text(newtext); } } break; |
codeblock: /command-limit, command-template | |
Template CommandThe template command implements a simple templating engine. | 3634 case 'template': |
Apply a template or define a new one? | 3638 3639 3640 if (options.action == 'apply'){ $el = $that; |
Do we have to apply the template to more than one element? | 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 if (options.children != undefined && options.children != ''){ $el = $that.children(options.children); var cnt = 0; $el.each( function(){ cnt++; plugin.applyTemplate($(this), options, cnt, $el.length); }); } else { plugin.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: | 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 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(); plugin.applyTemplate($('<'+options.children+'/>').appendTo($el), options, cnt, cnt); plugin.triggerEvent('added', $that, options); }).insertAfter($that); } } else { |
Templates are stored in a “global” plugin array: | 3682 3683 3684 if (templates[options.name] == undefined){ templates[options.name] = []; } |
Define the dynamic variables: | 3688 3689 3690 3691 3692 if (options.vars == undefined){ var vars = []; } else { var vars = options.vars.split(s.delimiter); } |
Add the template to the “global” array: | 3696 3697 3698 3699 3700 templates[options.name] = { 'template': $that.detach(), 'vars': vars }; } break; |
codeblock: /command-template | |
3704 3705 3706 3707 3708 } return $that; }; | |
filterElementsThe filterElements function is used by the filter command. It’s doing the heavy lifting for the command. | 3715 plugin.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. | 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 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? | 3734 3735 3736 3737 3738 if (options.global == 'yes'){ $container = $('body'); } else { $container = $el; } |
Loop through all affected elements and check if they have to be displayed or not. | 3742 $container.find(options.affected).each( function(){ |
First create a few cashes to speed up the following loop through the filter selections: | 3746 3747 3748 3749 3750 3751 3752 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: | 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 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: | 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 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: | 3788 3789 3790 3791 3792 3793 setTimeout( function(){ if (options.loader !== undefined) $(options.loader).hide(); plugin.triggerEvent('complete', $el, options); }, options.speed); }; |
readAPIThe readAPI function is used by the API command. It is currently able to read JSONP APIs and use an optional template to display the result. | 3801 3802 3803 plugin.readAPI = function($el, options){ if (options.format == 'json'){ |
Create an ajax jsonp request: | 3807 3808 3809 3810 3811 3812 3813 3814 3815 $.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: | 3819 if (options.template != ''){ |
First we add the template HTML to our element: | 3823 $el.html(templates[options.template].template.clone().show()); |
Than we add the data to each element that has the data-jkit-api attribute: | 3827 3828 3829 3830 3831 3832 $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: | 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 $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: | 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 } 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: | 3864 3865 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: | 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 if (options.interval > -1){ setTimeout( function(){ plugin.readAPI($el, options); }, options.interval*1000); } } }); } }; |
triggerEventThe triggerEvent function is used by various commands to trigger an event on an element with the commands options added to it: | 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 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:
| 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 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; }; |
preFixThe preFix function is used by the encode command to remove unneaded tab stops from the beginning of each line of a code block. | 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 plugin.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"); }; |
tickerThe ticker function is used by the ticker command. | 3970 plugin.ticker = function($el, options, messages, currentmessage, currentchar){ |
The stopped variable is used in case the ticker isn’t looped: | 3974 var stopped = false; |
We only run the ticker animation if the element is inside the viewport and the window in focus: | 3978 3979 3980 3981 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: | 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 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: | 4009 4010 4011 4012 4013 4014 4015 4016 } 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: | 4020 4021 4022 4023 4024 if (!stopped){ window.setTimeout( function() { plugin.ticker($el, options, messages, currentmessage, currentchar); }, timer); } }; |
loadAndReplaceThe loadAndReplace function is used by the ajax command. It basically loads an urls full data and than looks for a specific element isnide that data. It than replaces that element with the same element on the current page. | 4033 plugin.loadAndReplace = function(href, options, $el){ |
Create an unique temporary id we can use to store and access our loaded content. | 4037 var tempid = plugin.settings.prefix+'_ajax_temp_'+$.fn.jKit_getUnixtime(); |
Hide the affected element: | 4041 $(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: | 4045 4046 4047 4048 4049 $(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: | 4053 $('#'+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: | 4058 4059 $(options.element).html( $('#'+tempid+' '+options.element).html() ); plugin.init($(options.element)); |
Trigger some stuff and show the content we just added: | 4063 4064 4065 4066 4067 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: | 4071 4072 4073 4074 4075 4076 4077 $('#'+tempid).remove(); }); }); }; |
updateSrcThe updateSrc function is used by the live command. It changes the src url in a way that forces the browser to reload the src from the server. | 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 plugin.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()); } }; |
applyTemplateThe applyTemplate function is used by the template command. It adds the template with all it’s options to the suoplied element. | 4103 plugin.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. | 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 var content = {}; $.each( 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: | 4122 $el.html(templates[options.name].template.clone().show()); |
Hide all elements that have an if-entry-x class. We later show them again if needed. | 4126 $el.find('[class^="if-entry-"]').hide(); |
Rename dynamic attributes so that we don’t get dublicate ids: | 4130 plugin.renameDynamicAttributes($el, cnt); |
Add the content and show hidden elements if needed: | 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 $.each( templates[options.name].vars, function(i,v){ var $subEl = $el.find('.'+v); if ($subEl.is("input") || $subEl.is("select") || $subEl.is("textarea")){ $subEl.val(content[v]); } else { $subEl.html(content[v]); } if (content[v] == undefined && $el.find('.if-'+v).length > 0){ $el.find('.if-'+v).remove(); } if (cnt == 1) $el.find('.if-entry-first').show(); if (cnt == entries) $el.find('.if-entry-last').show(); $el.find('.if-entry-nr-'+cnt).show(); }); }; |
renameDynamicAttributesThe renameDynamicAttributes function is used by the plugin.applyTemplate function. It’s used to rename attributes on dynamic elements so that we get unique elements. | 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 plugin.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); } }); }); }; |
bindingThe binding function is used by the binding command. It connects different things to other things. It’s a really powerfull function with many options. | 4195 plugin.binding = function(el, options){ |
Only run the code if the window has focus: | 4199 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. | 4204 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: | 4209 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: | 4214 4215 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: | 4219 4220 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. | 4225 4226 4227 4228 4229 if (v == 'this'){ v = el; } else if (v == 'parent'){ v = $(el).parent().get(0); } |
A jQuery selector string can match more than one string, so run through all of them: | 4233 $(v).each( function(){ |
The source option defines from where exactly we get our value. There are quite a few options. | 4238 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. | 4243 4244 4245 4246 4247 4248 4249 4250 4251 case 'event': $(this).on( sourcesplit[1], function(e){ options.value = 1; plugin.binding(el, options); if (options.macro != undefined) plugin.applyMacro($(el), options.macro); }); break; |
“html” will get the HTML of the element: | 4255 4256 4257 4258 4259 case 'html': var temp = $(this).html(); break; |
“text” will get the putre text of the element: | 4263 4264 4265 4266 4267 case 'text': var temp = $(this).text(); break; |
“attr” will get a specific attribute that is specified after the dot, for example attr.id: | 4272 4273 4274 4275 4276 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. | 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 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: | 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 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. | 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 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: | 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 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 | 4384 4385 4386 4387 4388 case 'location': var temp = window.location[sourcesplit[1]]; break; |
“val” will get the value of the element: | 4392 4393 4394 4395 4396 4397 4398 4399 4400 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. | 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 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. | 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 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). | 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 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. | 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 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: | 4495 4496 4497 4498 4499 4500 4501 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: | 4505 if (doit){ |
The math option lets us do some additional calculation on our value: | 4509 4510 4511 if (options.math != ''){ eval('value = '+options.math.replace(/[^a-zA-Z 0-9+-*/.]+/g, '')+';'); } |
Do we have to trigger some additional events? | 4515 4516 4517 4518 4519 4520 4521 4522 4523 if (options.trigger == 'yes'){ if (commandkeys[options.commandkey]['triggervalue'] == undefined || commandkeys[options.commandkey]['triggervalue'] != value){ if (commandkeys[options.commandkey]['triggervalue'] !== undefined){ plugin.triggerEvent('notvalue'+commandkeys[options.commandkey]['triggervalue'], $(el), options); } plugin.triggerEvent('value'+value, $(el), options); commandkeys[options.commandkey]['triggervalue'] = value; } } |
The mode option defines what we have to do with our value. There are quite a few options. The attr and css modes take a second option that is separated with a dot. | 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 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: | 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 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: | 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 if (modesplit[0] != undefined){ var fn = window[modesplit[0]]; if(typeof fn === 'function') { fn(value,el); } } } } } |
Do we have to set an interval? | 4582 4583 4584 4585 4586 if (options.interval != -1){ window.setTimeout( function() { plugin.binding(el, options); }, options.interval); } }; |
loopThe loop function is used by the loop command and basically just shows and hides and element and than starts the next interval. | 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 plugin.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, plugin.loop($that, options)); }); } else { window.setTimeout( function() { plugin.loop($that, options); }, 100); } }; |
scaleFitThe scaleFit function is used by the background command. It calculates the correct with, height of the image relative to the window and the correct position inside that window based on those dimensions. | 4618 plugin.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. | 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 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: | 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 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' }); }; |
carouselThe carousel function is used by the carousel command. It moves the carousel either one forward, or one backward. | 4667 plugin.carousel = function($el, options, dir){ |
Every manual interaction stops the autoplay: | 4671 4672 4673 if (dir != undefined){ options.autoplay = false; } |
Only run the carousel if we’re inside the viewport and the window has focus: | 4677 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: | 4681 4682 4683 4684 4685 4686 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: | 4690 if (!isAnimated) { |
What number is the last element? | 4694 var pos = Math.min(options.limit, $el.children().length); |
Step one forward: | 4698 4699 4700 4701 4702 4703 4704 4705 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: | 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 } 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: | 4724 4725 4726 4727 4728 4729 4730 4731 4732 if (options.autoplay == 'yes'){ window.setTimeout( function() { plugin.carousel($el, options); }, options.interval); } } else { window.setTimeout( function() { plugin.carousel($el, options); }, options.interval); } }; |
slideshowThe slideshow function is used by the slideshow command. It 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. | 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 plugin.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() { plugin.slideshow(slides, current, el, options); }, options.interval); }); }); } else { window.setTimeout( function() { plugin.slideshow(slides, current, el, options); }, options.interval); } } }; |
animationThe animation function is used by the animation command, but only in case it’s a keyframe animation. | 4776 4777 4778 4779 4780 plugin.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: | 4784 4785 $.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: | 4790 4791 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: | 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 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: | 4821 4822 4823 4824 4825 4826 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? | 4830 4831 4832 if ((nextloop && options.loop == "yes") || !nextloop){ window.setTimeout( function() { plugin.animation(frames, current, el, options); }, options.interval); } |
Some additional stuff to trigger in case the animation is finished: | 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 if (options.loop == "no"){ if (options.macro != undefined) plugin.applyMacro(el, options.macro); plugin.triggerEvent('complete', el, options); } } else { window.setTimeout( function() { plugin.animation(frames, current, el, options); }, options.interval); } }; |
closeLightboxThe closeLightbox function is used by the lightbox command to close the active lightbox programmatically from inside the lightbox content. | 4853 4854 4855 4856 4857 plugin.closeLightbox = function(){ $('.'+plugin.settings.prefix+'-lightbox-el').fadeTo('fast', 0, function(){ $(this).remove(); }); }; |
addKeypressEventsThe addKeypressEvents function is used by the key command and adds a specific keycode event to an element. | 4865 plugin.addKeypressEvents = function($el, code){ |
Check first if key navigations aren’t globally switched off: | 4869 if (plugin.settings.keyNavigation){ |
Listen to the documents keydown event: | 4873 $(document).keydown(function(e){ |
Only add the event if this isn’t a textaream, select or text input: | 4877 if ( this !== e.target && (/textarea|select/i.test( e.target.nodeName ) || e.target.type === "text") ) return; |
Map keycodes to their identifiers: | 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 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: | 4937 4938 4939 4940 4941 for(var i=48; i<=90; i++){ keys[i] = String.fromCharCode(i).toLowerCase(); } if ($.inArray(e.which, keys)){ |
Add special keys: | 4945 4946 4947 4948 4949 4950 4951 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: | 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 if (keycode == code){ $el.trigger(special+keys[e.which]); e.preventDefault(); } } }); } } |
Start the plugin by running the initialization function: | 4968 4969 4970 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. | 4982 $.fn.jKit_effect = function(show, type, speed, easing, delay, fn){ |
This is a real jQuery plugin, so make sure chaining works: | 4986 return this.each(function() { |
Do we have to call a callback function? If not, just create an empty one: | 4990 if (fn == undefined) fn = function(){}; |
If we didn’t set a delay, set the delay variable to zero: | 4994 if (delay == undefined) delay = 0; |
We now have all we need, so run the animation we need: | 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 5025 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. | 5032 5033 5034 5035 5036 $.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. | 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 $.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. | 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 $.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. | 5084 5085 5086 5087 $.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. | 5095 5096 5097 5098 $.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. | 5106 5107 5108 5109 $.fn.jKit_dateCheck = function(string){ var filter = /^[0-9]{2}.[0-9]{2}.[0-9]{2}$/i; return filter.test(string); }; |
jKit_timeCheckThe jKit_timeCheck plugin function is used by the validation command to check if the time string is valid. | 5117 5118 5119 5120 $.fn.jKit_timeCheck = function(string){ var filter = /^[0-9]{1,2}:[0-9]{2}$/i; return filter.test(string); }; |
jKit_phoneCheckThe jKit_phoneCheck plugin function is used by the validation command to check if the phone string is valid. | 5128 5129 5130 5131 $.fn.jKit_phoneCheck = function(string){ var filter = /^(+|0)[d ]+(-d*)?d$/; return filter.test(string); }; |
jKit_passwordStrengthThe jKit_passwordStrength plugin function is used by the validation command to check if the password strength is good enough. The function calculates a score from 0 to 100 based on various checks. | 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 $.fn.jKit_passwordStrength = function(passwd){ var intScore = 0 if (passwd.length < 5){ intScore = intScore + 5; } else if (passwd.length > 4 && passwd.length < 8){ intScore = intScore + 15; } else if (passwd.length >= 8){ intScore = intScore + 30; } if (passwd.match(/[a-z]/)) intScore = intScore + 5; if (passwd.match(/[A-Z]/)) intScore = intScore + 10; if (passwd.match(/d+/)) intScore = intScore + 10; if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/)) intScore = intScore + 10; if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) intScore = intScore + 10; if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) intScore = intScore + 10; if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) intScore = intScore + 5; if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) intScore = intScore + 5; if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) intScore = intScore + 5; return intScore; }; |
jKit_getAttributesThe jKit_getAttributes plugin function returns an array with all attributes that are set on a specific DOM node. | 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 $.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. | 5189 5190 5191 5192 5193 5194 5195 5196 5197 $.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. | 5204 5205 5206 $.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. | 5213 5214 5215 5216 $.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. | 5223 5224 5225 5226 $.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. | 5233 5234 5235 5236 $.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. | 5243 5244 5245 5246 $.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. | 5253 5254 5255 $.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. | 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 $.fn.jKit = function(options, moreoptions) { return this.each(function() { var plugin = new $.jKit(this, options, moreoptions); $(this).data('jKit', plugin); }); }; })(jQuery); |