15 Jun 2015

Safely Attach Event Listeners in Javascript


Code Snippet to add an handler to an event listener
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
function commonjsAddEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function()
        {
            obj["e"+type+fn]( window.event );
        }
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
    else {
        obj["on"+type] = obj["e"+type+fn];
    }
}
 
function commonjsAddEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() 
        { 
            obj["e"+type+fn]( window.event ); 
        }
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
    else {
        obj["on"+type] = obj["e"+type+fn];
    }
}

And below Code Snippet to remove the handler from the event listener
01
02
03
04
05
06
07
08
09
10
11
12
function commonjsRemoveEvent( obj, type, fn ){
    if(obj.removeEventListener){
        obj.removeEventListener( type, fn, false );
    }
    else if(obj.detachEvent){
        obj.detachEvent("on"+type, obj[type+fn]);
        obj[type+fn]=null;
        obj["e"+type+fn]=null;
    }
    else
        obj["on"+type] = null;
}
 
function commonjsRemoveEvent( obj, type, fn ){
    if(obj.removeEventListener){
        obj.removeEventListener( type, fn, false );
    }
    else if(obj.detachEvent){
        obj.detachEvent("on"+type, obj[type+fn]);
        obj[type+fn]=null;
        obj["e"+type+fn]=null;
    }
    else
        obj["on"+type] = null;
}

Get HTML Copy of the Selection


Javascript Code Snippet to get the HTML of the page selected. Usually when we select a text in HTML page, what we get is the rendered text as selection but with this code, we can get its underlying HTML.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// =================================================================
// ++++++++++++     Get Range Selected Nodes    start   ++++++++++++
// ++++++++++++     Courtesy to  Tim Down @tpdown       ++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
function nextNode(node) {
    if (node.hasChildNodes()) {
        return node.firstChild;
    } else {
        while (node && !node.nextSibling) {
            node = node.parentNode;
        }
        if (!node) {
            return null;
        }
        return node.nextSibling;
    }
}
 
function getRangeSelectedNodes(range) {
    var node = range.startContainer;
    var endNode = range.endContainer;
 
    // Special case for a range that is contained within a single node
    if (node == endNode) {
        return [node];
    }
 
    // Iterate nodes until we hit the end container
    var rangeNodes = [];
    while (node && node != endNode) {
        rangeNodes.push( node = nextNode(node) );
    }
 
    // Add partially selected nodes at the start of the range
    node = range.startContainer;
    while (node && node != range.commonAncestorContainer) {
        rangeNodes.unshift(node);
        node = node.parentNode;
    }
 
    return rangeNodes;
}
 
function getSelectedNodes() {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (!sel.isCollapsed) {
            return getRangeSelectedNodes(sel.getRangeAt(0));
        }
    }
    return [];
}
 
// =================================================================
// ++++++++++++     Get Range Selected Nodes    start   ++++++++++++
// ++++++++++++     Courtesy to  Tim Down @tpdown       ++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

function nextNode(node) {
    if (node.hasChildNodes()) {
        return node.firstChild;
    } else {
        while (node && !node.nextSibling) {
            node = node.parentNode;
        }
        if (!node) {
            return null;
        }
        return node.nextSibling;
    }
}

function getRangeSelectedNodes(range) {
    var node = range.startContainer;
    var endNode = range.endContainer;

    // Special case for a range that is contained within a single node
    if (node == endNode) {
        return [node];
    }

    // Iterate nodes until we hit the end container
    var rangeNodes = [];
    while (node && node != endNode) {
        rangeNodes.push( node = nextNode(node) );
    }

    // Add partially selected nodes at the start of the range
    node = range.startContainer;
    while (node && node != range.commonAncestorContainer) {
        rangeNodes.unshift(node);
        node = node.parentNode;
    }

    return rangeNodes;
}

function getSelectedNodes() {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (!sel.isCollapsed) {
            return getRangeSelectedNodes(sel.getRangeAt(0));
        }
    }
    return [];
}

Attach a copy event listener to the Body of html page and call a event handler to process the selected nodes using the getSelectedNodes().

?
1
commonjsAddEvent(document.body,'copy',handleCopyFn) ;
commonjsAddEvent(document.body,'copy',handleCopyFn) ;

Use this code snippet to safely attach and detach handlers to events.




3 Apr 2015

Reverse Engineer Closure Compiled Javascript Code


If you have looked at the javscript source code of Google, you may have noticed that code is not intitutive, like this below code:
?
01
02
03
04
05
06
07
08
09
10
(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};
google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};
google.https=function(){return"https:"==window.location.protocol};google.ml=function(){};
google.time=function(){return(new Date).getTime()};google.log=function(a,b,e,f,l){var d=new Image,h=google.lc,g=google.li,c="",m=google.ls||"";
d.onerror=d.onload=d.onabort=function(){delete h[g]};h[g]=d;if(!e&&-1==b.search("&ei=")){var k=google.getEI(f),c="&ei="+k;
-1==b.search("&lei=")&&((f=google.getLEI(f))?c+="&lei="+f:k!=google.kEI&&(c+="&lei="+google.kEI))}
a=e||"/"+(l||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+c+m+"&zx="+google.time();/^http:/i.test(a)&&google.https()?(google.ml(Error("a"),!1,{src:a,glmm:1}),
delete h[g]):(window.google&&window.google.vel&&window.google.vel.lu&&window.google.vel.lu(a),
d.src=a,google.li=g+1)};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.load=function(a,b,e){google.x({id:a+n++},
function(){google.load(a,b,e)})};var n=0;})();google.kCSI={};
(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};
google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};
google.https=function(){return"https:"==window.location.protocol};google.ml=function(){};
google.time=function(){return(new Date).getTime()};google.log=function(a,b,e,f,l){var d=new Image,h=google.lc,g=google.li,c="",m=google.ls||"";
d.onerror=d.onload=d.onabort=function(){delete h[g]};h[g]=d;if(!e&&-1==b.search("&ei=")){var k=google.getEI(f),c="&ei="+k;
-1==b.search("&lei=")&&((f=google.getLEI(f))?c+="&lei="+f:k!=google.kEI&&(c+="&lei="+google.kEI))}
a=e||"/"+(l||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+c+m+"&zx="+google.time();/^http:/i.test(a)&&google.https()?(google.ml(Error("a"),!1,{src:a,glmm:1}),
delete h[g]):(window.google&&window.google.vel&&window.google.vel.lu&&window.google.vel.lu(a),
d.src=a,google.li=g+1)};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.load=function(a,b,e){google.x({id:a+n++},
function(){google.load(a,b,e)})};var n=0;})();google.kCSI={};
(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){return"https:"==window.location.protocol};google.ml=function(){};google.time=function(){return(new Date).getTime()};google.log=function(a,b,e,f,l){var d=new Image,h=google.lc,g=google.li,c="",m=google.ls||"";d.onerror=d.onload=d.onabort=function(){delete h[g]};h[g]=d;if(!e&&-1==b.search("&ei=")){var k=google.getEI(f),c="&ei="+k;-1==b.search("&lei=")&&((f=google.getLEI(f))?c+="&lei="+f:k!=google.kEI&&(c+="&lei="+google.kEI))}a=e||"/"+(l||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+c+m+"&zx="+google.time();/^http:/i.test(a)&&google.https()?(google.ml(Error("a"),!1,{src:a,glmm:1}),delete h[g]):(window.google&&window.google.vel&&
window.google.vel.lu&&window.google.vel.lu(a),d.src=a,google.li=g+1)};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.load=function(a,b,e){google.x({id:a+n++},function(){google.load(a,b,e)})};var n=0;})();google.kCSI={};

1. Prettify

Now the first step is to Prettify the source code. This is what it looks like after using the Prettify tool.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
(function () {
  google.lc = [
  ];
  google.li = 0;
   
  google.getEI = function (a) {
    for (var b; a && (!a.getAttribute || !(b = a.getAttribute('eid'))); ) a = a.parentNode;
    return b || google.kEI
  };
   
  In = function (a, b, c) {
    a.ma = c ? Kn(b, !0) : b;
  };
   
  Jn = function (a, b, c) {
    b instanceof Ln ? (a.$ = b, gra(a.$, a.ga)) : (c || (b = Mn(b, hra)), a.$ = new Ln(b, 0, a.ga));
    return a;
  };
   
  Nn = function (a) {
    return a.$;
  };
   
  var n = 0;
 }) ();
  
 google.kCSI = {
 };
(function () {
  google.lc = [
  ];

  google.li = 0;
  
  google.getEI = function (a) {
    for (var b; a && (!a.getAttribute || !(b = a.getAttribute('eid'))); ) a = a.parentNode;
    return b || google.kEI
  };
  
  In = function (a, b, c) {
    a.ma = c ? Kn(b, !0) : b;
  };
  
  Jn = function (a, b, c) {
    b instanceof Ln ? (a.$ = b, gra(a.$, a.ga)) : (c || (b = Mn(b, hra)), a.$ = new Ln(b, 0, a.ga));
    return a;
  };
  
  Nn = function (a) {
    return a.$;
  };
  
  var n = 0;
 }) ();
 
 google.kCSI = {
 };

Most modern browser support this feature in Developer Tools. Please read here for How to use Prettify Tool.

2. Javascript Debugger:  Apply breakpoints and find HTML events to insert breakpoint.

3. Find the Function Definition
  1. Copy the code to Notepad++ IDE.
  2. Open the Find tool, Ctrl+ F
  3. Set the 'Match case', 'Wrap around
  4. Set the Search Mode to 'Regular expression' and set the '. matches newline'
  5. Insert the below snippet in the 'Find what:'
1
^\s*funcName\s*=\s*function
^\s*funcName\s*=\s*function
    6. Replace the funcName with the name of the function you want to search.

Note:  Escape the character with '\' backslash for special characters like .,_-*+ etc


1 Feb 2015

Center Align Vertically


 We dont have a responsive vertical central alignment element in HTML, but we can workaround this using a jquery or css.

Jquery Solution
?
1
2
3
4
$( document ).ready(function() {
    $(".vcenter").css("position" ,"relative");
    $(".vcenter").css("top" ,($(".vcenter").parent().height()/2) -($('.vcenter').height()/2) );
});
$( document ).ready(function() {
    $(".vcenter").css("position" ,"relative");
    $(".vcenter").css("top" ,($(".vcenter").parent().height()/2) -($('.vcenter').height()/2) );
});

HTML
1
2
3
4
5
<div>
    <p class="vcenter">
        <strong>Datosys</strong> is a group of engineers who are working on to secure the future of human health and environment.
    </p>
</div>
 

<div>
    <p class="vcenter">
        <strong>Datosys</strong> is a group of engineers who are working on to secure the future of human health and environment.
    </p>
</div>


Output

OR

CSS Solution
?
1
2
3
4
5
6
7
8
.vcenter {
    position: relative;
    top:50%;
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -o-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
}
 .vcenter {
    position: relative;
    top:50%;
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -o-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
}



29 Nov 2014

Unable to Disable DASH in YouTube Center in firefox

The new YouTube feature DASH, has disabled the ability to buffer the entire video, instead now it buffers only a small block. Dont know exactly why YouTube added this feature?, but may be they wanted to help mobile phone users who have 2G/3G Internet Data Connection because they are billed for the data usage by Moblile Service Operators.

Anyway this sucks for the desktop users who have unlimited download Internet Service Connection because:
  • If you want to rewind the video, YouTube has to redownload it again
  • If  you pause the video, YouTube will not continue with the download of the video.
Luckily there is a workaround in disabling this YouTube's  DASH feature, by using YouTube Center, a browser extension that is availble for Firefox, Chrone, Safari and Opera.

Install YouTubeCenter  in Firefox


YouTubeCenter Addon

  1. Download this addon https://addons.mozilla.org/en-us/firefox/addon/youtube-center/
  2. Click on "Add to Firefox" button to install.
  3. Press "Allow" on the permission to install.
  4. After installation is complete, goto "Options" of  YouTubeCenter and then configure the settings.

Disable DASH in YouTubeCenter in Firefox

Some users who have previously installed this addon are not able to disable DASH after the latest update, its because this setting doesn't work well in HTML5 Player mode. For more technical info on Why DASH doesn't work with HTML5 player.

 The following settings will help users to disable the DASH in YouTube.

1. Click on YouTubeCenter "Options" . (Click on Firefox Settings Firefox Settings button >Add-ons >Extensions>YouTubeCenter Options )



2. Disable "DASH Playback" . (Goto "Player" left menu > "General" Tab > "DASH Playback" )
3. Set "Player type" to "Flash".
4. Set "Flash WMode" to "Direct".




5. Disable "Prevent auto-buffering" . (Goto "Player" left menu > "Auto Play" Tab )
6.  Disable "Prevent playlist auto-buffering" . 
7.  Disable "Prevent tab playlist auto-buffering" . 



8. Set "Auto resolution" to anything other than "1080p" and "480p". (Goto "Player" left menu > "Resolution" Tab) . You can set values  to {144p | 240p | 360p | 720p }



9.   Disable "DASH Playback" . (Goto "External Players" left menu > "Embed" Tab > "DASH Playback" ) Likewise repeat the same steps as in step 2 - 8 for "Embedded External Player"




10.  Disable "DASH Playback" . (Goto "External Players" left menu > "Channel" Tab > "DASH Playback" ) Likewise repeat the same steps as in step 2 - 8 for "Channel External Player"

11. Close the YouTubeCenter Settings and Restart the Firefox.


Now start buffering videos in YouTube like the old times.


UPDATE (07-Jan - 2015)
With the latest update of Firefox to 34.0.5 version, this process is not working. We have to wait for new patch update from the Youtube Center Developer



5 Nov 2014

Alert Box in codenameone


 
Dialog.show("Title", "Main content", "Yes", "Exit");
Dialog.show("Title", "Main content", "Yes", "Exit");

Delay code in Java


1
2
3
4
5
try {
 Thread.sleep(2000); //in milliseconds.
} catch(InterruptedException ex) {
 Thread.currentThread().interrupt();
}
try {
 Thread.sleep(2000); //in milliseconds.
} catch(InterruptedException ex) {
 Thread.currentThread().interrupt();
}