Tuesday, March 1, 2016

JavaScript: Quick reference



function logt(msg)
{
  if(navigator.appName == "Netscape")
    console.log("[DBG]: " + msg);
  else
    alert("[DBG]: " + msg);
}
------------Method to convert secs to HH MM SS --------------------------------
function getSecsInHHMMSS(secs){
    var hh = ("0" + Math.floor(secs/3600)).slice(-2);
    var mm = ("0" + Math.floor((secs%3600)/60)).slice(-2);
    var ss = ("0" + Math.floor((secs%3600)%60)).slice(-2);
    var hhmmss=hh+":"+mm+":"+ss;
    return hhmmss.toString();
}
//getSecsInHHMMSS(100) will returns  00:01:40

-------------Method to parse the query string --------------------------------------
function getQueryValue(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    logt('Query not found :'+variable);
    return "";
}

//Now make a request to index.html?mins=120
durr=getQueryValue('mins') * 60;
document.getElementById("endtime").innerHTML = getSecsInHHMMSS(durr);

-------------Method to print Key name of JSON obj using values -----------

//This defines a method called getKeyByValue() to any object which
// returns the Key name using value of JSON format
Object.prototype.getKeyByValue = function( value ) {
    for( var prop in this ) {
        if( this.hasOwnProperty( prop ) ) {
             if( this[ prop ] === value )
                 return prop;
        }
    }
}

var test = { Key1:11, Key2:22, Key3:33 }
alert(test.getKeyByValue (33))   # This will print "Key3"