utils.js
Collection of useful functions for any progressive environment
Extending jQuery
Method |
Code |
---|---|
regex |
//Select all elements with an ID starting a vowel:
$(':regex(id,^[aeiou])');
//Select all DIVs with classes that contain numbers:
$('div:regex(class,[0-9])');
//Select all SCRIPT tags with a SRC containing jQuery:
$('script:regex(src,jQuery)');
//Select all elements with a width between 100 and 300:
$(':regex(css:width, ^[1-3]\d{2}px$)');
//Select all NON block-level DIVs:
$('div:not(:regex(css:display, ^block$))');
//Add data property to all images (just an example);
$('img').each(function(){
$(this).data('extension', $(this)[].src.match(/.(.{1,4})$/)[1]);
});
//Select all images with PNG or JPG extensions:
$('img:regex(data:extension, png|jpg)');
|
width |
$('div:width(>200)'); //Select all DIVs that have a width greater than 200px
// Alternative usage:
$('div:width(>200):width(<300)'); //Select all DIVs that have a width greater
//than 200px but less than 300px
|
data |
$(':data(dom)'); //All elements with 'dom' flag
$('div:data(dom)'); //All DIV elements with 'dom' flag
$(':not(:data(dom))'); //All elements WITHOUT 'dom' flag
$(':data(ABC=123)'); //All elements with a data key of 'ABC' equal to 123
//Let's assume we have slightly varying data across a set of elements:
$('div').each(function(i){
$(this).data('divInfo','index:' + i);
// Will result in value being 'index:0', 'index:1', 'index:2' etc. etc.
});
//We can select all of those DIVs like this:
$('div:data(divInfo=/index:\d+/)');
//Note: It's necessary to use non-literal notation when writing these
//regular expressions, so if you want to match a real backslash you'd
//have to use '\\'. Similarly if you want to test for all digit's
//you'd have to use \d instead of d.
//Additionally, you can select elements on a basis of whether or not they have ANY data applied to them
$(':data'); //All elements with data
$(':not(:data)'); //All elements without data
|
isValidCreditCard |
$('#credit-card').isValidCreditCard() //==> true/false
|
isValidEmail |
$('#email').isValidEmail() //==> true/false
|
isValidPhone |
$('#input').isValidPhone() //==> true/false
|
isValidPassword |
$('#input').isValidPassword() //==> true/false
//it uses the following regex for validation
// /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,16})$/ //6-16 characters, one lower case, one upper case, one digit
|
isValidDate |
//must pass in the format, otherwise MM/DD/YYYY will be used
$('#input').isValidDate('MM-DD-YYYY') //==> true/false
|
setPhone |
$('#phone').setPhone(); //sets an event listener for the 'keyup' event to format the
//the value according to (555) 555-5555 x11111
|
setMask |
$('#phone').setMask('(000) 000-0000'); //1234567890 --> (123) 456-7890
|
enableInputMask |
$('#phone').enableInputMask('phone'); //sets a mask to the input field according to UTILS.inputMask.phone
//this means that the input will be constricted
|
allowTabbing |
$(textarea).allowTabbing(); //allow tabbing inside textarea (not to jump to the next input field)
|
capitalize |
$('#input').capitalize('one'); //converts first character of the first word to Uppercase
$('#input').capitalize('all'); //converts the first character of every word to Uppercase
|
limitByCount |
$('#textarea).limitByCount({ limit:100, splitBy:'word' }); //word count
$('#textarea).limitByCount({ limit:100, splitBy:'char' }); //character count
|
setCenter |
$('#div').setCenter(); //center a div
$('#div').setCenter({ x:10, y:10 }); //offset div from center by 10px right, 10px down
$('#div').setCenter(null,$parent); //center div within the parent
|
ignore |
$('ul').ignore('li').text(); //ignore children
|
nextNodeByClass |
//select first LI and then select the next elm (not necessarily a sibling) with the class .red-li
$('ul').find('li:first').nextNodeByClass('red-li');
|
prevNodeByClass |
//select first LI and then select the previous elm (not necessarily a sibling) with the class .red-li
$('ul').find('li:first').prevNodeByClass('red-li');
|
fetch |
//native fetch implementation ( or polyfill https://github.com/github/fetch )
var url = '/api/update',
options = {
method: 'GET', //optional --> defaults to GET (if POST, parameters will be passed as formData)
content_type: 'application/json', //optional --> defaults to 'application/x-www-form-urlencoded;charset=UTF-8'
data: {
method: 'getContentByTabName',
animal_id: 5
}
};
$.fetch(url,options).then(_onSuccess).catch(_onError);
|
putCursorAtEnd |
//focuses the input field and puts the cursor at the end of the text
$('input').putCursorAtEnd();
|
attachTransitionEvent |
//attaches an event listener to the DOM elm that fires when a particular transition finished running
$('.aside')
.attachTransitionEvent('right')
.on('midway', event => { console.log('transition has completed the initial motion'); })
.on('completed', event => { console.log('transition is back to the initial state'); })
|
Extending Lodash
Method |
Code |
---|---|
isWindow |
_.isWindow() //==> true/false
|
createArray |
_.createArray('1,2,3') //==> [1,2,3]
|
forceArray |
_.forceArray(arguments) //==> true array of arguments
|
joinArray |
_.joinArray([1,2,3],'+') //==> '1+2+3'
|
isIn |
_.isIn([1,3,6],5) //==> false
//greedy comparison
_.isIn(['1','3','5','6'],5,true); //==> false (as it compares by ===)
_.isIn(['1','3','5','6'],5,false); //==> true (as it compares by ==) ... default setting
//Array.prototype.isIn --> [1,2,3].isIn(3);
|
compare |
_.compare([1,2,3],[1,3,2]) //==> true
//Array.prototype.compare --> [1,2,3].compare([3,2]);
|
reGroup |
_.reGroup(['aa.omega','aa.delta','bb.alpha','bb.bravo','cc.11','cc.alpha','cc.beta','aa.gamma'],'.');
//==> [
["aa.omega","aa.delta","aa.gamma"],
["bb.alpha","bb.bravo"],
["cc.11","cc.alpha","cc.beta"]
]
//Array.prototype.reGroup --> ['aa.omega','bb.alpha','cc.beta'].reGroup('.');
|
Native Methods
Method |
Code |
---|---|
UTILS.values |
numbers: '1234567890',
letters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
special: ' .,-!@#$%&()?/":;\'',
url: '?/-_.#,%&()+=!@*$:;',
regex: {
text: /^([a-zA-Z]+)$/,
email: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,
url: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/, //#ffffff or #fff
ip: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
pwd: /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,16})$/ //6-16 characters, one lower case, one upper case, one digit
}
|
UTILS.isRetina |
UTILS.isRetina(); //=> whether the screen is a retina scrceen --> true/false
|
UTILS.isMobile |
UTILS.isMobile(); //=> whether the device used is a mobile device --> true/false
|
UTILS.isValidCreditCard |
UTILS.isValidCreditCard('123456'); //=> whether the card number is valid --> true/false
|
UTILS.isValidEmail |
UTILS.isValidEmail(); //=> whether the card number is valid --> true/false
|
UTILS.isValidPhone |
UTILS.isValidPhone('123-456-7890'); //=> whether it's a 10-digit number --> true/false
|
UTILS.isValidPassword |
UTILS.isValidPassword('123abc'); //=> whether the password satisfies the UTILS.values.regex.pwd requirements --> true/false
|
UTILS.isValidDate |
UTILS.isValidDate('03-15-2018','MM-DD-YYYY'); //=> whether the date format is valid --> true/false
//@format defaults to MM/DD/YYYY
|
UTILS.format.phone |
UTILS.format.phone('1234567890'); //=> //formats the phone number to (123) 456-7890
UTILS.format.phone('1234567890x555'); //=> (123) 456-7890 x555
UTILS.format.phone('1234567890','[000] 000 0000'); //=> [123] 456 7890
//Note, internally this uses UTILS.format.mask to format the string
|
UTILS.format.mask |
//formats a string according to a specific mask
UTILS.format.mask('1234567890','[000] 000 0000'); //=> [123] 456 7890
|
UTILS.format.commafy |
UTILS.format.commafy('1234567.89'); //=> 1,234,567.89
|
UTILS.format.toBoolean |
//converts any value to boolean true/false
//false
UTILS.format.toBoolean(); //=> false
UTILS.format.toBoolean('something'); //=> false
UTILS.format.toBoolean('no'); //=> false
//true
UTILS.format.toBoolean(1); //=> true
UTILS.format.toBoolean('1'); //=> true
UTILS.format.toBoolean('yes'); //=> true
UTILS.format.toBoolean('y'); //=> true
UTILS.format.toBoolean('on'); //=> true
UTILS.format.toBoolean(true); //=> true
UTILS.format.toBoolean('true'); //=> true
|
UTILS.format.toRegex |
//converts a string regex expression into an object
UTILS.format.toRegex('/^-?[0-9]*.?[0-9]+$/gi'); //=> /^-?[0-9]*.?[0-9]+$/gi
|
UTILS.format.shorten |
//shortens the text to the specified length ( delimiter is not inclusive )
UTILS.format.shorten('This is some text to make sure it gets shortened',10,'...'); //=> This is so...
|
UTILS.format.capitalize |
UTILS.format.capitalize('the truth is out there','one'); //=> The truth is out there
UTILS.format.capitalize('the truth is out there','all'); //=> The Truth Is Out There
|
UTILS.format.filterOutHTML |
//cleans the code of any html tags except for the ones set to be ignored
var content = `
|
UTILS.format.urlEncode |
UTILS.format.urlEncode('something to convert'); //=> M4ewtgpgLgFglgOwOYAIohQYxAgbhAJyiA==
|
UTILS.format.urlDecode |
UTILS.format.urlDecode('M4ewtgpgLgFglgOwOYAIohQYxAgbhAJyiA=='); //=> something to convert
|
UTILS.format.lzEncode |
UTILS.format.lzEncode('something to convert'); //=> something%20to%20convert
|
UTILS.format.lzDecode |
UTILS.format.lzDecode('something%20to%20convert'); //=> something to convert
|
UTILS.format.idify |
//mostly used to make sure an ID is a true number
UTILS.format.idify('something'); //=> 0
UTILS.format.idify('123'); //=> 123
UTILS.format.idify(222); //=> 222
UTILS.format.idify(''); //=> 0
|
UTILS.format.compress |
//mostly used to compress content
UTILS.format.compress('some long content'); //=> 'tjfdVrgtcfeXrgtT2FtkV2D'
|
UTILS.format.decompress |
//decompress content
UTILS.format.decompress('tjfdVrgtcfeXrgtT2FtkV2D'); //=> 'some long content'
|
UTILS.format.htmlEncode |
UTILS.format.htmlEncode("something's funny"); //=> //something's funny
|
UTILS.format.htmlDecode |
UTILS.format.htmlDecode('something's funny'); //=> //something's funny
|
UTILS.inputMask.phone |
//uses iMask (imask.js) to apply masks to an input field
UTILS.inputMask.phone($input); //=> applies a mask to the particular input field
//default masks
{ mask:'+0 000-000-0000', startsWith:'1', lazy:false, country:'United States' },
{ mask:'+00 {0} 000-00-0000', startsWith:'49', lazy:false, country:'Germany' },
{ mask:'000-000-0000', startsWith:'', country: 'United States' }
|
UTILS.isValidRegex |
//checks whether a string is a valid regex expression
UTILS.isValidRegex('/^-?[0-9]*.?[0-9]+$/gi'); //=> true
|
UTILS.getCharKey |
_onEscapeKeyPressed(event){
var key = UTILS.getCharKey(event),
if (key===27)
console.log('ENTER has been pressed.');
}
|
UTILS.uuid |
UTILS.uuid(); //=> generates a random id --> da3e-0c22
|
UTILS.asc |
UTILS.asc('a'); //=> 97
|
UTILS.chr |
UTILS.chr(97); //=> a
|
UTILS.dim.show |
UTILS.dim.show(); //=> applies UTILS.Blur to the entire page
|
UTILS.dim.hide |
UTILS.dim.hide(); //=> hides the global UTILS.Blur
|
UTILS.file.ext |
UTILS.file.ext('myfile.doc'); //=> ["doc", index:7, input:"myfile.doc", groups:undefined]
|
UTILS.file.check |
//check for file extensions when uploading a file
UTILS.file.check('mydoc.doc','img'); //=> false
UTILS.file.check('mydoc.png','img'); //=> true
UTILS.file.check('mydoc.xls','doc'); //=> true
//current types and allowed extensions
img: ['jpg','png','bmp','gif','tiff'],
doc: ['doc','rtf','txt','xls','zip'],
vid: ['mpeg','mpg','wmv','avi','rm','mp4','mov','fla','swf','flv','f4v'],
font: ['ttf','otf']
|
UTILS.fn.bind |
UTILS.fn.bind(function(){},scope); //=> binds function to the scope
|
UTILS.fn.bindMethods |
UTILS.fn.bindMethods(this); //=> binds all methods within 'this' scope
|
UTILS.fn.interval |
UTILS.fn.interval(function(){...},interval); //=> same as setInterval
|
UTILS.fn.clear |
UTILS.fn.clear(timer); //=> sets timer to NULL and clears it as Timeout and Interval
|
UTILS.isDefined |
UTILS.isDefined(param); //=> checks if the parametr is undefined or NULL --> true/false
|
UTILS.getURLParams |
// http://utilsjs.com/code/utils?x=5&y=7&subpage=code
UTILS.getURLParams(); //=> {x:"5", y:"7", subpage:"code"}
|
UTILS.addParamToURL |
UTILS.addParamToURL('http://utilsjs.com/code/utils',['g=6','df=567']);
//=> http://utilsjs.com/code/utils?g=6&df=567
UTILS.addParamToURL('http://utilsjs.com/code/utils?x=5&y=7&subpage=code',['g=6','df=567']);
//=> http://utilsjs.com/code/utils?x=5&y=7&subpage=code&g=6&df=567
|
UTILS.getIframe |
UTILS.getIframe($('#iframe_id'));
//=> {
window: iframe window object
document: iframe document object
}
|
UTILS.printDiv |
UTILS.getIframe($('#iframe_id'));
//=> opens the native print window with the content of that div
|
UTILS.createPromise() |
UTILS.createPromise(); //=> returns a Promise object with 'resolve' and 'reject' attached to the object
var promise = UTILS.createPromise();
promise.resolve();
|
UTILS.cookie.create |
UTILS.cookie.create(name,value,days); //=> creates a cookie in the browser
|
UTILS.cookie.read |
UTILS.cookie.read(name); //=> reads a cookie by name
|
UTILS.cookie.erase |
UTILS.cookie.erase(name); //=> removes a cookie by name
|
UTILS.log |
//the main purpose was to be able to enable/disable logging for debugging purposes
//you must define the APP.showLog() method that returns true/false in order to make it work... --> defaults to false
UTILS.log('something'); //=> 21:47:43 something []
UTILS.log('something',{ x:5 }); //=> 21:47:43 something [{...}]
UTILS.log.history //=> keeps log history as an array
|
UTILS.fetch |
//native fetch implementation ( or polyfill https://github.com/github/fetch )
var url = '/api/update',
options = {
method: 'GET', //optional --> defaults to GET (if POST, parameters will be passed as formData)
content_type: 'application/json', //optional --> defaults to 'application/x-www-form-urlencoded;charset=UTF-8'
data: {
method: 'getContentByTabName',
animal_id: 5
}
};
UTILS.fetch(url,options).then(_onSuccess).catch(_onError);
|
UTILS.attachTransitionEvent |
//attaches an event listener to the DOM elm that fires when a particular transition finished running
let $aside = $('.aside');
UTILS.attachTransitionEvent($aside,'right');
$aside
.on('midway', event => { console.log('the transition completed and the $aside is moved into the screen'); })
.on('completed', event => { console.log('the transition completed and the $aside back to its original position (hidden)'); });
|
Extending prototype
Method |
Code |
---|---|
Array | |
Array.prototype.first |
[4,3,5].first(); //==> 4
|
Array.prototype.last |
[4,3,5].last(); //==> 5
|
Array.prototype.min |
[4,3,5].min(); //==> 3
|
Array.prototype.max |
[4,3,5].max(); //==> 5
|
Array.prototype.index |
[4,3,5,10,7].index(5); //==> 2
|
Array.prototype.flatten |
[4,3,5,[2,7]].flatten(); //==> [4,3,5,2,7]
|
Array.prototype.diff |
[4,3,5].diff([3,2]); //==> [4,5]
|
Array.prototype.isIn |
[4,3,5,10,7].isIn(10); //==> true
|
Array.prototype.intersect |
[4,3,5,10,7].intersect([3,2,7]); //==> [3,7]
|
Array.prototype.compare |
[4,3,5].compare([5,4,3]); //==> true
|
Array.prototype.prepend |
[4,3,5].prepend(7); //==> [7,4,3,5]
|
Array.prototype.reGroup |
[4,3,5].reGroup(); //==> [[3],[4],[5]]
|
Function | |
Function.prototype.delay |
var runCleanup = function(text){
console.log(text);
};
runCleanup.delay(2000,'yes!'); //calls the method after 2 sec (one-time)
|
Function.prototype.interval |
var runCleanup = function(text){
console.log(text);
};
runCleanup.interval(2000,'yes!'); //calls the method every 2 sec (repeat)
|
Function.prototype.bind |
var runCleanup = function(text){
console.log(text);
}.bind(this); //binds the method to 'this' scope
|
String | |
String.prototype.urlEncode |
'something to convert'.urlEncode(); //=> something%20to%20convert
|
String.prototype.urlDecode |
'something%20converted'.urlDecode(); //=> something converted
|
String.prototype.lzEncode |
'something to convert'.lzEncode(); //=> M4ewtgpgLgFglgOwOYAIohQYxAgbhAJyiA==
|
String.prototype.lzDecode |
'M4ewtgpgLgFglgOwOYAIohQYxAgbhAJyiA=='.lzDecode(); //=> something converted
|
String.prototype.htmlEncode |
"something to Max's text".htmlEncode(); //=> something to Max's text
|
String.prototype.htmlDecode |
'something to Max's text'.htmlDecode(); //=> something to Max's text
|
String.prototype.sha1Encode |
//one-way encryption
'my password'.sha1Encode(); //=> A2F8F7FA195A080A22A689041DAA8F2044F9F336
|
String.prototype.base64Encode |
'something to convert'.base64Encode(); //=> c29tZXRoaW5nIHRvIGNvbnZlcnQ=
|
String.prototype.base64Decode |
'c29tZXRoaW5nIHRvIGNvbnZlcnQ='.base64Decode(); //=> something to convert
|
String.prototype.fileExtension |
'myfile.doc'.fileExtension() //=> ["doc", index:7, input:"myfile.doc", groups:undefined]
|
String.prototype.capitalize |
'something to convert'.capitalize(); //=> Something To Convert --> defaults to 'all'
'something to convert'.capitalize('one'); //=> Something to convert
|
String.prototype.idify |
//mostly used to make sure an ID is a true number
'something'.idify(); //=> 0
'something'.idify('123'); //=> 123
'something'.idify(222); //=> 222
''.idify(); //=> 0
|
String.prototype.shorten |
//shortens the text to the specified length ( delimiter is not inclusive )
'This is some text to make sure it gets shortened'.shorten(10,'...'); //=> This is so...
|
String.prototype.compress |
//compress long content
'long content'.compress(); //==> 'tcfeXrgtT2FtkV2D'
|
String.prototype.decompress |
//compress long content
'tcfeXrgtT2FtkV2D'.decompress(); //==> 'long content'
|
String.prototype.toRegex |
//checks whether a string is a valid regex expression
'/^-?[0-9]*.?[0-9]+$/gi'.toRegex(); //==> /^-?[0-9]*.?[0-9]+$/gi
|
String.prototype.isValidRegex |
//converts a string regex expression into an object
'/^-?[0-9]*.?[0-9]+$/gi'.isValidRegex(); //==> true
|
Window | |
toBoolean |
//converts any value to boolean true/false
//false
toBoolean(); //=> false
toBoolean('something'); //=> false
toBoolean('no'); //=> false
//true
toBoolean(1); //=> true
toBoolean('1'); //=> true
toBoolean('yes'); //=> true
toBoolean('y'); //=> true
toBoolean('on'); //=> true
toBoolean(true); //=> true
toBoolean('true'); //=> true
|
_log |
//the main purpose was to be able to enable/disable logging for debugging purposes
//you must define the APP.showLog() method that returns true/false in order to make it work... --> defaults to false
_log('something'); //=> 21:47:43 something []
_log('something',{ x:5 }); //=> 21:47:43 something [{...}]
_log.history //=> keeps log history as an array
|