This repository was archived by the owner on Jun 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmquery.ts
2025 lines (1746 loc) · 71.2 KB
/
mquery.ts
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
// DEFINE GLOBAL TYPES
export type mQuery = m$.Class;
export type m$ = m$.Class;
/**
* Binds a function to be executed when the DOM has finished loading.
* @param onReady The function to execute when the DOM is ready.
*/
export function m$(onReady: Function): mQuery;
/**
* Return a collection of matched elements.
* @param selector A selector, DOM Element, Document, or mQuery to create instance.
* @param context A DOM Element, Document, or mQuery to use as context.
*/
export function m$(selector?: mQuery | NodeList | Node | Node[] | string, context?: mQuery | NodeList | Node | Node[] | string): mQuery;
export function m$(selector?, context?): mQuery {
return new mQuery.Class(selector, context);
}
export const mQuery = m$;
export namespace m$ {
// Types
export type Class = mQuery;
export type Deferred = Promise.Deferred;
export type ForEachIterator<T> = (keyOrIndex: any, value: T) => boolean | void;
export type EachIterator = ForEachIterator<HTMLElement>;
export type ArrayLikeObject = PlainObject | ArrayLike<any>;
export type PlainObject = { [key: string]: any, length?: number };
export type AJAXSuccess = (data?: any, textStatus?: string, XHR?: XMLHttpRequest) => void;
export type AJAXDetails = (XHR?: XMLHttpRequest, optionsOrStatus?: PlainObject | string, errorThrown?: string) => void;
export type AJAXOptions = {
method?: string,
beforeSend?: AJAXDetails,
complete?: AJAXDetails,
success?: AJAXSuccess,
error?: AJAXDetails,
contentType?: false | string,
context?: Object,
data?: PlainObject | string | any[],
dataFilter?: (data: string, type: string) => any,
headers?: PlainObject,
type?: string,
url?: string,
mimeType?: string,
username?: string,
password?: string,
async?: boolean,
//? ifModified TODO
statusCode?: PlainObject,
timeout?: number,
xhr?: () => XMLHttpRequest
};
export enum HTTP {
GET = 'GET',
HEAD = 'HEAD',
POST = 'POST',
PUT = 'PUT',
DELETE = 'DELETE',
CONNECT = 'CONNECT',
OPTIONS = 'OPTIONS',
TRACE = 'TRACE',
PATCH = 'PATCH'
}
// init constants
const DOC = document;
const WIN = window || DOC.defaultView;
var AJAX_CONFIG = {
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
method: HTTP.GET,
statusCode: {},
xhr: () => new XMLHttpRequest(),
headers: {},
timeout: 0,
async: true
};
// mQuery constants
export const APP_NAME = 'mQuery';
export const AUX_ELEM = DOC.createElement(`_${APP_NAME}_`);
/**
* mQuery Core.
*/
export class mQuery implements ArrayLike<HTMLElement> {
[index: number]: HTMLElement;
[key: string]: any;
public prevObject?: mQuery;
public length: number = 0;
/**
* Constructor.
* @param selector mQuery | NodeList | Node | Node[] | QuerySelector | HTML String
*/
constructor(selector?, context?) {
// If the selector is equivalent to false, return
if (isFalse(selector)) { return this }
// If selector is Document or Window, return instance with selector
if (typeOf(selector, ['document', 'window'])) { return this.push(selector) }
// If selector is Function, use it like ready callback and return
if (typeOf(selector, 'function')) { return ROOT.ready(selector) }
// If selector is NOT string merge selector and return
if (!typeOf(selector, 'string')) { return <this>merge(this, createArr(selector)) }
// Try parse HTML and, if any element has been created, merge and return
if (isHTML(selector)) {
let elems = parseHTML(selector);
if (elems.length) { return <this>merge(this, elems) }
}
// Find selector with find function and return
return find(this, createContext(context), selector);
}
// =================== ARRAY PROPERTIES =================== //
/**
* Insert element without repeat.
*/
private push(elem: Node): this {
if (!isSet(elem)) { return this }
if (isSet(elem[APP_NAME])) {
// Get APP_NAME property
let prop = elem[APP_NAME];
// Verify if elem has been inserted inside this list before (last)
if (prop.$ref === this) { return this }
// Add list reference to the element
prop.$ref = this;
} else {
// Set APP_NAME property into Node
elem[APP_NAME] = {
$ref: this,
data: [],
hasAttr: void 0,
events: []
};
}
// Add element increasing length
this[this.length++] = <HTMLElement>elem;
// Return this
return this;
}
/**
* Concat array-like elements inside current object.
*/
private concat(elems: any): this {
return <this>merge(this, elems);
}
// ================== MQUERY PROPERTIES =================== //
/**
* [ONLY MQUERY] Return all leaf elements (elements without child).
*/
public leaves(): mQuery {
return this.find('*').filter((_, elem) => !elem.firstElementChild);
}
/**
* Specify a function to execute when the DOM is fully loaded.
* @param handler A function to execute after the DOM is ready.
*/
public ready(handler: Function): this {
if (DOC.readyState !== 'loading') {
handler(m$);
} else {
DOC.addEventListener('DOMContentLoaded', () => { handler(m$) });
}
return this;
}
/**
* Iterate over a mQuery object, executing a function for each matched element.
* @param handler A function to execute for each matched element.
*/
public each(handler: EachIterator): this {
return <this>each(this, handler);
}
/**
* Attach an event handler function for one or more events to the selected elements.
* @param events One or more space-separated event types.
* @param selector A selector string to filter the descendants of the selected elements that trigger the event.
* @param data Data to be passed to the handler in event.data when an event occurs.
* @param handler A function to execute when the event is triggered.
*/
// TODO: Add event namespace
public on(events: string, selector?, data?, handler?: EventListener): this {
let length = arguments.length;
if (length < 4) {
for (let i = length - 1; i > 0; --i) {
let arg = arguments[i],
type = (typeof arg).toLowerCase();
if (type === 'function') {
if (!handler) {
handler = arg;
arguments[i] = void 0;
}
} else if (type !== 'string') {
if (!data) {
data = arg;
arguments[i] = void 0;
}
}
}
}
return <this>addEventListener(this, events, <string>selector, data, handler);
}
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
* @param events One or more space-separated event types.
* @param selector A selector string to filter the descendants of the selected elements that trigger the event.
* @param data Data to be passed to the handler in event.data when an event occurs.
* @param handler A function to execute when the event is triggered.
*/
public one(events: string, selector?, data?, handler?: EventListener): this {
if (!isSet(handler)) {
for (let i = arguments.length - 1; i > 0; --i) {
let arg = arguments[i],
type = (typeof arg).toLowerCase();
if (type === 'function') {
if (!handler) {
handler = arg;
arguments[i] = void 0;
}
} else if (type !== 'string') {
if (!data) {
data = arg;
arguments[i] = void 0;
}
}
}
}
return <this>addEventListener(this, events, <string>selector, data, handler, true);
}
/**
* Remove an event handler.
* @param events One or more space-separated event types.
* @param selector A selector which should match the one originally passed to .on() when attaching event handlers.
* @param handler A handler function previously attached for the event(s).
*/
public off(events: string, selector?, handler?: EventListener): this {
if (!isSet(handler)) {
let type = (typeof selector).toLowerCase();
if (type === 'function') {
handler = selector;
selector = void 0;
}
}
return <this>removeEventListener(this, events, <string>selector, handler);
}
/**
* Check the current matched set of elements against a selector or function.
* @param is (i, elem) => boolean A function used as a test for every element in the set.
*/
public is(filter: (i, elem) => boolean): boolean;
/**
* Check the current matched set of elements against a selector or function.
* @param selector A string containing a selector expression to match elements against.
*/
public is(selector: string): boolean;
public is(filter: any): boolean {
let isStr = typeOf(filter, 'string');
return some(this, (i, elem) =>
isStr ? matches(elem, filter) : filter.call(elem, i, elem)
);
}
/**
* Reduce the set of matched elements to those that match the selector or pass the function's test.
* @param filter A function used as a test for each element in the set. 'this' is the current DOM element.
*/
public filter(filter: Function): mQuery;
/**
* Reduce the set of matched elements to those that match the selector or pass the function's test.
* @param selector A string containing a selector expression to match the current set of elements against.
*/
public filter(selector: string): mQuery;
public filter(filter): mQuery {
let elems = m$(), isStr = typeOf(filter, 'string');
this.each((i, elem) => {
if (isStr) {
matches(elem, filter) && elems.push(elem);
} else if (filter.call(elem, i, elem)) {
elems.push(elem);
}
});
return setContext(elems, this);
}
/**
* Remove elements from the set of matched elements.
* @param filter A function used as a test for each element in the set.
*/
public not(filter: Function): mQuery;
/**
* Remove elements from the set of matched elements.
* @param selector A string containing a selector expression to match elements against.
*/
public not(selector: string): mQuery;
public not(filter): mQuery {
return this.filter(typeOf(filter, 'string') ?
(_, elem) => !matches(elem, filter) :
(i, elem) => !filter.call(elem, i, elem)
);
}
/**
* Reduce the set of matched elements to those that have a descendant that matches the selector.
* @param selector A string containing a selector expression to match elements against.
*/
public has(selector: string): mQuery;
/**
* Reduce the set of matched elements to those that have a descendant that matches the element.
* @param elem A DOM element child to match.
*/
public has(elem: Node): mQuery;
public has(selector): mQuery {
let elems = m$(), isStr = typeOf(selector, 'string');
this.each((_, elem) => {
if (isStr ? elem.querySelector(selector) : elem.contains(selector)) {
elems.push(elem);
}
});
return setContext(elems, this);
}
/**
* Get the descendants of each element in the current set of matched elements, filtered by a selector.
* @param selector A string containing a selector expression to match elements against.
*/
public find(selector: string): mQuery {
return find(m$(), this, selector);
}
/**
* Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
* @param selector A string containing a selector expression to match elements against.
*/
public parent(selector?: string): mQuery {
let parents = m$();
this.each((_, elem) => {
if (!hasParent(elem)) { return }
elem = elem.parentElement;
if (!matches(elem, selector)) { return }
parents.push(elem);
});
return setContext(parents, this);
}
/**
* Get the ancestors of each element in the current set of matched elements.
* @param selector A string containing a selector expression to match elements against.
*/
public parents(selector?: string): mQuery {
let parents = m$(), newParents = this.parent();
do {
parents.concat(newParents);
newParents = newParents.parent();
} while (newParents.length);
return parents.filter(selector);
}
/**
* End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
*/
public end(): mQuery {
return this.prevObject || EMPTY;
}
/**
* Execute all handlers and behaviors attached to the matched elements for the given event type.
* @param event A Event object.
* @param params Additional parameters to pass along to the event handler.
*/
public trigger(event: Event, params?: PlainObject | any[]);
/**
* Execute all handlers and behaviors attached to the matched elements for the given event type.
* @param eventType A string containing a JavaScript event type, such as click or submit.
* @param params Additional parameters to pass along to the event handler.
*/
public trigger(eventType: string, params?: PlainObject | any[]);
public trigger(event, params?: PlainObject | any[]): mQuery {
let customEvent = event;
if (typeOf(event, 'string')) {
customEvent = m$.Event(event);
}
// Set detail into the event
extend(createIfNeeded(event, 'detail', {}), params);
return this.each((_, elem) => {
if (event === 'focus') { return elem.focus() }
elem.dispatchEvent(customEvent);
});
}
/**
* Get the value of an attribute for the first element in the set of matched elements.
* @param attrName The name of the attribute to get.
*/
public attr(attrName: string): string;
/**
* Set one or more attributes for the set of matched elements.
* @param attrs An object of attribute-value pairs to set.
*/
public attr(attrs: PlainObject): this;
/**
* Set one or more attributes for the set of matched elements.
* @param attrName The name of the attribute to set.
* @param value A value to set for the attribute. If null, the specified attribute will be removed (as in .removeAttr()).
*/
public attr(attrName: string, value: string | null): this;
public attr(attrs: PlainObject | string, value?: string | null): this | string {
// attr(attrName: string, value: string | null): this;
if (isSet(value)) {
return this.each((_, elem) => {
if (value === null) { this.removeAttr(<string>attrs) }
elem.setAttribute(<string>attrs, value);
});
}
// attr(attrs: PlainObject): this;
if (!typeOf(attrs, 'string')) {
each(<PlainObject>attrs, (attr, value) => {
this.attr(attr, value);
});
return this;
}
// attr(attrName: string): string;
return isEmpty(this) ? void 0 : (this[0].getAttribute(<string>attrs) || void 0);
}
/**
* Remove an attribute from each element in the set of matched elements.
* @param attrNames An attribute to remove, it can be a space-separated list of attributes.
*/
public removeAttr(attrNames: string): this {
return this.each((_, elem) => {
attrNames.split(' ').forEach((attrName) => {
elem.removeAttribute(attrName);
});
});
}
/**
* Get the value of a property for the first element in the set of matched elements.
* @param propName The name of the property to get.
*/
public prop(propName: string): any;
/**
* Set one or more properties for the set of matched elements.
* @param props An object of property-value pairs to set.
*/
public prop(props: PlainObject): this;
/**
* Set one or more properties for the set of matched elements.
* @param propName The name of the property to set.
* @param value A value to set for the property.
*/
public prop(propName: string, value: string): this;
public prop(props, value?: string) {
// prop(propName: string, value: string): this;
if (isSet(value)) {
return this.each((_, elem) => {
if (isSet(elem[props])) {
elem[props] = value;
return;
}
elem.setAttribute(props, value);
});
}
// prop(props: PlainObject): this;
if (!typeOf(props, 'string')) {
each(<PlainObject>props, (prop, value) => {
this.prop(prop, value);
});
return this;
}
// prop(propName: string): any;
if (isEmpty(this)) { return void 0 }
if (isSet(this[0][props])) {
return this[0][props];
}
return this[0].getAttribute(props) || void 0;
}
/**
* Remove a property for the set of matched elements.
* @param propNames An property to remove, it can be a space-separated list of attributes
*/
public removeProp(propNames: string): this {
return this.each((_, elem) => {
propNames.split(' ').forEach((propName) => {
if (isSet(elem[propName])) {
delete elem[propName];
return;
}
elem.removeAttribute(propName);
});
});
}
/**
* Get the computed style properties for the first element in the set of matched elements.
* @param styleName A CSS property.
*/
public css(styleName: string): string;
/**
* Set one or more CSS properties for the set of matched elements.
* @param properties An object of property-value pairs to set.
*/
public css(properties: PlainObject): this;
/**
* Set one or more CSS properties for the set of matched elements.
* @param styleName A CSS property name.
* @param value A value to set for the property.
*/
public css(styleName: string, value: string | number): this;
public css(styleName, value?): this | string {
if (!typeOf(styleName, 'string')) {
each(styleName, (key, value) => { this.css(key, value) });
return this;
}
if (isSet(value)) {
if (typeOf(value, 'number')) { value += 'px' }
return this.each((_, elem) => { elem.style[styleName] = value });
}
if (isEmpty(this)) { return void 0 }
let elem: any = this[0],
view = elem.ownerDocument.defaultView;
if (view && view.getComputedStyle) {
return view.getComputedStyle(elem, void 0).getPropertyValue(styleName);
}
styleName = snakeToCamelCase(styleName);
if (elem.currentStyle) {
return elem.currentStyle[styleName];
}
console.warn('Returning HTMLElement.style, this may not corresponding to the current style.');
return elem.style[styleName];
}
/**
* Get the combined text contents of each element in the set of matched elements, including their descendants.
*/
public text(): string;
/**
* Set the content of each element in the set of matched elements to the specified text.
* @param text The text to set as the content of each matched element.
*/
public text(text: string): this;
public text(text?: string): this | string {
if (isSet(text)) {
return this.each((_, elem) => {
elem.textContent = text;
});
}
let value = '';
this.each((_, elem) => {
value += elem.textContent;
});
return value.trim() || void 0;
}
/**
* Get the HTML contents of the first element in the set of matched elements.
*/
public html(): string;
/**
* Set the HTML contents of each element in the set of matched elements.
* @param htmlString A string of HTML to set as the content of each matched element.
*/
public html(htmlString: string): this;
public html(htmlString?: string): this | string {
if (isSet(htmlString)) {
return this.each((_, elem) => {
elem.innerHTML = htmlString;
});
}
return isEmpty(this) ? void 0 : this[0].innerHTML;
}
/**
* Get the children of each element in the set of matched elements, optionally filtered by a selector.
* @param selector A string containing a selector expression to match elements against.
*/
public children(selector?: string): mQuery {
let elems = m$();
this.each((_, elem) => { elems.concat(elem.children) });
elems.prevObject = this;
return selector ? elems.filter(selector) : elems;
}
/**
* Reduce the set of matched elements to the first in the set.
*/
public first(): mQuery {
return setContext(m$(this.get(0)), this);
}
/**
* Reduce the set of matched elements to the final one in the set.
*/
public last(): mQuery {
return setContext(m$(this.get(-1)), this);
}
/**
* Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
* @param selector A string containing a selector expression to match elements against.
*/
public siblings(selector?: string): mQuery {
let siblings = m$();
this.each((_, elem) => {
each(elem.parentElement.children, (_, child) => {
if (child === elem) { return }
if (!matches(child, selector)) { return }
siblings.push(child);
});
});
return setContext(siblings, this);
}
/**
* Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.
* @param selector A string containing a selector expression to match elements against.
*/
public prev(selector?: string): mQuery {
let prev = m$();
this.each((_, elem) => {
let prevElem = elem.previousElementSibling;
if (!matches(prevElem, selector)) { return }
prev.push(prevElem);
});
return setContext(prev, this);
}
/**
* Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
* @param selector A string containing a selector expression to match elements against.
*/
public next(selector?: string): mQuery {
let next = m$();
this.each((_, elem) => {
let nextElem = elem.nextElementSibling;
if (!matches(nextElem, selector)) { return }
next.push(nextElem);
});
return setContext(next, this);
}
/**
* Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
* @param contents DOM element, text node, array of elements and text nodes, HTML string, or mQuery object to insert at the beginning of each element in the set of matched elements.
*/
public prepend(...contents): this {
let rawChildren = contents.reverse();
return this.each((_, parent) => {
setChildren(rawChildren,
(child) => { parent.insertBefore(child, parent.firstChild) },
(str) => { parent.insertAdjacentHTML('afterbegin', str) });
});
}
public prependTo(selector?): this {
m$(selector).prepend(this);
return this;
}
/**
* Insert content, specified by the parameter, to the end of each element in the set of matched elements.
* @param contents DOM element, text node, array of elements and text nodes, HTML string, or mQuery object to insert at the end of each element in the set of matched elements.
*/
public append(...contents): this {
return this.each((_, parent) => {
setChildren(contents,
(child) => { parent.appendChild(child) },
(str) => { parent.insertAdjacentHTML('beforeend', str) });
});
}
public appendTo(selector?): this {
m$(selector).append(this);
return this;
}
/**
* Return the values store for the first element in the collection.
* @param key A string naming the piece of data to set.
* @param value The new data value; this can be any Javascript type except undefined.
*/
public data(): any;
/**
* Store arbitrary data associated with the matched elements.
* @param obj An object of key-value pairs of data to update.
*/
public data(obj: PlainObject): this;
/**
* Return the value at the named data store for the first element in the collection, as set by data(name, value) or by an HTML5 data-* attribute.
* @param key Name of the data stored.
*/
public data(key: string | number): any;
/**
* Store arbitrary data associated with the matched elements.
* @param key A string naming the piece of data to set.
* @param value The new data value; this can be any Javascript type except undefined.
*/
public data(key: string | number, value: any): this;
public data(keyOrObj?: any, value?: any): this | any {
if (isEmpty(this)) { return void 0 }
// data(): any;
if (!isSet(keyOrObj)) {
return dataRef(this[0]);
}
// data(key: string | number, value: any): this;
if (isSet(value)) {
return this.each((_, elem) => {
dataRef(elem, false)[keyOrObj] = value;
});
}
// data(key: string | number): any;
if (typeOf(keyOrObj, ['string', 'number'])) {
return dataRef(this[0], keyOrObj);
}
// data(obj: Object): this;
each(keyOrObj, (key, value) => {
this.data(key, value);
});
return this;
}
/**
* Get the current value of the first element in the set of matched elements.
*/
public val(): string;
/**
* Set the value of each element in the set of matched elements.
* @param value A string of text or a number corresponding to the value of each matched element to set as selected/checked.
*/
public val(value: string): this;
public val(value?: string): this | string {
if (!isSet(value)) {
return this.prop('value');
}
return this.prop('value', value);
}
/**
* Adds the specified class(es) to each element in the set of matched elements.
* @param className One or more space-separated classes to be added to the class attribute of each matched element.
*/
public addClass(className: string): this {
return this.each((_, elem) => {
className.split(' ').forEach((name) => {
elem.classList.add(name);
});
});
}
/**
* Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
* @param className One or more space-separated classes to be removed from the class attribute of each matched element.
*/
public removeClass(className: string): this {
return this.each((_, elem) => {
className.split(' ').forEach((name) => {
elem.classList.remove(name);
});
});
}
/**
* Determine whether any of the matched elements are assigned the given class.
* @param className The class name to search for.
*/
public hasClass(className: string): boolean {
return some(this, (_, elem) => elem.classList.contains(className));
}
/**
* Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
* @param className One or more class names (separated by spaces) to be toggled for each element in the matched set.
*/
public toggleClass(className: string): this {
return this.each((_, elem) => { elem.classList.toggle(className) });
}
/**
* Remove the set of matched elements from the DOM.
* @param selector A selector expression that filters the set of matched elements to be removed.
*/
public remove(selector?: string): mQuery {
let elems = m$();
this.each((_, elem) => {
if (!matches(elem, selector)) {
elems.push(elem);
return;
}
// Remove element
if (elem.remove) {
elem.remove();
} else if (elem['removeNode']) {
elem['removeNode']();
} else {
elem.outerHTML = '';
}
});
return setContext(elems, this);
}
/**
* Remove all child nodes of the set of matched elements from the DOM.
*/
public empty(): this {
return this.each((_, elem) => { emptyElement(elem) });
}
/**
* Pass each element in the current matched set through a function, producing a new mQuery object containing the return values.
* @param beforePush The function to process each item.
*/
public map(beforePush: (element, index) => any): mQuery {
return <mQuery>map(this, beforePush, setContext(m$(), this));
}
/**
* Retrieve one of the elements matched. If index was not passed, return an array with all elements.
* @param index A zero-based integer indicating which element to retrieve.
*/
public get(index?: number): HTMLElement[] | HTMLElement {
if (!isSet(index)) { return makeArray(this) }
if (index < 0) { index = this.length + index }
return index < this.length ? this[index] : void 0;
}
/**
* Reduce the set of matched elements to the one at the specified index.
* @param index An integer indicating the 0-based position of the element.
*/
public eq(index?: number): mQuery {
return setContext(m$(this.get(index)), this);
}
/**
* Get the current computed width for the first element in the set of matched elements.
*/
public width(): number;
/**
* Set the CSS width of each element in the set of matched elements.
* @param valueFn A function returning the width to set. Receives the index and the old width. "this" refers to the current element in the set.
*/
public width(valueFn: (index?: number, width?: number) => string | number): mQuery;
/**
* Set the CSS width of each element in the set of matched elements.
* @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).
*/
public width(value: string | number): mQuery;
public width(value?: any): mQuery | number {
if (!typeOf(value, 'function')) {
return size(this, 'Width', value);
}
return this.each((i, elem) => {
let $elem = m$(elem);
$elem.width(value.call(elem, i, $elem.width()));
});
}
/**
* Get the current computed height for the first element in the set of matched elements.
*/
public height(): number;
/**
* Set the CSS height of every matched element.
* @param valueFn A function returning the height to set. Receives the index and the old height. "this" refers to the current element in the set.
*/
public height(valueFn: (index?: number, width?: number) => string | number): mQuery;
/**
* Set the CSS height of every matched element.
* @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).
*/
public height(value: string | number): mQuery;
public height(value?: any): mQuery | number {
if (!typeOf(value, 'function')) {
return size(this, 'Height', value);
}
return this.each((i, elem) => {
let $elem = m$(elem);
$elem.height(value.call(elem, i, $elem.height()));
});
}
/**
* Bind one or two handlers to the matched elements.
* @param handlerIn A function to execute when the mouse pointer enters the element.
* @param handlerOut A function to execute when the mouse pointer leaves the element.
*/
public hover(handlerIn: EventListener, handlerOut?: EventListener): this {
if (isSet(handlerIn)) {
if (!isSet(handlerOut)) {
return this.on('mouseenter mouseleave', handlerIn);
}
this.on('mouseenter', handlerIn);
}
if (isSet(handlerOut)) {
this.on('mouseleave', handlerOut);
}
return this;
}
/**
* Load data from the server and place the returned HTML into the matched element.
* @param url A string containing the URL to which the request is sent.
* @param data A plain object or string that is sent to the server with the request.
* @param complete A callback function that is executed when the request completes.
*/
public load(url, data?: AJAXSuccess | any, complete?: AJAXSuccess): this {
// If instance is empty, just return
if (isEmpty(this)) { return this }
// Get parameters
if (!isSet(complete)) {
complete = data;
data = void 0;
}
// Get selector with the url (if exists)
let matches = url.trim().match(/^([^\s]+)\s?(.*)$/),
selector = matches[2];
m$.ajax({