Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Thursday, September 10, 2015

Great JS frameworks infographic

Here is a great infographic that is very useful when choosing an adequate JS framework for your projects: http://www.webdesigndegreecenter.org/choosing-javascript-framework/

Wednesday, January 21, 2015

Tuesday, February 4, 2014

Wednesday, September 4, 2013

Javascript: Decode character pressed from keydown()'s event handler

Use:
// 'event' comes from handler params
var character = String.fromCharCode(event.which): // 'character' has the pressed char

Resource: http://stackoverflow.com/questions/2220196/how-to-decode-character-pressed-from-jquerys-keydowns-event-handler

Thursday, July 25, 2013

Javascript: Disable backspace key in browsers

Use:

 $(document).keydown(function (e) {
        var nodeName = e.target.nodeName.toLowerCase();

        if (e.which === 8) {
            if (((nodeName === 'input' && (e.target.type === 'text' || e.target.type === 'email')) ||
            nodeName === 'textarea') && e.target.readOnly == false) {
                // do nothing
            } else {
                e.preventDefault();
            }
        }
    });

Reference:
http://stackoverflow.com/questions/6309693/disabling-backspace-key-works-in-all-browsers-but-ie

Monday, May 27, 2013

Javascript: Converting .NET DateTime to Javascript Date Object

User this:

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/; 
var m = re.exec(jsonDate); 
var d = new Date(parseInt(m[0]));

Resource:
http://stackoverflow.com/questions/1016847/converting-net-datetime-to-json

MomentJS: convert from javasript date object to formated String

var myDateObject = new Date();
var myMomentJSFormat = "DD/MM/YYYY hh:mm";
        var myMomentObject = moment(myDateObject);
        // formated using moment.js
        var myMomentObjectFormated = myMomentObject.format(myMomentJSFormat);

Resources:
http://momentjs.com/docs/#/displaying/format/


Tuesday, April 2, 2013

Javascript: random number in a given range

// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Source:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random

Javascript: Sort Array of Objects by Field Value


var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

- Sort by employee age


employees.sort(function(a, b){
 return a.age-b.age
})


- Sort by employee name


employees.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
 if (nameA < nameB) //sort string ascending
  return -1 
 if (nameA > nameB)
  return 1
 return 0 //default return value (no sorting)
})


- Sort by employee name



employees.sort(function(a, b){
 var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
 if (nameA < nameB) //sort string ascending
  return -1 

 if (nameA > nameB)
  return 1
 return 0 //default return value (no sorting)
})

- Sort by date (retirement date)

employees.sort(function(a, b){
 var dateA=new Date(a.retiredate), dateB=new Date(b.retiredate)
 return dateA-dateB //sort by date ascending
})

References:
http://www.javascriptkit.com/javatutors/arraysort2.shtml
http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript






Thursday, January 3, 2013

Javascript: clone array

To clone an array in javascript you can use the slice() method:


var a = [ 'apple', 'orange', 'grape' ];
var b = [];

b = a.slice(0);
b[0] = 'cola';

console.log(a);//[ 'apple', 'orange', 'grape' ]
console.log(b);//[ 'cola', 'orange', 'grape' ]


Resource:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
http://www.xenoveritas.org/blog/xeno/the-correct-way-to-clone-javascript-arrays

Friday, November 2, 2012

Javascript: sleep php like function for javascript


Use hold() method from StratifiedJS:

<script src="http://code.onilabs.com/apollo/0.13/oni-apollo.js"></script>
<script type="text/sjs">
  for (var i = 1; i < 4; i++) {
      alert(i);
      hold(1000);
  }
</script>

Reference:
http://stackoverflow.com/questions/10690801/sleep-function-in-javascript-without-using-recursion
http://onilabs.com/stratifiedjs

Thursday, November 1, 2012

Javascript: handling static methods and instance methods

<html>
    <head>
    </head>
    <body>        
        <script type="text/javascript">                
            
            // Calculator1 "class" declaration
            function Calculator1(){
                /* instance multiply sum that will be available for the
                Calculator1 objects but not for the Calculator1 "class" */
                this.multiply = function(val1 , val2){
                    return (val1*val2);
                }
            }
            
            /* instance method sum that will be available for the
            Calculator1 objects but not for the Calculator1 "class" */
            Calculator1.prototype.sum = function(val1 , val2){
                return (val1+val2);
            }
            
            // calculator1 object/instance
            var calc1 = new Calculator1();
            
            // call to multiply, that is an instance method
            console.log(calc1.multiply(4,3)); // 12
            
            /* error because multiply is an instance
            method not a Calculator1 "class" method */
            //console.log(Calculator1.multiply(4,3)); 
            
            // call to sum, that is an instance method
            console.log(calc1.sum(4,3)); // 7
            
            /* error because sum is an instance method
            not a Calculator1 "class" method */
            //console.log(Calculator1.sum(4,3)); 
            
            // Calculator2 "class" declaration
            function Calculator2(){}
            
            // static method of the "class" Calculator 2
            Calculator2.multiply = function(val1 , val2){
                return (val1*val2);
            }
            
            var calc2 = new Calculator2();
            
            // call to multiply, that is a Calculator2 "class" method
            console.log(Calculator2.multiply(4,3)); // 12
            
            /* error because multiply is a Calculator2 "class" method
              not an instance method and it doesn't get inherited to be called
              from instances, it can only be called from the Calculator2 "class" */       
            //console.log(calc2.multiply(4,3)); 
                    
        </script>    
    </body>
</html>

Resources:

Wednesday, October 31, 2012

Javascript: convert from string to integer

Use parseInt:

var myString = "34";
var myIntegerFromString = parseInt(myString); // 34 (integer)

console.log("myString ");
console.log(myString); // 34
console.log(typeof myString); //string

console.log("myIntegerFromString ");
console.log(myIntegerFromString); // 34
console.log(typeof myIntegerFromString); //integer

Resource:
http://www.javascripter.net/faq/convert2.htm
http://www.javascriptkit.com/javatutors/determinevar2.shtml


Monday, October 22, 2012

Javascript: count number of attributes of an Object

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
var myObjectPropertiesCount = 0;
         
 for (var myObjectElement in myObject){
      myObjectPropertiesCount++;
 }

console.log(myObjectPropertiesCount);//3

Resource:
http://stackoverflow.com/questions/1345939/how-do-i-count-a-javascript-objects-attributes


Tuesday, October 9, 2012

ExtJS4.1 : Uncaught TypeError: Cannot call method 'getWidth' of undefined


I created a formpanel, which has a predefined width and height:

var myCrearUsuarioFormPanel = Ext.create('WebMonitorClass.view.CrearUsuarioFormPanel');

Know I needed to put my myCrearUsuarioFormPanel into a window. I needed to set the window width and height the same as the myCrearUsuarioFormPanel width and height:
                         
                            var myWindow = Ext.create("Ext.Window",{
                                width : myCrearUsuarioFormPanel.getWidth() //  here I tried that
                                ,height: myCrearUsuarioFormPanel.getHeight() // here I tried that
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : false                                
                                ,items:[myCrearUsuarioFormPanel]
                            }).show();

But I Got:

Uncaught TypeError: Cannot call method 'getWidth' of undefined 

in this line

width : myCrearUsuarioFormPanel.getWidth()

The solution is to use the offsetWidth and offsetHeight properties:


                          var myWindow = Ext.create("Ext.Window",{
                                width : myCrearUsuarioFormPanel.offsetWidth // Here is the solution
                                ,height: myCrearUsuarioFormPanel.offsetHeight // Here is the solution
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : false                                
                                ,items:[myCrearUsuarioFormPanel]
                            }).show();

Resource:
http://stackoverflow.com/questions/5249723/wrong-div-width-when-getting-it-with-javascript
http://stackoverflow.com/questions/10634282/in-extjs-when-dragdrop-offsetwidth-is-null-or-not-an-object-error-for-ie7

Sunday, October 7, 2012

Javascript: substring


var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7));

Reference:
http://www.w3schools.com/jsref/jsref_substring.asp

Javascripy: simple encode/decode Json LIbrary

Use the Extjs JSON library

// create new object
var myObject = new Object();
// set properties to the object
myObject["RB"] = "(aBc+ABC)";
myObject["RA"] = "(aBC+AbC)";
myObject["SA"] = "(abc+ABc)";
myObject["SB"] = "(abC+Abc)";
//from javascript object to json text:
var myJsonString = Ext.JSON.encode(myObject);


//from jsontext to javascript object
var myResponseString = '{"RB":"(aBc+ABC)","RA":"(aBC+AbC)","SA":"(abc+ABc)","SB":"(abC+Abc)"}';
var myResponseObject = Ext.JSON.decode(myResponseString);
alert(myResponseObject["RB"]) // "(aBc+ABC)"
alert(myResponseObject["RA"]) // "(aBC+AbC)"
alert(myResponseObject["SA"]) //  "(abc+ABc)"
alert(myResponseObject["SB"]) //  "(abC+Abc)"

Resources:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.JSON
http://www.sencha.com/forum/showthread.php?3333-json-encode-decode

Javascript: Remove Duplicate Values from Array

Using JQuery:


var names = ["Mike","Matt","Nancy","Mike","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
alert(uniqueNames);// ["Mike","Matt","Nancy","Jenny","Carl"];

Resource:
http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array

Javascript: convert numbers to equal ASCII character

Use String.fromCharCode() method:

var myInt = 65;
var myString = String.fromCharCode(myInt); // A

Resource:
http://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript

Javascript: zerofill function

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

Resource: