Wednesday, October 29, 2014

Code optimizations and new standards

Most of the times the use of some new standards of JavasScript, known as ECMAScript, is constraint by browser compatibility. The latest browsers along with IE from version 9 implement many or all of these new features. See ECMAScript 5 compatibility table.

This post is also about code optimization. One of the most important point to have in mind at coding in JavaScript is to avoid unnecessary repetitions to accelerate execution and save bytes of code.

Lets see some examples of these concepts. These functions do the same in different ways:

Not optimized code:
var retval = false;
if ((window.location.href.toLowerCase().indexOf('/candidate1/list.aspx') > -1) ||
    (window.location.href.toLowerCase().indexOf('/defaultcompany.aspx') > -1) ||
    (window.location.href.toLowerCase().indexOf('/defaultcompanyv2.aspx') > -1)) {
 retval = true;
}
return retval;

Optimized code with JavaScript:
var retval = false,
    _href = window.location.href.toLowerCase(), 
    _a = ['/candidate1/list.aspx','/defaultcompany.aspx','/defaultcompanyv2.aspx'];
for (var i = 0; !retval && i < _a.length; i++) retval = (-1 != _href.indexOf(_a[i]));
return retval;

Optimized code with jQuery:
var _href = window.location.href.toLowerCase();
return $.map(['/candidate1/list.aspx','/defaultcompany.aspx','/defaultcompanyv2.aspx'],function (e) { return _href.indexOf(e) != -1 ? 1 : null; }).length;

Optimized code with JavaScript (ECMAScript 5):
var _href = window.location.href.toLowerCase(), 
return ['/candidate1/list.aspx', '/defaultcompany.aspx', '/defaultcompanyv2.aspx'].some(function (e) {
  return -1 != _href.indexOf(e);
});

Thursday, September 25, 2014

Cross-browser Image preview

To preview an image in browser before uploading it to server.
Tested in HTML5 browsers and IE > 7.
JSFiddle issues an error in IE < 10 so I put the code in here.
jQuery is used in this example.

CSS:

.imgLogoIE
{
  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);
  width:500px;
  height:400px;
}

JavaScript:

var v = navigator.appVersion,
    p = v.indexOf('MSIE'),
    IElt10 = (p != -1 && parseFloat(v.substr(p+5)) < 10);

function LoadPreviewImg (pFile) {
    var _$imgLogo = $('.js_imgLogo');
    if (IElt10) {
        if ('IMG' == _$imgLogo.prop('nodeName')) {
             _$imgLogo.replaceWith('
');
        }
        setTimeout(function () {
            $('.js_imgLogo').get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = pFile.value
        },50);
    }
    else if (pFile.files && pFile.files[0]) {
            var _reader = new FileReader(); 
            _reader.onload = function (e) {
                _$imgLogo.attr('src', e.target.result);
            }
            _reader.onerror = function (e) {
                _$imgLogo.hide();
            }
            _reader.readAsDataURL(pFile.files[0]);
        }
}

HTML:

<form id="form1">
  preview:
        <input onchange="LoadPreviewImg(this)" type="file" />
        <img class="js_imgLogo" />
</form>

Tuesday, July 15, 2014

Class definitions for lesser code

In order to minimize the amount of code is preferable to use private attributes and methods (AA&MM). The next example shows how to do it in a simple way. You can see how to access either private or public AA&MM.

The accessibility boundary of variables in JavaScript starts from the point where they are declared to every function invoked from that point including callbacks and either setTimeout() or setInterval().

If you have to define an instantiable class you may use the definition of the dynamic class called MainClass in this example:

function MainClass () {
     // ------------------------------------ Private attributes & methods
     var me = this,
         privateVar = 1;
     function init() {
        bindEvents();
     }
     function bindEvents() {
        $('.aSelector').on('click', ClickOn_aSelector);
     }
     function ClickOn_aSelector(e) {
         e.preventDefault();
         privateFunc();
         me.publicMethod();
         // "me." allows to access public methods or attributes 
         //       from either private or public methods.
     }
     function privateFunc () {
       console.log(privateVar);
       console.log(me.publicAtt);
     }
     // ------------------------------------ Public attributes & methods
     this.publicAtt = 2;
     this.publicMethod = function () {
        var _myself = this;
        privateFunc();
        _myself.publicMethod2(3)
     };
     this.publicMethod2 = function (pNum) {
        console.log (privateVar + this.publicAtt + pNum); // 6
     };
     //
     init();
  };

var oMainClass = new MainClass();
oMainClass.publicMethod();

Thursday, February 20, 2014

Tuesday, February 18, 2014

Shuffle an array

A very simple and useful technique:
aIndexes.sort(function () { 
  return .5 - Math.random(); 
});

Monday, February 17, 2014

Filter a list by typed text

This is used to show the rows in a list that match a given text and hide the rest.
The typed text is marked in bold on every shown row.

HTML:

JavaScript:

Demo: