Tuesday 11 August 2015

Loading spinner overlay for hybrid/mobile web applications

Below is the spinner I have implemented in one of my projects. Below are the components you need to place in your respective Javascript, Css and HTML pages -

Javascript:
function showOverlay() {
document.getElementById("OVERLAY_ID").style.display = "block";
}

function hideOverlay() {
document.getElementById("OVERLAY_ID").style.display = "none";
}

CSS:
.overlay {
Spinner Image(loading.gif)
    background-color: grey;
    top:0;
    left:0;
    width:100%;
    height:100%;
    position: absolute;
    -moz-opacity: 0.70;
    opacity:.70;
    filter: alpha(opacity=70);
 }
.loaderPosition {
    margin:0 auto;
    height:42px;
    width:42px;
    position:absolute;
    top:48%;
    left:46%;
 }

HTML:
<div id="OVERLAY_ID" class="overlay" style="display:none">
<img src="img/loading.gif" alt="Loading..." class="loaderPosition">
</div>


jQuery Mobile: Events


Orientation events:

  • At times a user will change the orientation of device when using an application, which could happen as a result of general movement of the device.
  • Orientation events are triggered when you rotate the mobile device vertically or horizontally i.e. change your mobile device orientation.

Example:

$(window).on("orientationchange", function(event){
      alert("Orientation Change");
});



Monday 21 July 2014

Prevent the backspace key from going to the previous page in Ext JS application

If you have an app with just one view in ExtJS(Sencha), there is a possibility that the user will open the app in a browser that they have been using to cruise around the web and the user will likely use the backspace key in your app(say, inside a text box) then you should think about turning off the backspace == url -1 feature.

To disable 'Backspace' key use below JavaScript inside script tag of your html page:

document.onkeydown = KeyCheck;
function KeyCheck(e) {
if (!e) {
e = window.event;
}
var doPrevent = false;
if (e.keyCode === 8) {
var d = e.srcElement || e.target;
if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'EMAIL' )) || d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
} else {
doPrevent = true;
}
}
if (doPrevent) {
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;
}
}

Above code works well for IE and Chrome.


Saturday 21 June 2014

Evolution with Changing Times

Without the correct elucidation of how life evolved on this frabjous planet we have been able to ameliorate our existence. Crawling, walking and now flying high, we have travelled so far. Very long journey indeed from the Big bang to life, caves to glass-houses, worshiping nature to exploiting them, from sunlight to neon lights, giving life to cloning and last but not the least transmogrification of green jungles to cemented ones. Sometimes it's absolutely right to think that with the demise of pharaohs and withering pyramids, man has become the strongest drug for another man. Crossing centuries over centuries, human beings and the natural world have been on the collision course but still the human body is approximately two-third of water. Earth, water, air and fire still retain their power in front of all the deadly weapons and missile. The journey from evolution theory to living in peace and harmony, to cozy life and hi-tech automated world, we have upcoming theories like some forms of cosmic radiation can have a potent effect on our DNA and may precipitate periodic leaps in our evolution due to the induced genetic shifts.

There is no doubt that we are living in unstable times of great and unpredictable change.  We are seeing major cloud bursts, earthquakes, tsunami, volcanic activity, global warming and prolonged drought. Climate change is certainly upon us and of course there are many questions as to cause of this. But, the truth is that the world herself is changing.

"Infosys" can be termed as another beauteous byspel of evolution in modern IT world. With a small start from seven members and with an initial capital of US$ 250 it has grown to become a company of US$ 8.095 billion in 30 years with 1,58,000 employees. Technical evolution has changed the concept of physical labor to intellectual labor. Futurists have worked significantly on genetic engineering, nanotechnology, artificial intelligence and landing on mars and moon. Apt example of our technological dependence is for even writing this essay, we rely on search engines. Goal of evolutionary medicine now is to understand why people get sick, not simply how they get sick. “Why copy old life forms when we can now create new ones?”

We always need a driving force to work and perform better and our present time changing equation is helping our productivity to culminate. Our unceasing struggle to make life cozier, easier have enhanced our thinking and soared our expectations form younger generations. Computing on hands to cloud computing, we have accomplished a lot. Although our physical evolution obstructs us from connecting from distant places but with our super-evolved brain we can cross water, air and ice hindrances. Something that is about living in a more connected way, and moving away from separation, disharmony and greed. Over ages we have evolved from animals to nomads and then civilizing to become great rulers. Unfolding the hidden secrets of nature, our scientists have volunteered their whole life providing us with quantum physics and aerospace technologies, all because we want the best out of available. "Survival for the fittest" theory has incited the motivation to gain more and live more.

Everything haven’t changed completely yet, years ago Ram, Pandavs, Mughals, Hitler, Britishers fought for power, wealth and status on the cost of money and innocent lives and even today we live in a country under unstable and incompetent governance where our so called educated politicians and country shapers are never tired of being in scams. Life is cheaper than a bullet these days, “survival of the fittest” – is being construed to “kill or be killed”. What kind of evolution are we facing? Aggression, war, territorial possession, resource exploitation and separation from nature, deep wounds of poor given by the rich. We feel proud to say we live in harmony and brotherhood in spite of the fact that we believe in forming organizations to avoid wars and maintain balance among the countries rather believing in ourselves. Gurukuls' evolved too, children are now taught how to defeat their rivals in lieu of acquiring knowledge.

There is also an evolution in political will of our country. People from various background – including corporates, actors, army men, chai-wala, sehjada and aam-admi do not hesitate to express their views for the political reform. We have witnessed record breaking enrolment in the voter list across our country this year. Is this the sign of great success this election will bring or, huge amount of despair and frustration post-election?

In present scenario, we have the issue of the petrol prices.  What is going on with the price of a litre of petrol?  Are the oil companies ripping us off?  Or, do we have any oil reserve left?  What is this talk of “peak oil” and a rapidly approaching scarcity of all fossil fuels and mined energy sources – including coal, uranium?

What about global economic crisis?  What is going on with our financial system?  Has the over-speculation of the corporations in United States caught up with us all and tipped the world into another Great Misery?

Lot more questions are being asked. But, the point is – we need to be very careful.  Because maybe, just maybe, these things are not a sign of chaos but are actually showing us that we are getting it right – in a long run. These crises could be an opportunity for real change and positive growth – both individually and as a planet.

At the end what exactly we infer, perhaps we are evolving from Homo-sapiens (the pondering human) to Homo-spiritus (the awakening spiritual human). The massive and accelerating changes going on in the world around us are in fact the fuel for this change. Surely this is a very positive thing. A great time to be alive! As we begin to ride the wave into human redesign, the destination is still largely unknown but the opportunities are almost limitless. . There is no limit to what we can achieve tomorrow and a probability that our next generation would have a quite different definition of "evolution".

The great gift we have with us is – our reasons and our consciousness. Use them well!

Thursday 17 April 2014

Open an external application using IE browser

We can launch a new application using ActiveXObject of the Internet Explorer. Below is the sample code -

<!DOCTYPE html>
<html>
<body>

<p>Click the button to open a new application window.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
 w = new ActiveXObject("WScript.Shell");
          w.run('chrome.exe');
          return true;}
</script>

</body>
</html>

Wednesday 5 February 2014

HTML text box to allow numbers only

We generally encounter the need of functionality where text boxes need to be filled with numbers only(may be for security/validation). We have a easy JavaScript solution for this -

<!DOCTYPE html>
<html>
<script>
 function CheckNumeric(event)
{
    var key = window.event ? event.keyCode : event.which;
    //Check for backspace, delete, left arrow and right arrow keys
    if (event.keyCode == 8  || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39)
    {
        return true;
    }
    //All other keys excluding numeric keys
    else if ( key < 48 || key > 57 )
    {
        return false;
    }
    else return true; //Numeric keys from 0 to 9
};
</script>


<body>
<input type="text" id="txtSample" name="txtSample" onkeypress="return CheckNumeric(event)" />
</body>


</html>


Alternatively, there is one more method to use input types as numbers only. Here you can also set restrictions on what numbers are accepted. Its HTML5 way -
Cons: It is not supported through all browsers and their versions.

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp">
  Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
  <input type="submit">
</form>

<p><b>Note:</b> type="number" is not supported in Internet Explorer 9 and earlier versions.</p>

</body>
</html>

Friday 16 August 2013

SYMBOLS WITH KEYBOARD

Many times we wonder how to make symbols/alt codes with keyboard...
Below are the alt codes we can make. For this you need to press "Alt" key with the combination of numbers on the number pad(numbers on the right side) as show in the picture below -
Alt + 0153..... ™... trademark symbol
Alt + 0169.... ©.... copyright symbol
Alt + 0174..... ®....registered ­ trademark symbol
Alt + 0176 ...°......degre­e symbol
Alt + 0177 ...±....plus-or ­-minus sign
Alt + 0182 ...¶.....paragr­aph mark
Alt + 0190 ...¾....fractio­n, three-fourths
Alt + 0215 ....×.....multiplication sign
Alt + 0162...¢....the ­ cent sign
Alt + 0161.....¡..... ­.upside down exclamation point
Alt + 0191.....¿..... ­upside down question mark

Alt + 1.......☺....sm­iley face
Alt + 2 ......☻.....bla­ck smiley face
Alt + 15.....☼.....su­n
Alt + 12......♀.....female sign
Alt + 11.....♂......m­ale sign
Alt + 6.......♠.....spade
Alt + 5.......♣...... ­Club
Alt + 3.......♥...... ­Heart
Alt + 4.......♦...... ­Diamond
Alt + 13......♪.....e­ighth note
Alt + 14......♫...... ­beamed eighth note
Alt + 8721.... ∑.... N-array summation
Alt + 251.....√.....s­quare root check mark
Alt + 8236.....∞..... ­infinity
Alt + 24.......↑..... ­up arrow
Alt + 25......↓...... ­down arrow
Alt + 26.....→.....ri­ght arrow
Alt + 27......←.....l­eft arrow
Alt + 18.....↕......u­p/down arrow
Alt + 29......↔...left right arrow



How do you do it with your Laptop? Watch it here!
Making HTML text symbols? Click here.


References - 
http://fsymbols.com/
http://text-symbols.com/html/


Monday 1 July 2013

HTML5’s pros and cons compared to native app development

Pros –
  • Supports multimedia without plugin - It is the first version to support multimedia without plugins and has the ability to be “understood” by all computers and devices.
  • HTML5 web apps can be accessed on any device via a web browser - Much like a mobile website.
    These web apps also provide the capability for offline access and usage via application cache, meaning you don’t have to have a network connection to use them.
  • Single web app rather than multiple native apps - Some have predicted the impending demise of the native app.
  • Ability to bypass app stores – This presents an additional advantage for companies that use mobile apps to engage consumers in purchase transactions.
  • Makes things easier - HTML 5 is aimed at making things easier to build search front-ends, wikis, real-time chat, drag-and-drop tools, discussion boards and many other modern web elements into any site, and have them work more efficiently.

 Cons –
  • Security issues - HTML5 web apps are set up in a way that ultra-savvy users could tamper with processing scripts, which might allow unauthorized access. Variables could be altered in a way that would allow hackers to access perks, discounts, etc. for which they really aren’t eligible.
  • Functionality does not rival that of a native app (not yet anyway) - Most say that it’s pretty good, but it’s no native app.  It will be a while yet before web apps can offer the speed and features of a native app.  It’s important to remember that consumers use native apps because they’re easy, fast and convenient. Also, better integration with hardware and other apps.
  • You lose the marketing benefits of being featured in app stores -  If you are a smaller company, new and potential customers are probably more likely to find you if you’re featured in an app store.


Strategic decision-makers for successful apps should weigh the importance of the following:
  1. User experience
  2. Performance
  3. Monetization
  4. Cross platform deployment costs
  5. Fragmentation
  6. Availability of programming expertise
  7. Importance of immediate updates and distribution control
  8. Timeliness of new OS innovations
  9. Security
When does using HTML5 make sense?
The short answer: When the information is always updating; you don’t want Apple or Google as intermediaries, or if the user doesn't want to download an application.

Note: Above comparison may not hold true for hybrid container-based apps that run in a native shell 


Thursday 6 June 2013

Frequently asked PhoneGap/Cordova interview questions

When we talk about PhoneGap/Hybrid mobile app development, it is most probable that the interviewer may also ask about JavaScript, Dojo, jQuery, HTML5, CSS, Sencha, JSON and so on. Be prepared. Below are some questions which I came across -

1. What is PhoneGap and why ?
PhoneGap is a mobile application framework that allows developers to use HTML, JavaScript and CSS to create mobile apps that are present as first-class applications on the phone. That means the mobile apps have their own icons and operate similarly to native applications without a browser frame around them.

They have access to a set of native functions to further make them work like native apps.

Mobile developers use PhoneGap because it allows them to have a common codebase for all their application code. It doesn’t force developers to write code from scratch every time they move from platform to platform.

2. PhoneGap architecture.
PhoneGap has a plugin-based architecture. Each device-specific feature is a plugin, which consists of javascript and native sides. Js side should be as cross-platform as possible, whereas native side can be implemented only once, for 1 device. Nevertheless built-in plugins are developed for all of the most popular platforms, so no need to reinvent the wheel.
This architecture, together with open source code, not only allows a developer to fix their bugs, but also allows them to tweak their plugins for as per requirements. Also, a developer can build his own plugin, and support any platform of his choice.

3. What is the difference between PhoneGap and Cordova?
PhoneGap is a distribution of Apache Cordova. You can think of Apache Cordova as the engine that powers PhoneGap, similar to how WebKit is the engine that powers Chrome or Safari.

4. What is PhoneGap Build, and how is it different from PhoneGap framework?
PhoneGap is a mobile application development framework, based upon the open source Apache Cordova project. It allows you to write an app once with HTML, CSS and JavaScript, and then deploy it to a wide range of mobile devices without losing the features of a native app. PhoneGap Build is a cloud-based service built on top of the PhoneGap framework. It allows you to easily build those same mobile apps in the cloud.

5. What is a Plist file in iOS development ?
Yes, this is not related to phonegap, but interviewer expects the answer!

Property lists are a way of structuring arbitrary data and accessing it at run-time. An information property list is a specialized type of property list that contains configuration data for a bundle. The keys and values in the file describe the various behaviors and configuration options you want applied to your bundle. Xcode typically creates an information property list file for any bundle-based projects automatically and configures an initial set of keys and values with appropriate default values. You can edit the file to add any keys and values that are appropriate for your project or change the default values of existing keys.

For further details click here.

6. What is the difference between ChildBrowser and InAppBrowser in PhoneGap ?
As the name suggests, Child Browser Plugin is a plugin and can be integrated in any phonegap application.

Whereas, InAppBrowser is a phonegap API that provides the ability to spawn a browser instance from a Cordova(2.3.0) application. The API is based on standard browser capability. In a nutshell, this has the same functionality as the ChildBrowser, and has events support as well.
Example usage:
var ref = window.open('http://google.com', '_blank');
ref.addEventListener('loadstart', function(event) { alert(event.type + ' - ' + event.url); } );
ref.addEventListener('loadstop', function(event) { alert(event.type + ' - ' + event.url); } );
ref.addEventListener('exit', function(event) { alert(event.type); } );

// also, you can do ref.removeEventListener('loadstart', myfunc) .. etc

7. What are CDNs in jQuery? Why do we use it?
CDNs(Content Delivery Networks) can offer a performance benefit by hosting jQuery on servers spread across the globe.
There are three CDNs available that host the jQuery library free of charge:
  1. Google’s Libraries API CDN (a.k.a. Google Ajax API CDN)
  2. Microsoft’s Ajax CDN
  3. Media Temple’s ProCDN (the official “jQuery CDN”)
Using jQuery's CDN provided by MediaTemple
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

There are several benefits to using CDNs:
  • The file will normally load faster than it would if self hosted.
  • Odds are better that the site visitor will have a cached copy of the file since other sites will also be linking to the same file.
  • It saves the site owner some bandwidth since the file is externally hosted.
8. Name PhoneGap events
  • deviceready
  • pause
  • resume
  • online
  • offline
  • backbutton
  • batterycritical
  • batterylow
  • batterystatus
  • menubutton
  • searchbutton
  • startcallbutton
  • endcallbutton
  • volumedownbutton
  • volumeupbutton
More details here



References:
http://docs.phonegap.com/
http://phonegap.com/about/faq/
https://cordova.apache.org/




Wednesday 29 May 2013

Commonly asked JavaScript interview questions

1. What is the difference between == and === in javascript ?
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0==false   // true
0===false  // false, because they are of a different type
1=="1"     // true, auto type coercion
1==="1"    // false, because they are of a different type

Null and Undefined types are == (but not ===). [i.e. Null==Undefined (but not Null===Undefined)]

2. null vs undefined in Javascript ?
In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value:

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

3. What are global variables and how are they declared? Also, explain problems using globals?
Global variables are available throughout your code: that is, the variables have no scope. Local variables scope, on the other hand, is restricted to where it is declared (ex-within a function). The var keyword is used to declare a local variable, while omitting the var keyword creates a global variable.

// Declare a local variable
var localVariable = "TechRepublic"
// Declare a global
globalVariable = "NewDelhi"

Most JavaScript developers avoid globals. One reason why is they’re averse to naming conflicts between local and globals, Also, code that depends on globals can be difficult to maintain and test.

4. How do you handle errors in JavaScript?
Exceptions that occur at runtime can be handled via try/catch/finally blocks. This can avoid unfriendly error messages. The finally block is optional and execution is transferred to the catch block of code when/if runtime errors occur. When the try/catch block is finally done, code execution transfers to the finally code block. This is the same way it works in other languages like C# and Java.

try {
// do something
} catch (e) {
// do something with the exception
} finally {
// This code block always executes whether there is an exception or not.
}

5. The onerror Event Handler
JavaScript 1.1 allowed a new event handler named "onerror". This Event Handler allows you to have something happen when the page throws an error.
The onerror event can only be defined inside your JavaScript code as a property of the window object:

<script type="text/javascript">
window.onerror=function(){
 //code to run when error has occured on page
}
</script>

6. Write a 1-line JavaScript code that concatenates all strings passed into a function?
The following function should help achieve the desired result

function concatenate() {
return String.prototype.concat.apply('', arguments);
}

7. What are windows object and navigator object in JavaScript?
The window object represents an open window in a browser.
Windows object is top level object in Java script and contains several other objects such as, document, history, location, name, menu bar etc., in itself. It is the global object for Java script that is written at client-side. For more details, click here.

The navigator object contains information about the browser.
navigator.appName - Gives the name of the browser
navigator.appVersion - Gives the browser version
navigator.appCodeName - Gives the browser codename
navigator.platform - Gives the platform on which the browser is running
For more details, click here.

8. Difference between window.onload and onDocumentReady?
The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.
If you just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows you to do that.


Wednesday 1 May 2013

amCharts vs Chart.js - Visuals

I was just going through chartjs.org(Open source HTML5 charts using canvas tag) and found it very useful. Its good for small/medium chart usage(supports only 6 chart types as of now). But, being a fan of amCharts, I started comparing some of the visuals as below -

Radar chart

Column chart

Pie chart
Hope this will give you some insights of amCharts and Chatrjs and you will be able to compare at a glance. For other javascript charting comparisons click here.