JavaScript Utils - acegyver/utils GitHub Wiki

#####Collection of useful and either frequently or rarely used JavaScript snippets.

Please, feel free to use any on my hand-made and hand-collected snippets in any of your work – whether it's for private or commercial use. We're all in this together, right? So why not help each other out?

For bug reporting, problems, issues, suggestions, you can reach me on Twitter as @webgyver.

What is JavaScript?

  • Platform-independent, event-driven, interpreted client-side scripting language
  • General purpose programming language to control the behavior of software objects
  • Most widely used in web browsers, whose software objects tend to represent a variety of HTML elements in a document (and the document itself)

Declare a scoped namespace

;window.utils = (function($, win, doc, undefined){
    // do stuff here . . .

    function myFnctn(){
         return 'You are such a hacker.';
     }

     return{
        myFnctn: myFnctn
     }

})(jQuery, window, document);

Clean and quick & dirty way to get the current page name

function getPageName(){
    var wPath = window.location.pathname;
    try{
        var wPage = wPath.substring(wPath.lastIndexOf('/') + 1);
        if(wPage !== ''){
            return wPage;
        }else{
            console.log('There is no page name reference available through the URI.');
        }
    }catch(e){
        console.log("Cannot get the page name for this window location.")
    }
}

Get the Current URL

function thisURL(a){
    //  window.location.protocol = "http"
    //  window.location.host = "css-tricks.com"
    //  window.location.pathname = "example/index.html"
    if(a == 0){
        var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;
        return newURL;
    }else{

        if(a == 1){
            var pathArray = window.location.pathname.split( '/' );
            var secondLevelLocation = pathArray[0];
        }

        if(a == 2){
            var newPathname = "";
            for ( i = 0; i < pathArray.length; i++ ){
                newPathname += "/";
                newPathname += pathArray[i];
            }
        }
    }
}

Clean and quick & dirty way to find out whether a specific value is a number

function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

Determine whether a specific value is null, undefined or just white space

function isEmpty(str){

    var bad = false;

    if(isNumber(str.length)){
        if(str.length < 1){
            bad = true;
        }else{
            bad = false;
        }
    }

    if(!str){
        bad = true;
    }else{
        bad = false;
    }

    var bl = /^\s*$/;

    var isBlank = bl.test(str);
    if(isBlank){
        bad = true;
    }else{
        bad = false;
    }

    return bad;
}

Reverse a string

var s = "I like that!"
s.split("").reverse().join("");

// result: "!taht ekil I"

Trim an input string (or any string)

//Usage: trimString( $('#thisUserName').val() );

function trimString(str){
    if(isEmpty(str)){
        var str = str.replace(/^\s\s*/, ''), ws = /\s/, i = str.length;
        while( ws.test( str.charAt(--i) ) );
        return str.slice(0, i + 1);
    }
}

Truncate a string either by chopping off characters or words

// USAGE:
// var myStr = 'Supercalifragilisticexpialidocious';
// strTruncate(myStr, 10, '...', 'char')

//      var myPhrase = 'The brown lazy fox went to Walmart.'
//      strTruncate(myPhrase, 10, '...', 'word')


function strTruncate(str, length, suffix, typeOfText) {
    if(str.length <= length) {
        return str;
    }
    if(suffix == undefined) {
        suffix = '...';
    }
    if(typeOfText == "char"){
        return str.substr(0, length).replace(/\s+?(\S+)?$/g, '') + suffix;
    }else if(typeOfText == "word"){
        //trim the string to the maximum length
        str = str.substr(0, length);
        //re-trim if we are in the middle of a word
        str = str.substr(0, Math.min(str.length, str.lastIndexOf(" "))) + suffix;
        return str;
    }
}

Replace Multiple Blank Spaces Within A String With One Space Only

function oneSpace(str){
    var str = str.replace( / +/g, ' ' );
    return str;
}

Clean and Quick & Dirty Way To Capitalize Every Word In A Long String

function toTitleCase(str){
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

Validate An E-mail Address

// USAGE: verifyEmail($('#emailField').val() );
function verifyEmail(v){
    var status = false;
    if( !(/^([a-z0-9])([\w\.\-\+])+([a-z0-9])\@((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(v) ) ){
        status = false;
    }else{
        status = true;
    }
     return status;
}

Retrieve the Value of a Group of Radio Buttons

(without waiting for any kind of event, such as click, hover, mouseenter, etc.)

// USAGE: getCheckedValue( $('.userRadios' );
function getCheckedValue(radioObj){
    var ro = radioObj;
    var selected = $("input[type='radio'][name='" + ro+ "']:checked");
    if( isNum(selected.length) ){
        if (selected.length > 0){
            roVal = selected.val();
        }
    }
}

Find Any Object's Top & Left Position

//  var x = getOffset( document.getElementById('hostName') ).left;
//  console.log(x);
function getOffset( el ){
    var _x = 0, _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ){
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.parentNode;
    }
    return { top: _y, left: _x };
}

Cross-browser Method To Get The Document Height Of A Web Page

// That's The Height Of Entire Web Page - Not Just What You See In The Browser Window
// But If The Conent Is Smaller Than The Browser Window,
// Document Height And Window Height Will Be The Same)
// USAGE:      var gdh = $.getDocHeight();

function getDocHeight(){
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

Cross-browser Method To Get The Window Dimensions (height & width)

// USAGE:
// console.log(wndsize().height);
// console.log(wndsize().width);

function wndsize(){
    var w = 0;
    var h = 0;
    //IE
    if(!window.innerWidth){
        if(!(document.documentElement.clientWidth == 0)){
            //strict mode
            w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
        }else{
            //quirks mode
            w = document.body.clientWidth;h = document.body.clientHeight;
        }
    }else{
        //w3c
        w = window.innerWidth;h = window.innerHeight;
    }
    return {width:w,height:h};
}

Cross-browser Method To Center An Element In The Browser Window

// USAGE:
// Center An Element By Providing Its Width & Height
// The Return Values Are The Element's X / Y Coordinates
//      var center = wndcent({width:800,height:550});
//      console.log( center.x );
//      console.log(center.y);

function wndcent(){
    var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
    var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
    //IE
    if(!window.pageYOffset){
        //strict mode
        if(!(document.documentElement.scrollTop == 0)){
            offsetY = document.documentElement.scrollTop;
            offsetX = document.documentElement.scrollLeft;
        }else{
        //quirks mode
            offsetY = document.body.scrollTop;
            offsetX = document.body.scrollLeft;
        }
    }else{
        //w3c
        offsetX = window.pageXOffset;
        offsetY = window.pageYOffset;
    }
    _x = ((wndsize().width-hWnd.width)/2)+offsetX;
    _y = ((wndsize().height-hWnd.height)/2)+offsetY;
    return{x:_x,y:_y};
}

In All Browsers It Is Necessary To Use The Offsettop And Offsetleft Of The Element.

These Properties Give The Coordinates Relative To The Offsetparent Of The Element.

The Script Moves Up The Tree Of Offsetparents And Adds The Offsettop And Offsetleft Of Each

Eventually, Regardless Of The Actual Composition Of The Offsetparent Tree, this Leads To The Real Coordinates Of The Element On The Screen.

function findPosX(obj){
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

function findPosY(obj){
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

Smaller & Simpler Cookie Code###

// USAGE:
//      window.createCookie = createCookie;
//      window.readCookie = readCookie;
//      window.eraseCookie = eraseCookie;

function createCookie(name,value,days){
    var specialDays = days.toString();
    if(specialDays.indexOf('GMT') >= 0){
        var now = new Date(), time = now.getTime(), edate = 0;
        //  ONE HOUR
        //  time += 3600 * 1000; now.setTime(time);
        //  FOUR HOURS
        time += 4 * (3600 * 1000); now.setTime(time);
        edate = now.toGMTString();
        var expires = "; expires="+edate;
    }else{
        if (days){
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name){
    createCookie(name,"",-1);
}

If you are using this in a scoped namespace . . .

Don't forget to return (export) the functions to make them globally available. Like so:

return{

    getPageName:        getPageName,
    thisURL:            thisURL,
    isNumber:           isNumber,
    isEmpty:            isEmpty,
    trimString:         trimString,
    strTruncate:        strTruncate,
    oneSpace:           oneSpace,
    verifyEmail:        verifyEmail,
    toTitleCase:        toTitleCase,
    getCheckedValue:    getCheckedValue,
    getOffset:          getOffset,
    getDocHeight:       getDocHeight,
    wndsize:            wndsize,
    wndcent:            wndcent,
    findPosX:           findPosX,
    createCookie:       createCookie,
    readCookie:         readCookie,
    eraseCookie:        eraseCookie
}

Simple Obfuscation

;"use strict";jQuery.base64=(function($){var _PADCHAR="=",_ALPHA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_VERSION="1.0";function _getbyte64(s,i){var idx=_ALPHA.indexOf(s.charAt(i));if(idx===-1){throw"Cannot decode base64"}return idx}function _decode(s){var pads=0,i,b10,imax=s.length,x=[];s=String(s);if(imax===0){return s}if(imax%4!==0){throw"Cannot decode base64"}if(s.charAt(imax-1)===_PADCHAR){pads=1;if(s.charAt(imax-2)===_PADCHAR){pads=2}imax-=4}for(i=0;i<imax;i+=4){b10=(_getbyte64(s,i)<<18)|(_getbyte64(s,i+1)<<12)|(_getbyte64(s,i+2)<<6)|_getbyte64(s,i+3);x.push(String.fromCharCode(b10>>16,(b10>>8)&255,b10&255))}switch(pads){case 1:b10=(_getbyte64(s,i)<<18)|(_getbyte64(s,i+1)<<12)|(_getbyte64(s,i+2)<<6);x.push(String.fromCharCode(b10>>16,(b10>>8)&255));break;case 2:b10=(_getbyte64(s,i)<<18)|(_getbyte64(s,i+1)<<12);x.push(String.fromCharCode(b10>>16));break}return x.join("")}function _getbyte(s,i){var x=s.charCodeAt(i);if(x>255){throw"INVALID_CHARACTER_ERR: DOM Exception 5"}return x}function _encode(s){if(arguments.length!==1){throw"SyntaxError: exactly one argument required"}s=String(s);var i,b10,x=[],imax=s.length-s.length%3;if(s.length===0){return s}for(i=0;i<imax;i+=3){b10=(_getbyte(s,i)<<16)|(_getbyte(s,i+1)<<8)|_getbyte(s,i+2);x.push(_ALPHA.charAt(b10>>18));x.push(_ALPHA.charAt((b10>>12)&63));x.push(_ALPHA.charAt((b10>>6)&63));x.push(_ALPHA.charAt(b10&63))}switch(s.length-imax){case 1:b10=_getbyte(s,i)<<16;x.push(_ALPHA.charAt(b10>>18)+_ALPHA.charAt((b10>>12)&63)+_PADCHAR+_PADCHAR);break;case 2:b10=(_getbyte(s,i)<<16)|(_getbyte(s,i+1)<<8);x.push(_ALPHA.charAt(b10>>18)+_ALPHA.charAt((b10>>12)&63)+_ALPHA.charAt((b10>>6)&63)+_PADCHAR);break}return x.join("")}return{decode:_decode,encode:_encode,VERSION:_VERSION}}(jQuery));

RESTful API Calls Part 1

GET /tickets/12/messages - Retrieves list of messages for ticket #12
GET /tickets/12/messages/5 - Retrieves message #5 for ticket #12
POST /tickets/12/messages - Creates a new message in ticket #12
PUT /tickets/12/messages/5 - Updates message #5 for ticket #12
PATCH /tickets/12/messages/5 - Partially updates message #5 for ticket #12
DELETE /tickets/12/messages/5 - Deletes message #5 for ticket #12

Check if a variable is an object?

if(abc && typeof abc === "object") {
    console.log('abc is an object and does not return null value');
}

What is negative infinity?

In JavaScript, it’s a number, derived by dividing negative number by zero.

Supported Boolean Operators

&&, || and !

The various Data Types in JavaScript?

Number
String
Boolean
Function
Object
Null
Undefined

What does the isNaN function do?

isNaN function will check an argument and return TRUE (1) if the argument does not seem to be a number.

Convert numbers between different bases in JavaScript

Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use:

parseInt ("3F", 16);

Difference between undefined value and null value?

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.

undefined and null are two distinct types:

  1. undefined is a type itself (undefined) while null is an object.

  2. Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programatically.

JavaScript FizzBuzz

for(var i = 0; i <= 100; i++){
    if(i%3===0){
        console.log('Fizz', i);
    }else if(i%5===0){
        console.log('Buzz', i);
    }else if(i%15===0){
        console.log('FizzBuzz', i);
    }
}

jQuery FizzBuzz

$(function(){
    for(i=0;i++<100;$('<p>').text(i%5? s|| i:s+'Buzz').appendTo('body')) s=i%3?'':'Fizz';
});

Use Strict

"use strict";
  • Buzzword for hippsters
  • Still not supported by all web browsers
  • Great for development
  • Works with valid ECMA 3 code

Math

Math.pow(2,3)                     // 8
Math.round(n)                     // round normal
Math.ceil(n)                      // round up
Math.floor(n)                      // round down
Math.max(20,6,7,19,75)             // 75
Math.min(12,3,5,22)                // 3
Math.abs(n)                        // distance from/to zero
Math.floor(1.6)                    // round a number downward to its nearest integer
Math.floor(Math.random() * 100)    // random number  
Math.PI                            // the value of PI 
Math.E
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E     

Primitive Values

No methods. No properties. Not an object

string
number
boolean
undefined

Examples:

"Hello"                                // is a string
new String("Hello")                    // is a String object
var obj = new String("Hello")          // undefined
if(typeof obj === "string){...}
if(typeof "hello" === "string){...}
obj.valueOf()                          // Hello

typeof "object"
typeof "boolean"
typeof "undefined"
typeof "string"
typeof "number"
typeof "function"

A simple example of JavaScript Closure

function calledFunction(passedFunction) {
    passedFunction("newValue");
}

function clickMe() {
    var value = "originalValue";
    alert(value);
    calledFunction(function(externalValue) {
        value = externalValue;
    });

    alert(value);
}

clickMe();

Go ahead, copy and paste this code and run it. You’ll notice that you’ll get two alerts, the first will say “originalValue” and the second “newValue”. This works because we call calledFunction() and pass it another function as an argument. The functions being passed as an argument has access to the value variable and can modify it. Now, we could have called calledFunction() with a setTimeout and the passed function will still have access to the value variable, even though the the calling function is no longer in scope.

####Another example, taking closure into account and doing it right:

function addButtonsWithHandlersGood(numOfButtons) {
    var i, button;

    for(i = 1; i <= numOfButtons; i++) {
        button = document.createElement("button");
        button.innerHTML = "Button " + i;
        button.onclick = (function(x) {
            return function(){
                alert("You just clicked Button " + x);
            };
        }(i));

        document.body.appendChild(button);        
}

}

addButtonsWithHandlersGood(5);

Notice that the onClick function is actually auto-invoked, and the function actually returns another function. This allows us to pass in the value of i into that function as it was when the function was created. Now we will have the correct value for the button when it is clicked.

####Closure & Private Members

Another great use of closure is to create private members. Often you will find yourself in need of private variables that are not available to external sources and can only be accessed from inside your function. The same holds true for private methods (or functions, since we are in JavaScript here). This can be easily achieved with closure.

var namespace = {};
(namespace.someClass = function() {
    var _privateProperty = "some value";

    function _privateMethod() {
        //perform some stuff
    }

    return {
        publicProperty: "some value",
        publicMethod: function publicMethod() {
            //perform some stuff
        }
    }
}()); 

Lets take a closer look at what is going on here. The first thing you’ll notice is that namespace.someClass is equal to an auto invoked function that returns an object literal.

So the function runs it’s course and returns an object that is then assigned to namespace.someClass. _privateProperty and _privateMethod() get "closured" and are now available to someClass, but since their containing function is no longer in scope (i.e. it has run already) they are not available to anyone else. Hence, private members.

###Arrays

 var myArray = [];
 myArray.sort();
 myArray.push();
 myArray.pop();
 myArray.reverse();
 myArray.concat();

Summarize the Contents of a Numeric Array in JavaScript

JavaScript:

Array.prototype.summarize = function(){
    var t = Object(this);
    var total = 0;
    for(var i = 0; i < t.length; i++) {
        total += t[i] << 0;
    }
   return total;
}

myArray = ['1', '2', '3', '4'];
myArray.summarize();

jQuery:

Array.prototype.summarize = function(){
    var t = Object(this);
    var total = 0;
    $.each(t,function(){total+=parseFloat(this) || 0;});
    return total;
}

myArray = ['1', '2', '3', '4'];
alert( myArray.summarize() );

Grab the string value of a field and then display the reversed value in an alert

$(document).ready(function() {
   var ipf = $('.fiddy');

   $(ipf).keypress(function(e) {
      // ENTER KEY
      if (e.which == "13") {            
         // GET VALUE OF INPUT
         var s = $(ipf).val();
         // REVERSE VALUE OF INPUT
         s = s.split("").reverse().join("");
         // ALERT THE REVERSED VALUE            
         alert(s);
      }       
    });

 });

HTML looks like this:

<input type="text" name="fiddy" class="fiddy">

For long-term reusability, extend the String prototype"

String.prototype.reverse = function() {
    var s = "";
    var i = this.length;
    while (i>0) {
        s += this.substring(i-1,i);
        i--;
    }
    return s;
}

Now you can simply write:

"I like that".reverse();

Find the sum of all multiples of 3 and 5 under 1,000.

For example, the sum of multiples of 3 and 5 under 10 would be: 23 (3 + 5 + 6 + 9).

var i=0;
var sumTotal = 0;

for(i=0; i < 1000; i++){
    if(i%3 == 0){
        sumTotal += i;
    }else if(i%5 == 0){
        sumTotal += i;
    }
}

return sumTotal;
⚠️ **GitHub.com Fallback** ⚠️