-
Notifications
You must be signed in to change notification settings - Fork 3
/
basic.js
1262 lines (1040 loc) · 36.9 KB
/
basic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function()
{
////////////////////////////////
// Wetfish Basic
// Core functionality
// A constructor for public functions
var public = wetfish = function(selector)
{
if (!(this instanceof public))
{
return new public(selector)
}
// If the selector is a string
if(typeof selector == "string")
{
// Try matching some elements on the page
this.el = this.elements = document.querySelectorAll(selector);
}
else
{
// Assume an element was passed (like the value of this in an event)
this.el = this.elements = [selector];
}
this.length = this.el.length;
return this;
}
// Helper function to loop through elements
public.prototype.forEach = function(array, callback)
{
for(var i = 0, l = array.length; i < l; i++)
{
callback.call(this, array[i], i);
}
}
// Helper function to return either a single element or an array based on the length of the input given
// Output should be an array
// Fallback is the default value returned if there is no output
public.prototype.returnAllOrOne = function(output, fallback)
{
if(output.length)
{
if(output.length == 1)
{
return output[0];
}
return output;
}
if(fallback !== undefined)
{
return fallback;
}
}
// An object literal for private functions
var private = { };
// Polyfill from MDN for IE support
// See: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
private.CustomEvent = function(event, params)
{
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
private.CustomEvent.prototype = window.Event.prototype;
// Private function to determine element height
private.height = function(element, mode)
{
// Special case for the window
if(element == window)
{
var height =
{
inner: window.innerHeight,
outer: window.outerHeight
};
}
else
{
// Document should actually reference the documentElement
if(element == document)
{
element = document.documentElement;
}
// Now get the computed style
var style = window.getComputedStyle(element);
var height =
{
inner: element.offsetHeight,
outer: element.offsetHeight + parseInt(style.marginTop) + parseInt(style.marginBottom)
};
}
// If a valid mode was passed, return that property
if(height[mode] !== undefined)
return height[mode];
// Otherwise return both
return height;
}
// Polyfill from MDN
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray)
{
Array.isArray = function(arg)
{
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
// Private function to determine element width
private.width = function(element, mode)
{
// Special case for the window
if(element == window)
{
var width =
{
inner: window.innerWidth,
outer: window.outerWidth
};
}
else
{
// Document should actually reference the documentElement
if(element == document)
{
element = document.documentElement;
}
// Now get the computed style
var style = window.getComputedStyle(element);
var width =
{
inner: element.offsetWidth,
outer: element.offsetWidth + parseInt(style.marginLeft) + parseInt(style.marginRight)
};
}
// If a valid mode was passed, return that property
if(width[mode] !== undefined)
return width[mode];
// Otherwise return both
return width;
}
////////////////////////////////
// Check how basic should be exported
// Detect if we're in node or a browser
if(typeof module === 'object' && module.exports)
{
// We're in Node or a CommonJS compatible environment
module.exports = public;
}
else if(typeof define === 'function' && define.amd)
{
// We're in a browser being loaded with AMD (Require.js)
define(function() { return public });
}
else
{
// We're in a browser, so put everything into global variables
this.$ = public;
this.basic = public;
}
////////////////////////////////
// addClass() - add a class to all matched nodes
// usage - $('.selector').addClass('example');
public.prototype.addClass = function(classNames)
{
classNames = classNames.split(' ');
this.forEach(this.elements, function(element)
{
var classes = element.className.split(' ');
classNames.forEach(function(className)
{
var index = classes.indexOf(className);
// Only add a class if it doesn't exist
if(index == -1)
{
classes.push(className);
element.className = classes.join(' ');
}
});
});
return this;
}
////////////////////////////////
// append('string') - add a string to the end of all currently matched elements
// usage - $('body').append('The end!');
public.prototype.append = function(content)
{
// Loop through current elements
this.forEach(this.elements, function(element)
{
var child;
if(typeof content == "string")
{
// Avoid interfering with the current DOM by using a
// DocumentFragment instead of tampering with the innerHTML
var range = document.createRange();
range.selectNode(document.body);
child = range.createContextualFragment(content);
}
else
{
child = content.cloneNode(true);
}
element.appendChild(child);
});
return this;
}
////////////////////////////////
// attr('attribute') - get the value of an attribute on all matched elements
// attr('attribute', 'value') - set the value of an attribute on all matched elements
// usage - $('svg text').attr('stroke', 4);
public.prototype.attr = function(key, value)
{
var output = [];
// Loop through current elements
this.forEach(this.elements, function(element)
{
// If no value is specified, return the current value of the attribute
if(value === undefined)
{
output.push(element.getAttribute(key))
}
else
{
// If the value is true, create the attribute without any value
if(value === true)
{
element.setAttribute(key, '');
}
// If the value is false, remove the attribute
else if(value === false)
{
element.removeAttribute(key);
}
// Otherwise set the value as is
else
{
element.setAttribute(key, value);
}
}
});
return this.returnAllOrOne(output, this);
}
////////////////////////////////
// clone(deep) - clone an element
// usage - var clone = $('.element').clone();
public.prototype.clone = function(deep)
{
if(deep === undefined)
{
deep = true;
}
var output = [];
this.forEach(this.elements, function(element)
{
output.push(element.cloneNode(deep));
});
return this.returnAllOrOne(output);
}
////////////////////////////////
// data('attribute') - get the value of a data attribute on all matched elements
// data('attribute', 'value') - set the value of a data attribute on all matched elements
// usage - $('svg text').data('stroke', 4);
public.prototype.data = function(key, value)
{
var output = [];
// Loop through current elements
this.forEach(this.elements, function(element)
{
// Make sure the dataset is an object (for old versions of IE)
if(element.dataset === undefined)
{
element.dataset = {};
}
// If no value is specified, return the current value of the data attribute
if(value === undefined)
{
// If this key isn't found
if(element.dataset[key] === undefined)
{
// Check to see if it exists as an attribute (for old versions of IE)
var attr = element.getAttribute('data-' + key);
if(attr != null)
{
element.dataset[key] = attr;
}
}
output.push(element.dataset[key])
}
else
{
element.dataset[key] = value;
}
});
return this.returnAllOrOne(output, false);
}
////////////////////////////////
// each(callback) - loop over the list of currently matched elements, calling the callback for each
// usage - $('a').each(function(element, index) { console.log(this) };
public.prototype.each = function(callback)
{
// Loop through current elements
this.forEach(this.elements, function(element, index)
{
callback.call(element, index, element);
});
return this;
}
////////////////////////////////
// eq() - select something from the list of currently matched elements
// usage - $('a').eq(3).addClass('example');
public.prototype.eq = function(index)
{
// If an existing element was found
if(typeof this.elements[index] != "undefined")
{
this.elements = this.el = [this.elements[index]];
return this;
}
// Otherwise unset all matched elements
this.elements = this.el = [];
return this;
}
////////////////////////////////
// find() - find a selector within another element
// usage - $('nav').find('a').addClass('example');
public.prototype.find = function(selector)
{
// Clear existing elements array
var elements = this.elements;
this.elements = [];
// Loop through the original elements
this.forEach(elements, function(element)
{
var children = element.querySelectorAll(selector);
// Loop through any matching children and push them to the list of elements
this.forEach(children, function(child)
{
this.elements.push(child);
});
});
// Update the shorthand elements container
this.el = this.elements;
return this;
}
////////////////////////////////
// removeClass() - remove a class from all matched nodes
// usage - if($('.selector').hasClass('example')) { console.log('wow!'); }
public.prototype.hasClass = function(classes, mode)
{
var classes = classes.split(' ');
var match = false;
// TODO: Break loop when match is found?
this.forEach(this.elements, function(element)
{
// Reset matches between each loop
var matches = {};
this.forEach(classes, function(className)
{
var classNames = element.className.split(' ');
var index = classNames.indexOf(className);
if(index != -1)
{
matches[className] = true;
}
});
// If this is an inclusive match
if(mode == 'or')
{
if(Object.keys(matches).length)
{
match = true;
}
}
// Otherwise, make sure we matched all of the requested classes
else
{
if(Object.keys(matches).length == classes.length)
{
match = true;
}
}
});
return match;
}
// Depends on: ./deps/height.js
////////////////////////////////
// height() - get the height of a specific element or all matched elements
// usage - var height = $('.single-selector').height(); // Returns an object containing the element's inner and outer height
// usage - var height = $('.multi-selector').height(); // Returns an array of objects containing the inner and outer height of all matched elements
public.prototype.height = function(mode)
{
// Default to inner height
if(mode === undefined)
mode = 'inner';
var output = [];
this.forEach(this.elements, function(element)
{
output.push(private.height(element, mode));
});
return this.returnAllOrOne(output);
}
////////////////////////////////
// html('string') - replace the contents of all currently matched elements
// usage - $('p').html('<b>Replaced!</b>');
public.prototype.html = function(content)
{
// Loop through current elements
this.forEach(this.elements, function(element)
{
if(typeof content == "string")
{
element.innerHTML = content;
}
else
{
element.innerHTML = content.outerHTML;
}
});
return this;
}
////////////////////////////////
// index() - find the index an element
// usage - var index = $('.element').index();
public.prototype.index = function()
{
var output = [];
this.forEach(this.elements, function(element)
{
this.forEach(element.parentNode.children, function(child, index)
{
if(element == child)
{
output.push(index);
}
});
});
return this.returnAllOrOne(output);
}
////////////////////////////////
// noConflict() - returns public class
// usage - var customVar = basic.noConflict();
public.prototype.noConflict = function()
{
return public;
}
// Depends on: ./off.js
////////////////////////////////
// off() - remove an event that is only fired when a child selector is matched
// usage - $('.selector').off('click', '.selector', callback);
private.eventCallbacks = [];
private.eventFunctions = [];
private.offSelector = function(events, selector, callback)
{
events = events.split(' ');
// Look for the index of this callback
var functionIndex = private.eventCallbacks.indexOf(callback);
// If the function is found
if(functionIndex > -1)
{
this.forEach(events, function(event)
{
this.forEach(this.elements, function(element)
{
element.removeEventListener(event, private.eventFunctions[functionIndex]);
});
});
// Remove functions from arrays
delete private.eventCallbacks[functionIndex];
delete private.eventFunctions[functionIndex];
}
return this;
}
////////////////////////////////
// off() - remove an event from all matched elements
// usage - $('.selector').off('click', callback);
public.prototype.off = function(events, callback)
{
// If more than two arguments are passed, handle this event using offSelector
if(arguments.length > 2 && private.offSelector !== undefined)
{
return private.offSelector.apply(this, arguments);
}
events = events.split(' ');
this.forEach(events, function(event)
{
this.forEach(this.elements, function(element)
{
element.removeEventListener(event, callback);
});
});
return this;
}
// Depends on: ./on.js
////////////////////////////////
// on() - bind an event that is only fired when a child selector is matched
// usage - $('body').on('click', '.selector' function() { console.log('you clicked!'); });
private.eventCallbacks = [];
private.eventFunctions = [];
private.onSelector = function(events, selector, callback)
{
events = events.split(' ');
private.eventCallbacks.push(callback);
var functionIndex = private.eventFunctions.push(function(event)
{
var children = document.querySelectorAll(selector);
for(var i = 0, l = children.length; i < l; i++)
{
var child = children[i];
if(event.target == child)
{
callback.call(event.target, event);
}
}
});
// Subtract 1 because push returns the array length
functionIndex--;
this.forEach(events, function(event)
{
this.forEach(this.elements, function(element)
{
element.addEventListener(event, private.eventFunctions[functionIndex]);
});
});
return this;
}
////////////////////////////////
// on() - bind an event to all matched elements
// usage - $('.selector').on('click', function() { console.log('you clicked!'); });
public.prototype.on = function(events, callback)
{
// If more than two arguments are passed, handle this event using onSelector
if(arguments.length > 2 && private.onSelector !== undefined)
{
return private.onSelector.apply(this, arguments);
}
events = events.split(' ');
this.forEach(events, function(event)
{
this.forEach(this.elements, function(element)
{
element.addEventListener(event, callback);
});
});
return this;
}
////////////////////////////////
// parent() - get the direct parent of all matched elements
// usage - $('.selector').parent();
public.prototype.parent = function()
{
var elements = [];
this.forEach(this.elements, function(element, index)
{
elements[index] = element.parentNode;
});
this.elements = this.el = elements;
return this;
}
////////////////////////////////
// parents() - loop through all parents until a matching selector is found
// usage - $('.selector').parents('.container');
private.parent = function(element, parent)
{
if(!element)
{
return false;
}
if(element.parentNode == parent)
{
return parent;
}
else
{
return private.parent(element.parentNode, parent);
}
}
public.prototype.parents = function(selector)
{
var elements = [];
var parents = [];
if(typeof selector === "object" && document.contains(selector))
{
parents = [selector];
}
else
{
parents = document.querySelectorAll(selector);
}
this.forEach(this.elements, function(element)
{
this.forEach(parents, function(parent)
{
var matched = private.parent(element, parent);
if(matched)
{
elements.push(parent);
}
});
});
this.elements = this.el = elements;
return this;
}
////////////////////////////////
// position(relative) - get the position of a specific element or all matched elements
// - optionally specify if the position should be relative to the 'viewport' or the 'page' (default)
// usage - var position = $('.single-selector').position(); // Returns an object containing the element's inner and outer position
// usage - var position = $('.multi-selector').position(); // Returns an array of objects containing the inner and outer position of all matched elements
public.prototype.position = function(relative)
{
var output = [];
relative = relative || 'page';
this.forEach(this.elements, function(element)
{
var rect = element.getBoundingClientRect();
// DOM Rects are immutable, so we have to copy the data
var position =
{
top: rect.top,
left: rect.left,
right: rect.right,
bottom: rect.bottom
};
if(relative == "page")
{
// Add the scroll position to top / left
position.left += window.scrollX;
position.top += window.scrollY;
}
output.push(position);
});
return this.returnAllOrOne(output);
}
////////////////////////////////
// prepend('string') - add a string to the beginning of all currently matched elements
// usage - $('body').prepend('Dear user,');
public.prototype.prepend = function(content)
{
// Loop through current elements
this.forEach(this.elements, function(element)
{
var child;
if(typeof content == "string")
{
var range = document.createRange();
range.selectNode(document.body);
child = range.createContextualFragment(content);
}
else
{
child = content.cloneNode(true);
}
element.insertBefore(child, element.firstChild);
});
return this;
}
////////////////////////////////
// prop('property') - get a property of all matched elements
// prop('key', 'value') - set the property of all matched elements
// usage - $('.checkbox').prop('checked', true);
public.prototype.prop = function(key, value)
{
var output = [];
// Loop through current elements
this.forEach(this.elements, function(element)
{
// If no value is specified, return the current property of the element
if(value === undefined)
{
output.push(element[key]);
}
// Otherwise, set the property
else
{
element[key] = value;
}
});
return this.returnAllOrOne(output, this);
}
// Depends on: ./deps/customEvent.js
////////////////////////////////
// ready() - wait for the page to load before firing callback
// usage - $(document).ready, function() { console.log('Page ready!'); });
public.prototype.ready = function(callback)
{
this.forEach(this.elements, function(element)
{
element.addEventListener('ready', callback);
});
}
// Native dom loaded event
document.addEventListener('DOMContentLoaded', function()
{
// Create a custom event with a nicer name
var ready = new private.CustomEvent('ready');
// Trigger it!
document.dispatchEvent(ready);
})
////////////////////////////////
// remove() - remove all currently matched elements
// usage - $('p').remove();
public.prototype.remove = function()
{
// Loop through current elements
this.forEach(this.elements, function(element)
{
element.parentNode.removeChild(element);
});
return this;
}
////////////////////////////////
// removeClass() - remove a class from all matched nodes
// usage - $('.selector').removeClass('example');
public.prototype.removeClass = function(classNames)
{
classNames = classNames.split(' ');
this.forEach(this.elements, function(element)
{
var classes = element.className.split(' ');
classNames.forEach(function(className)
{
var index = classes.indexOf(className);
// Only remove a class if it exists
if(index != -1)
{
classes.splice(index, 1);
element.className = classes.join(' ');
}
});
});
return this;
}
////////////////////////////////
// replace('string') - replace all currently matched elements with the string
// usage - $('.start').replace("<div class='stop'>Replaced!</div>');
public.prototype.replace = function(content)
{
// Loop through current elements
this.forEach(this.elements, function(element)
{
if(typeof content == "string")
{
element.outerHTML = content;
}
else
{
element.outerHTML = content.outerHTML;
}
});
return this;
}
////////////////////////////////
// scroll() - get the scroll position of a specific element or all matched elements
// usage - var scroll = $('.single-selector').scroll(); // Returns an object containing the element's scrollTop and scrollLeft
// usage - var scroll = $('.multi-selector').scroll(); // Returns an array of objects containing the scrollTop and scrollLeft of all matched elements
public.prototype.scroll = function()
{
var output = [];
this.forEach(this.elements, function(element)
{
// The window is a special case that doesn't have scrollTop / scrollLeft properties
if(element == window)
{
var scroll =
{
top: element.pageYOffset,
left: element.pageXOffset
};
}
else
{
var scroll =
{
top: element.scrollTop,
left: element.scrollLeft
};
}
output.push(scroll);
});
return this.returnAllOrOne(output);
}
// Depends on: ./deps/width.js, ./deps/height.js
////////////////////////////////
// size() - get the size of a specific element or all matched elements
// usage - var size = $('.single-selector').size(); // Returns an object containing the element's height and width
// usage - var size = $('.multi-selector').size(); // Returns an array of objects containing the height and width of all matched elements
public.prototype.size = function(mode)
{
// Default to inner size
if(mode === undefined)
mode = 'inner';
var output = [];
this.forEach(this.elements, function(element)
{
var size =
{
height: private.height(element, mode),
width: private.width(element, mode)
};
output.push(size);
});
return this.returnAllOrOne(output);
}
////////////////////////////////
// style() - get or set styles for matched elements
// usage - $('a').style({'color': 'red', 'font-size': '30pt'}); // Set the style for all matched elements to 30pt and red
// usage - $('.unique-selector').style('color'); // Get the color attribute for a single element
// usage - $('a').style('color'); // Get an array of the color attributes for all matched elements
public.prototype.style = function(style)
{
// If we're setting an object of styles
if(typeof style == "object")
{
var properties = Object.keys(style);
this.forEach(properties, function(property)
{
this.forEach(this.elements, function(element)
{
element.style[property] = style[property];
});
});
return this;
}
// Otherwise, we must be getting the value of a property
else if(typeof style == "string")
{
var output = [];
this.forEach(this.elements, function(element)