Archive for the ‘JavaScript’ Category

Calculate size of indexedDB database

IndexedDB has no built-in mechanism for calculating the size of a database. Below is a code snippet that shows how to calculate the ‘approximate’ size if you are storing strings. In my case we are storing Base64 images.

Depending on what data type you are storing here are some suggestions on how to calculate the size:

  • String. The example shown below simply uses the String.length property. You can typically get a one-to-one ratio where each character is equal to one byte. For example, if length equals 20, you can roughly assume that the size of the string is 20 bytes. However, if you have many uncommon characters in your strings those can equal 2 bytes each. For more information see this page on the Mozilla Developer Network.
  • Array. The size of an array depends on the array type and what you are storing in it. If it’s just a plain old Array of strings, such as ["a","test","something"],  you can parse the array for strings and then measure the size of each item within it as I just mentioned. If it’s a typed array you’ll have to take into account if it’s 8-bit, 16-bit, 32-bit or 64-bit. If you have numbers in your array, I believe all JavaScript numbers are 8 bytes each.
  • Blob. Access the Blob.size property.
/**
 * Provides the size of database in bytes
 * @param callback callback(size, null) or callback(null, error)
 */
var size = function(callback){
    if(this._db != null){
        var size = 0;

        var transaction = this._db.transaction(["your_db"])
            .objectStore("your_db")
            .openCursor();

        transaction.onsuccess = function(event){
            var cursor = event.target.result;
            if(cursor){
                var storedObject = cursor.value;
                var json = JSON.stringify(storedObject);
                size += json.length;
                cursor.continue();
            }
            else{
                callback(size,null);
            }
        }.bind(this);
        transaction.onerror = function(err){
            callback(null,err);
        }
    }
    else{
        callback(null,null);
    }
}

Usage

Here’s how you would use this in your application:

getSize(function(size,err){
     if(size > 0){
         console.log("Database size = " + size + " bytes");
     }
     if(err != null){
         console.log("There was a problem getting database size: " + err);
     }
}

Reference

W3C Specification for IndexedDB Database API
MDN – Blog

Tags: ,
Posted in JavaScript | No Comments »

What all mobile web devs should know about PhoneGap

If you already building or looking into getting started with mobile web applications you should understand the basics of PhoneGap. The name ‘PhoneGap’ is widely recognized, and perhaps more widely misunderstood.

The nudge to write this article was born out of conversations where we stumbled across concrete limitations to modern responsive JavaScript libraries such as bootstrap and jQuery. Limitations that cannot be overcome by adding more brilliant functionality because some JavaScript capabilities simply do not exist within the browser today. Furthermore, other requirements were imposed by political realities, timeframes and expectations.

That’s where PhoneGap steps in. 

So what, tell me what PhoneGap does?

PhoneGap is owned by Adobe and it has an open source top-level Apache Foundation sister project called Cordova. I won’t bore you with its long and twisted history, you can read about it here if you want.

The bottom line is PhoneGap allows you to develop JavaScript mobile applications that have access to certain aspects of the native device such as writing data to a filesystem. Your web application is wrapped within a native mobile application container that gives you JavaScript access to native operating system capabilities beyond what the browser itself is capable of doing!

By native I mean iOS Objective C, Android Java, WindowsPhone, Windows 8, Blackberry 10, Amazon Fire OS and Tizen. Your JavaScript applications runs in a chrome-less browser that gives you special hooks to the operating system. You can also submit PhoneGap applications to the AppStore, Google Play and others.

Who uses this stuff, well you may be using a PhoneGap app from one of these online stores and not even know it. To mention a few: Southwest Airlines and many others.

What limitations can PhoneGap address that responsive libraries don’t?

If your requirements call for all or most of the following items, then PhoneGap is the correct choice for your project today. That may change as HTML5 continues to rapidly grow, but for now I’m sticking with the following bullet points. Stick with me and read through all of these before starting to throw out counter arguments.

JavaScript skillz. If you are an existing JavaScript shop, then PhoneGap leverages your existing JavaScript skills to access capabilities beyond current browser functionality without the need to have an in-depth understanding of Objective C or Java.

Sure, it’s easy to say you can hire expert contractors to develop iOS and Android applications, along with UX designers and testers. But, if your budget doesn’t include the capital costs for these folks and all you have is JavaScript ninjas on staff then the choice is easy.

Or, maybe you have genius-level developers that could easily and quickly spin up on all your need to know on ObjectiveC and Java Android. If this isn’t the case, and your timeframes and budgets don’t allow for this then you’ll need a fallback plan such as PhoneGap.

Access to camera.  Yes, you can currently access the camera on some web browsers today. However, the support on mobile browsers is still inconsistent, limited or non-existent. On the other hand, native device OS’s are expected to have access to cameras If they didn’t it would be considered a serious oversight. PhoneGap provides cross-platform mobile device access to the camera.

Read/write access to SD Card. Just to reiterate, this is both read and write access to a local storage device. Certainly there is a FileReader API in plain old JavaScript, but as far as I know there isn’t a FileWriter or its equivalent yet. If you need the write access to go along with read capabilities then you should be looking at PhoneGap.

[Correction Jan. 27, 2014] I mis-wrote. The FileWriter API exists however it has limited supported across browsers: http://caniuse.com/#search=filewriter. And, examples of it’s use can be found here.

AppStore or Google Play. If you have a requirement to submit your application to the app store then PhoneGap will help you get there. There is no way today for submitting a stand-alone web application for acceptance on AppStore or Google Play. Period. Some will argue that the need for using these online application stores is going away, but that’s a non-issue if you have been directed to meet this requirement a.s.a.p. and your job depends on it. If that’s the case, then PhoneGap will be your friend.

Is there anything else I should know?

Yes…First, PhoneGap is not perfect, but then again few software projects are perfect. You will need to install and know a few things about the native IDEs you want to support. If you want to deploy Android you’ll need to install Eclipse or IntelliJ. For iOS you’ll need to install XCode. Etc. You still have to compile a native project or you can try your hand at Adobe’s PhoneGap Build, which is a cloud based build system for PhoneGap.

It is confusing that there are two projects that share a common/similar code base: PhoneGap and Cordova. Also, Cordova’s documentation has typically been more up to date that Adobe’s. If you do your research you’ll find various performance complaints and bug issues (like I just said are there any software projects that don’t have these??).  Yet, overall it’s a great starting point if you have the needs listed above, and it’s much better than trying to start from scratch given today’s dramatically shortened delivery expectations.

You can absolutely still use bootstrap, jQuery and other JavaScript libraries within PhoneGap. There are caveats, of course, related to application life-cycle issue, navigation as well as App Store and Google Play user interface acceptance guidelines.

If you want to add functionality to PhoneGap because you find some critical thing is missing that you need for your project, the good news is you can develop a custom plug-in.

Last, I should mention Titanium Studio. It also lets you leverage JavaScript skills, with the primary difference being that it converts JavaScript into native byte code rather than just displaying it in a chrome-less view.  Plus it’s comes with its own IDE and MVC Framework.  I’ve never used Titanium so I can’t judge it, however I know people who do use it successfully and love it. It’s one more thing to consider that you should be aware of.

References

Cordova Documentation

PhoneGap Documentation

PhoneGap Platform Support

Tags: , , , , , , ,
Posted in JavaScript, Mobile, PhoneGap | No Comments »

The question that I get asked the most these days is “what development languages should I be learning [to stay competitive/excited/motivated/etc] ?” The high-tech industry, and software in particular, is changing at a ridiculously fast pace and that introduces a lot of uncertainty and confusion as well as great opportunity. My answer to this question is unequivocal: I think for the foreseeable future developers should be learning the basic concepts of JavaScript and Python. If you don’t already have these skills then you simply cannot go wrong with this approach. If you’ve been a long-time server-side developer, or you are just getting started with software development then knowing the patterns and practices for JavaScript and Python will serve you well.

Why?

There are three primary reasons and I’ll try to be short and to the point. First, there are at least 2.5 billion internet users world wide, and that number is growing. Their primary method of accessing the web is a browser and JavaScript is the lingua franca of the browser world. JavaScript is a scripting language and it is “the” fundamental building block that allows web pages to “do” things such as submitting your search request to a server, or helping to find your location from your phone. Almost all web pages being served up around the world have JavaScript in them.

Second, the majority of retail, commercial and governmental web applications have a requirement that calls for the use of “server-side” code. This is code, such as Python, that runs on a server and not in the browser application. The most common functionality of server-side code is passing data back and forth between a database and a web application. For example, if a web app asks for a username and password, that user name and password are almost always stored on a server somewhere and not, for security reasons, in the web page and on the client browser where it could be very easily stolen.

Third, you can absolutely apply these client-server patterns and practices to other languages used within the realm of web development. A User Interface designer who has been solely focused on layout and styling via Cascading Style Sheets (CSS) can now understand and appreciate how the underlying JavaScript code can affect the look, feel and behavior of a web page. Python skills can also be used a springboard for more quickly learning other powerful web development platforms such as ruby-on-rails.

The bottom line is if you understand both client development (JavaScript) and server development (Python), then you start to gain considerable value as someone who understands how to help the entire system work together in harmony.

A short note on jQuery.

Many (most?) new web developers learn jQuery first. However, even if you know jQuery you don’t necessarily understand JavaScript. The awesome jQuery libraries provide an interface that hides and simplifies a lot of native JavaScript hoopla, and in general can really make life significantly easier and save time when building modern cross-browser web apps. jQuery is built using JavaScript (and CSS3), but it is not JavaScript. Because of that, when something goes wrong or not as you expected (not if, but when!), and you have a general understanding of how JavaScript works, then you stand a much better chance of figuring out a timely work-around with significantly less stress, frustration and time wasted towards your projects deadline.

The absolute minimum recommended reading list:

JavaScript.

  • Douglas Crockford’s book “JavaScript: the good parts”.
  • Douglas Crockford’s website – He is considered a key brainchild behind the ongoing development and understanding of JavaScript.
  • W3schools – An excellent website for anyone using or learning JavaScript. It has tutorials and online Try It Yourself sample apps.

Python.

Tags: , , , , , , ,
Posted in JavaScript | No Comments »

Easy enums for custom JavaScript libraries

There’s a ton of information on the internet related to the best way to create JavaScript enums. This post is different in that it focuses on using enums that are immutable and cannot be changed within your own custom libraries.

The challenge with enum usage in JavaScript is global variable leakage can accidentally cause unexpected changes within your application, especially in cases of large, complex applications that may involve your own JavaScript libraries along-side 3rd party libraries. Global variable leakage means two variables can potentially have the same name, and this may not cause an error. Good debuggers help to avoid this problem by using jslint. But, if someone else is using your libraries then you can’t depend on them using best practices. So, variable leakage can cause unexplainable/unpredictable problems and create hard to track bugs. What we need is a coding pattern to protect enums so that we can guarantee that we always get the value expected.

As of today, JavaScript doesn’t have a universally accepted, built-in cross-browser solution for guaranteeing that specific variables can be made immutable. In other words, if we create a statement var BLUE = “blue” there is no way to enforce that something elsewhere in an application, or code that someone else wrote that is running the same application cannot ever change the value of BLUE.

In comparison, strongly typed languages such as C# and Java let you declare constants. If you accidentally try to change them in your code you get a compiler error that prevents the application from running. The compile-time checking can help prevent bugs in your code later on. Here are several examples from Java and C#:

 final int RADIUS = 1000; //Java
 const int RADIUS = 1000; //C#

So here we go. I’ll use six use cases to illustrate a variety of ways to make certain your enums are immutable. This list is not designed to be all inclusive, its intent is to demonstrate patterns that you can use to learn more about JavaScript enums. You can try these out using the following jsfiddle.

USE CASE 1 – Basic public enum function with no namespace protection. This use cases offers the least amount of protection against global variable leakage. I’d only expect to see this type of enum in very small, stand-alone applications.

function basicEnum() {
    var values = {
         BLACK: '#000000',
         RED: '#FF0000',
         GREEN: '#00FF00'
    }

    return values;
}

console.log("test0 " + basicEnum().BLACK); //test0 #000000

USE CASE 2 – Basic public enum that uses an internal, privately scoped namespace in which to define the enum object. This use case offers slightly more protection than Use Case 1, but the public function itself is still not protected within the global namespace. It’s possible there could be two functions with the same name “colorEnum”. And, the larger the application gets the higher probability there is of having accidental name duplication.

function colorEnum() {
    var values = values || {}
    values.colorEnum = {
         BLACK: '#000000',
         RED: '#FF0000',
         GREEN: '#00FF00'
      };

      return values;
};

console.log("test1 " + colorEnum().colorEnum.GREEN); //test1 #00FF00

USE CASE 3 – Public enum with no namespace protection using an anonymous function expression to define the enum. This is a variation of Use Case 2 showing you can define multiple categories of enums. And, like Use Case 2 it still offers zero public/global namespace protection. I’m using the terms public and global to mean the same thing.

DoSomething = (function(){

    var constValues = constValues || {}
    constValues.color = {"BLACK" : "#000000" }
    constValues.error = {"ERROR_TIMEOUT" : "Connection Timeout" }
    return constValues;
});

console.log("test2 " + DoSomething().color.BLACK); //test2 #000000
console.log("test3 " + DoSomething().error.ERROR_TIMEOUT); //test3 Connection Timeout

USE CASE 4 – Public enum with namespace protection using an anonymous function expression and internal (private) namespaces to differentiate multiple categories of custom enum objects. This use case starts to offer better protection against global variable leakage by wrapping the public function in a namespace.

var my_test = my_test || {}
my_test.DoSomething = (function(){

    var constValues = constValues || {}
    constValues.color = {
        "BLACK" : "#000000",
        "RED" : "#FF0000"
    }
    constValues.error = {
        "ERROR_TIMEOUT" : "Connection Timeout",
        "ERROR_FAULT" : "Connection problem"
    }
    return constValues;
});

console.log("test4 " + my_test.DoSomething().color.BLACK); //test4 #000000
console.log("test5 " + my_test.DoSomething().error.ERROR_TIMEOUT); //test5 Connection Timeout

USE CASE 5 – Namespace protected public anonymous function expression along with an internally (private) scoped function that defines the enum. This is a variation of Use Case 5 showing how to use switch/case statements along with a privately scoped function that are all wrapped inside the anonymous function.

var my_second_test = my_second_test || {};
my_second_test.DoSomething = (function(val){

    var color;

    switch(val)
    {
        case 1:
            color = basicEnum().BLACK;
            break;
        case 2:
            color = basicEnum().RED;
            break;
        case 3:
            color = basicEnum().GREEN;
            break;
    }

    function basicEnum() {
        var values = {
             BLACK: '#000000',
             RED: '#FF0000',
             GREEN: '#00FF00'
        }

        return values;
    }

    return color;
});

console.log("test6 " + my_second_test.DoSomething(2)); //test6 #FF0000

USE CASE 6 – This Use Case shows placing a privately scoped anonymous function expression defining the enum inside a public anonymous function expression, and finally accessed through another prototyped anonymous function expression. Yikes, that was a lot of technical mumbo-jumbo verbiage, right?! It also offers several tests to validate if the enum is immutable or not.

var my_third_test = my_third_test || {};
my_third_test.DoSomething = (function(){

    this.basicEnum = (function() {
        var values = {
             BLACK: '#000000',
             RED: '#FF0000',
             GREEN: '#00FF00'
        }

        return values;
    });

});

my_third_test.DoSomething.prototype.findColor = (function(val){
    var color;

    switch(val)
    {
        case 1:
            color = this.basicEnum().BLACK;
            break;
        case 2:
            color = this.basicEnum().RED;
            break;
        case 3:
            color = this.basicEnum().GREEN;
            break;
    }

    return color;
});

var myColor = new my_third_test.DoSomething();

console.log("test7 " + myColor.findColor(3)); //test7 #00FF00

//The enum properties cannot be changed
myColor.basicEnum().BLACK = "test";

console.log("test8 " + myColor.basicEnum().BLACK); //test8 #000000

try{
    //test that basicEnum() is immutable
    myColor.basicEnum() = "test"; //Throws ERROR!
}
catch(err){
    console.log("test9 " + err);
    //test9 ReferenceError: Invalid left-hand side in assignment
}

Conclusion. So that’s all there is to it. Hopefully these examples help to not only demonstrate some patterns to protect your data, but also give you ideas for saving time while building larger applications.

Reference.

JSFiddle project

Tags: , ,
Posted in JavaScript | No Comments »

jQuery Mobile – Setting full content width

Here are some hints to help get all of your jQuery content stretched to the full width of your mobile browser screen regardless of screen size or orientation. These techniques have been tested on jQuery 1.7.x, jQuery 2.0 and jQuery mobile 1.3.1.

Lets start with a look at the minimum required CSS:

html,body,div[data-role ="page"], div[data-role="content"] {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
}

Problem – Using the minimum CSS above, leaves a spacer on the top and left hand sides of the app, and the right hand border and/or bottom border disappears. I noticed the right hand margin extends approximately 9 to 15 pixels (or greater depending on device) beyond the visible view. I verified this behavior on Android 4.1 native browser and Chrome 26, as well as on iPad 3 using Safari and Chrome 25.

Solution – set certain CSS width properties as shown below. This solution has been tested on Android 4.1 native and Chome 26, Android 2.3.2 native, and on iPad Safari and Chrome 25. Just a bit of a warning that if displayed on a desktop browser you will see vertical scrollbars. But, you should be detecting the different between mobile and desktop anyway, right!

Note: this solution doesn’t address the problem with content height, it only looks at width. So, yes, you will notice that the height of my sample is off the page.


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <title>jQuery Test</title>

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />

    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.js"></script>
<style>
        html,body, div[data-role ="page"] {
            height: 100%;
            width: 100%;
            margin: 0px;
            padding: 0px;
        }

         .ui-content{
            height: 100%;
            width: 100%;
            margin: 0px;
            padding: 0px;
            border-style: solid;
            border-color: chartreuse;
            border-width: 5px;
        }

        #map {
            height: 100%;
            width: 100%;
            padding: 0px;
            border-style: solid;
            border-color: crimson;
            border-width: 10px;
        }
</style>
</head>

<body>

<div data-role="page" id="page1" >

    <div data-role="content">
        <div id="map"</div>
    </div>

</div>
</body>

References

Determining the dimensions of an [HTML] element

Check HTML5 Browser Height and Width using Canvas

[Modified April 26, 2013 - fixed code bug]

Tags: , , ,
Posted in JavaScript, jQuery | 1 Comment »

Fastest way to figure out x and y image offsets

Here is an app that will help you quickly visualize x and y image offsets. I think everyone has tried to eyeball offsets by tweaking the x and y a bit, hitting build again (and again) and then viewing your changes. Simply upload your image in the embedded app below and then adjust the sliders until the image is in the right place.

You can download a zip file (5kb) of the code here.

If you don’t see the slider bars in the app below you need to upgrade to a browser that supports HTML5 <input type=’range’> tag, or feel free to download and modify the code.

Tags:
Posted in JavaScript | No Comments »