Friday 23 January 2015

NameSpace in Javascript :

NameSpace in Javascript :
=======================

In order to reduce the number of objects and functions that are added to the global scope in our applications,

using namespaces in JavaScript is definitely a recommended practice. Just like static members,

namespaces don’t have any dedicated syntax built into the language either.

But we’re able to get the same benefits by creating a single global object and adding all our objects and functions to this object.

var AppSpace = AppSpace || {};

AppSpace.Podcast = function {
    this.title = 'Astronomy Cast';
    this.description = 'A fact-based journey through the galaxy.';
    this.link = 'http://www.astronomycast.com';
};

AppSpace.Podcast.prototype.toString = function() {
    return 'Title: ' + this.title;
}

This way we lower the possibility of naming collisions when using our code in conjunction with other JavaScript libraries.

We can also use the same naming conventions for namespaces as in any other programming language that does provide syntactical support.

Suppose we want to use a namespace like “MyCompany.MyApplication.Model”.

We can accomplish this by using the same approach as shown earlier:

var MyCompany = MyCompany || {};
MyCompany.MyApplication = {};
MyCompany.MyApplication.Model = {};

or something like the following:

var MyCompany = MyCompany || {
    MyApplication: {
        Model: {}
    }      
};

However, this approach can become very cumbersome and hard to maintain when our code expands over time.

In order to overcome this issue we can use a general purpose namespace function to achieve the same thing using a single line of code.

var model = namespace('MyCompany.MyApplication.Model');

model.Podcast = function {
    this.title = 'Astronomy Cast';
    this.description = 'A fact-based journey through the galaxy.';
    this.link = 'http://www.astronomycast.com';
};

model.Podcast.prototype.toString = function() {
    return 'Title: ' + this.title;
}

Here’s an example of how we can implement such a namespace function.

function namespace(namespaceString) {
    var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';  
       
    for(var i = 0, length = parts.length; i < length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }
   
    return parent;
}

Using this approach requires less typing and the resulting code also looks less verbose. Some JavaScript libraries,

like YUI and the Dojo Toolkit, provide their own implementations for such a namespace utility function.

I encourage you to take a look at their implementations as well.

Android USB Driver Update

Android USB Driver Update:

Nexus 7 can’t be recognized by MS-Windows via USB
1.Connect your Nexus 7 to your computer's USB port.

2.Right-click on Computer from your desktop or Windows Explorer, and select [Manage].
 http://kmpic.asus.com/images/2013/09/23/96034148-472b-4260-addd-ccfc0a229d81.png

3.Select [Device Manager] in the left pane of the Computer Management window.
4.Locate and expand [ASUS Android Device] in the right pane.
5.Right-click Android Composite ADB Interface and select [Update Driver Software].
http://kmpic.asus.com/images/2013/09/23/06996354-6745-4aed-a697-824625469d33.jpg

6.Click [Browse my computer for driver software] to specify a location. 
http://kmpic.asus.com/images/2013/09/23/8fe2dcc7-94b9-4501-a9ee-2badd775c74b.png       
NOTE : Some time it’s located in Other devices. We have to right click & process follg steps.
7.Click[Let me pick from a list of device drivers on my computer to specify the driver file.
NOTE :
First we have to downlaod USB Driver from http://dottech.org/26188/usb-adb-and-fastboot-drivers-for-windows-for-all-android-phones/#all
Or Nexuz product here Asus. So, I get driver from asus site.
( i.e )relavent Nexux 7 or category. I will enhance this for my blog too. Thanks for your feture post.
http://kmpic.asus.com/images/2013/09/23/3ffde5f9-6752-4011-b648-a8bc4a6d2e18.png

8.Click [USB Composite Device] option and Click on [Next].
http://kmpic.asus.com/images/2013/09/23/c323ff48-fa78-4395-b667-873250ccfa61.png

9.Click [Close] when the update is finished.
http://kmpic.asus.com/images/2013/09/23/fa3025b9-5246-4dd8-bb77-36675d7ff73c.png



Step to install APK in Android Emulator :

Step to install APK in Android Emulator :
=========================================
Step 1-> Run the emulator ( While I created new emulator Now )

step 2-> Paste the apk in SDK manager tools and platform-tools folders.
( To avoid some issues/ error)

Step 3-> Run this command adb CMD:\>install AppName.APK (open eun->cmd)

step 4-> Wait for 2 min it's show Success Message.
Sometimes App icon closed unfortunately.

step 5->But App will run continuous Try

Load an External JavaScript file dynamically calling:

Load an External Javascript file dyanamically calling:
======================================================

<script>

var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="other.js";    // we can pass even folder level js files too. (i.e) foldernamee+"mainjs.js";
oHead.appendChild( oScript);

</script>


For Further Ref:
Thanks for Sharing :
http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html

PHP - How to call external host from local host - Cross Domain Call

How to call external host from local host / (cross domain call from PHP WAMP)
===================================================================

In the JS file have this request :

var request = new XMLHttpRequest();
request.open("POST", endpoint + "/api/version/authedication/userlogin", true);


Here endpoint is external IP / URL for hosted Domain address

So, Make the following changes in WAMP -> Apache -> config -> http.config gile

Below this virtual host:

# Virtual hosts


#Include conf/extra/httpd-vhosts.conf


# Oauth ESA server
ProxyPassMatch ^/(api)(.*) http://23.543.34.34:8480/$1$2
  -> $1 is (api),$2 is http://....

ProxyPassReverse /api/ http://23.543.34.34:8490/$1$2

Exp: => when call link start with api redirect to follwing URL and follwed folder

Uncommand this modules in the same file

LoadModule vhost_alias_module modules/mod_vhost_alias.so

LoadModule proxy_http_module modules/mod_proxy_http.so

LoadModule proxy_scgi_module modules/mod_proxy_scgi.so

etc....

Load / Add JS Dynamically :

Load / Add JS Dynamically :
-----------------------------------

addElement JavaScript Function
==============================
function addElement() {

  var ni = document.getElementById('myDiv');

  var numi = document.getElementById('theValue');

  var num = (document.getElementById('theValue').value -1)+ 2;

  numi.value = num;

  var newdiv = document.createElement('div');

  var divIdName = 'my'+num+'Div';

  newdiv.setAttribute('id',divIdName);

  newdiv.innerHTML = 'Element Number '+num+' has been added! <a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove the div "'+divIdName+'"</a>';

  ni.appendChild(newdiv);

}

removeElement JavaScript Function
=================================

function removeElement(divNum) {

  var d = document.getElementById('myDiv');

  var olddiv = document.getElementById(divNum);

  d.removeChild(olddiv);

}

Input value change by Number Picker based on left right side of text box:

Input value change by Number Picker based on left right side of text box:
========================================================================

Javascript Arithamatic Operation :


Javascript addion word if both the varaible are in Numeric datatype;

when try to make addiona operation in javscript function,

It's consider as string concationation in var + number.


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spinner Control in HTML5 by Mobile DON</title>
<script>
function inc()
{

var inc= document.getElementById('age').value;

inc++;
console.log(inc);
document.getElementById('age').value=inc;
}

function dec()
{

var dec= document.getElementById('age').value;
dec= dec-1;
console.log(dec);
document.getElementById('age').value=dec;
}

</script>
</head>
<body>
   <form>
     <label for="age" >
      <i value="dec" onclick="dec()" >   Minus </i>
      <input type="number" name="age" id="age"  />
      <i value="inc" onclick="inc()" > Plus</i>
     </label>
    </form>
</body>
</html>

Dynamically Load JS/CSS using Javascript Function:

Dynamically Load JS/CSS using Javascript Function:
-----------------------------------------------------------------

<input type="button" onclick="helper()" value="Helper">

   <script language="JavaScript">
   function helper()
   {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.type= 'text/javascript';
      script.src= 'helper.js';
      head.appendChild(script);
   }
   </script>

Load xml data in Javascript

Load xml data in Javascript 
load_xml_data.html:
=====================

<html>

<body>
    <h1>W3Schools Internal Note</h1>
    <div>
        <b>To:</b>  <span id="to"></span>
        <br />
        <b>From:</b>  <span id="from"></span>
        <br />
        <b>Message:</b>  <span id="message"></span>
    </div>

    <script>
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "node.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;
       
        document.getElementById("to").innerHTML = xmlDoc.getElementsByTagName("exitButtonText")[0].childNodes[0].nodeValue;
        document.getElementById("from").innerHTML = xmlDoc.getElementsByTagName("balanceButtonText")[0].childNodes[0].nodeValue;
       // document.getElementById("message").innerHTML = xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
    </script>

</body>

</html>


node.xml:
==========

<?xml version="1.0" encoding="UTF-8" ?>
<node>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>

    <body>Don't forget me this weekend!</body>
</node>




PhoneGap/Cordova Android get screen size after onDeviceReady :

PhoneGap/Cordova Android get screen size after onDeviceReady :
==============================================================
SOLN 1:
=======
function getWindowSizes()
{
  var windowHeight = 0, windowWidth = 0;
 
  if (typeof (window.innerWidth) == 'number') {
      windowHeight = window.innerHeight;
      windowWidth = window.innerWidth;
     
  } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
      windowHeight = document.documentElement.clientHeight;
      windowWidth = document.documentElement.clientWidth;
     
  } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
     windowHeight = document.body.clientHeight;
     windowWidth = document.body.clientWidth;
  }
  return [windowWidth, windowHeight];
}
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1,
width=device-width, height=device-height, target-densitydpi=device-dpi" />




There are a few ways to do it, for example:

    Check window.orientation value
    Compare innerHeight vs. innerWidth

You can adapt one of the methods below.

SOLN 2:
=======

Check if device is in portrait mode

function isPortrait() {
    return window.innerHeight > window.innerWidth;
}

SOLN 3:
=======
Check if device is in landscape mode

function isLandscape() {
    return (window.orientation === 90 || window.orientation === -90);
}

SOLN 4:
=======
Example usage

if (isPortrait()) {
    alert("This page is best viewed in landscape mode");
}

SOLN 5:
=======
How do I detect the orientation change?

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});

Read Json in javaScript using Ajax call

Read Json in javaScript using Ajax call (XMLHttp)

data.json File:
===============

data = '[{"name" : "Harry", "age" : "32"}]';

html file :
============

<!doctype html>
<html>
    <head>
        <title>askyb - Load JSON File Locally by Javascript Without JQuery</title>
        <script type="text/javascript" src="sub/data.json"></script>
        <script type="text/javascript">
function load() {
var mydata = JSON.parse(data);
alert(mydata[0].name);
alert(mydata[0].age);
alert(JSON.stringify(mydata));
}

</script>
    </head>
    <body onload="load()">
        askyb - Load JSON File Locally by Javascript Without JQuery
    </body>
</html>


Example 2: using Ajax Call
===========================

<!doctype html>
<html>
<head>
<script>
function AJAX_JSON_Req( url )
{
    var AJAX_req = new XMLHttpRequest();
    AJAX_req.open( "GET", url, true );
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function()
    {
        if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
        {
            var response = JSON.parse( AJAX_req.responseText );
            document.write( response.name );
        }
    }
    AJAX_req.send();
}

AJAX_JSON_Req('js/people.json');

</script>
</head>
<body>

</body>
</html>

Rotate Screen Orientation detection Device Desktop:

Rotate Screen Orientation Device Desktop:
==============================

<!DOCTYPE html>
<html>

<body>
    <script>
        window.addEventListener("orientationchange", function () {
            var _width = window.innerWidth;
        });
    </script>


    <style>
       
       
        @media screen and (max-width:720px) and (orientation: landscape) {
            body {
                background: url(img/portrait.png) no-repeat center center fixed;
                -webkit-background-size: contain;
                -moz-background-size: contain;
                -o-background-size: contain;
                background-size: contain;
             
            }
        }
       
       
        @media screen and (orientation: landscape) {}
    </style>
</body>

</html>

Toggle_show_hide_same_button


show hide in Same Button ( TOGGLE )
====================================

<a onclick ="javascript:ShowHide('HiddenDiv')" href="javascript:;" >Show/Hide</a>

<div class="mid" id="HiddenDiv" style="DISPLAY: none" >
This text was hidden
</div>

<script language="JavaScript">
function ShowHide(divId)
{
if(document.getElementById(divId).style.display == 'none')
{
document.getElementById(divId).style.display='block';
}
else
{
document.getElementById(divId).style.display = 'none';
}
}
</script>


Show / Hide in seperate Button :
=================================


<a onclick ="javascript:Show('HiddenDiv')" href="javascript:;" >Show</a>

<div class="mid" id="HiddenDiv" style="DISPLAY: none" >
This text was hidden
</div>

<script language="JavaScript">
function Show(divId)
{
if(document.getElementById(divId).style.display == 'none')
{

document.getElementById(divId).style.display='block';
}
}
function hide(divId)
{
if(document.getElementById(divId).style.display == 'block')
{
document.getElementById(divId).style.display = 'none';
}
}
</script>

<a onclick ="javascript:hide('HiddenDiv')" href="javascript:;" >Hide</a>

Toggle image_Javascript

Toggle image_Javascript :
--------------------------------
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
var imageNo = 2;
function swapImage() {
image = document.getElementById('image')
switch (imageNo) {
case 1:
  image.src = "img/back.png"
  imageNo = 2
  document.getElementById('content').style.display = 'none'
  return(false);
case 2:
  image.src = "img/back2.png"
  imageNo = 1
document.getElementById('content').style.display = 'block'
return(false);
}
}
</script>
</head>
<body>

 <h4><a ><img id="image" name="image" src="img/back.png" border="0" onclick="swapImage();"/></a></h4>
<!-- Your normal document content lives here -->
</body>
</html>

Toggle_Play_puase_image_audio_JS

Toggle_Play_puase_image_audio_JS :

<!doctype html>

<html>
<body>
<audio  id="player" src="Kalimba.mp3"></audio>
    <img src="img/volumemute.jpg" class="topbottomicon" onclick="aud_play_pause()" id="image"/>

<script>
function aud_play_pause() {
  var myAudio = document.getElementById("player");
  var image = document.getElementById("image");
  if (myAudio.paused) {
     
    myAudio.play();
      image.src = "img/volume.jpg"
  } else {
    myAudio.pause();
      image.src = "img/volumemute.jpg"
  }
}
</script>
</body>
</html>


Two_images_Toggle_Js

Two_images_Toggle_Js :
==================
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
var imageNo = 2;
function swapImage()
{
image = document.getElementById('back_btn_image');
if(imageNo ==1)
{
  image.src = "img/back.png"
  imageNo = 2;

  return(false);
}
else
{
  image.src = "img/back2.png"
  imageNo = 1;

return(false);
}
}
</script>
</head>
<body>
<h4><a ><img id="back_btn_image" name="back_btn_image" src="img/back.png" border="0" onclick="swapImage();"/></a></h4>
<!-- Your normal document content lives here -->
</body>
</html>

React + Typescript_ Module federation _ Micro Front end -Standalone and integrated

Module Federation The Module Federation is actually part of Webpack config. This config enables us to expose or receive different parts of t...