Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, October 15, 2011

Generating QR code by Google Chart API


Google provide lots of API for developers to develop their own tools. Today I would like to go through a funny feature from Google Chart Tools - QR code generating.


Developer always have to come across with tons of data and make it to a presentable report for end-users. Google Chart Tools can save your a day. However, we just focus on QR code generating function today. If you interest in it, check it out at http://code.google.com/apis/chart/.


Generating QR code by Google API is just a piece of cake. You just have to append your target message to a URL. Here is an example.


I want to make a QR code with a message 'We love programming.', here we go
https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=We%20love%20programming


Actually it will be a image if you click on it. The parameter chs is widthxheight. Parameter chl is the message or URL you want to include. Please do URL encode for your message.


I have written a snippet of code to generate QR code by current URL automatically.

<div id="qrcode"></div>
<script>
var img = document.createElement('img');
img.src = 'https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=' + encodeURIComponent(document.location.href);
document.getElementById('qrcode').appendChild(img);
</script>



Here is just the core function. You can also design your own interface to make a nice QR code generator. For more details, check out the document of Google, http://code.google.com/apis/chart/infographics/docs/overview.html

You can build QR code easily with Google Chart API now, but how QR code can help on your business? Try to read this:

Tuesday, September 6, 2011

[Javascript] date function return NaN in IE but work fine in Firefox

Sometimes, javascript run in IE and firefox have different interpretation on a string of date. If there is a date string, for example

2011-01-01T12:56:12

Well, I think it is a well-formatted date string and no-doubt that Javascript can change it to a date object without any mistake. However, I find that I got different return at IE and firefox. At IE, I got NaN, but I can get date object at firefox.

For a developer who have to meet tight deadline, we don't want to know what the back-end logic inside different browsers. Here is the function for you to cater this problem.


function parseISO8601(dateStringInRange) {

    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);
   
    if(parts) {
        month = +parts[2];
        date.setFullYear(parts[1], month - 1, parts[3], parts[4], parts[5], parts[6]);
        if(month != date.getMonth() + 1) {
            date.setTime(NaN);
        }
    }
    return date;

}

The input is YYYY-MM-DDTHH:ii:ss, output is date object and NaN if there is not a date input.

Thursday, August 25, 2011

[Javascript] Dynamic class not working in IE7

We all known how to change class for a DIV by Javascript. For example:

document.getElementById("div_name").setAttribute("class", "class_name");

Generally, it works across different browser nowadays. Unfortunately, some users still using IE7 or even older-version, and we have to take care of them. Here is a JS function for workaround.


function rollStyle (styleObj, styleName) {
    if (styleObj.className) {
        styleObj.className = styleName;
    } else {
        document.getElementById(styleObj).className = styleName;
    }
}

 Usage:

rollStyle("div_name","class_name")

Tuesday, August 23, 2011

[Javascript] Implementing Instagram API with Javascript

Instagram becomes a popular photo taking app on iPhone rapidly. You can also integrate Instagram photo on your web by API. This is a basic tutorial on how to code it.

Let's take a look at the demo first.

In this example, jQuery has been used for decreasing development time. It can also be done without jQuery. Here is the full source.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Instagram</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js"></script>
<style>
html, body { height: 100%; margin: 0; padding: 0; background-color: #ffffff;}

#panel { height: auto; float: right; width: 100%; }
#panel .photoWrapper { width: 150px; height: 150px; margin:2px; float:left; box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4); display:none;}
#panel. photoWrapper .photo { width: auto; height: auto; }

</style>
<script type="text/javascript">
<!--
$(document).ready(function(){
    var access_token = '3794301.f59def8.e08bcd8b10614074882b2d1b787e2b6f';

    loadFeed();

    function loadFeed() {
        var param = {access_token:access_token};
        cmd(param, onPhotoLoaded);
    }

    function cmd(param, callback) {
        //popular
        var cmdURL = 'https://api.instagram.com/v1/media/popular?callback=?';
        $.getJSON(cmdURL, param, callback);
    }

    function onPhotoLoaded(data) {
        if(data.meta.code == 200) {
            var photos = data.data;
           
            if(photos.length > 0) {
                for (var key in photos ){
                    var photo = photos[key];
                    $('<div id=p' + photo.id + '></div>').addClass('photoWrapper').appendTo('#panel');
                   
                    var str = '<img id="' + photo.id + '" src="' + photo.images.thumbnail.url + '" width="100%">';
                    $('<div></div>').addClass('photo').html(str).appendTo('#p' + photo.id);
       
                    $('#' + photo.id).load(function() {
                        $('#p' + $(this).attr('id')).fadeTo('slow', 1.0);
                    });

                }
            }else{
                alert('empty');
            }
           
        }else{
            alert(data.meta.error_message);
        }
    }

});
//-->
</script>
</head>
<body>
<div id="panel"></div>
</body>
</html>

 This is an example grabbing popular feed from Instagram. You may have a question on the access_code. This is a code generated from OAuth authentication. Each application that work with Instagram API should be registered at official website. A client_id and client_secure will be assigned for your application. But at development stage, you can use the access_code in my example. However, only popular feed can be retrieved from this code, such as /media/* .

I have developed a JS function called cmd() to centralize all API call in this example. JSON has been adopted because it can handle cross-domain issue.

Actually, the logic in the example is not so complicated. Hope this example can give you a brief idea on the API integration.

Book you may feel interested:

Tuesday, August 16, 2011

[Javascript] loading URL into a DIV

Sometimes, we want to load in other website into my own site as part of element. Javascript can help perfectly. First of all, we have to place a container for the website you want to display. In this example, I also build a combo box to change different URL for loading. So, the HTML coding should look like,

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Loading URL into a DIV</title>
   
    <style type="text/css">
   
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
   
    #web-panel {
        height: 100%;
        float: right;
        width: 100%;
        overflow: hidden;
    }
   
    #control {
        background: #fff;
        padding: 5px;
        font-size: 14px;
        font-family: Arial;
        border: 1px solid #ccc;
        box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
    }

    </style>

  </head>
  <body>
    <div id="control">
      <strong>URL:</strong>
      <select id="url">
          <option value="">Please select</option>
        <option value="http://www.apple.com">Apple</option>
        <option value="http://www.yahoo.com">Yahoo</option>
        <option value="http://www.google.com">Google</option>
      </select>

    </div>
    <div id="web-panel"></div>
  </body>
</html>

OK, now build the Javascript function to load in the URL. Just simple Javascript is good enough and we don't need jQuery help.
<script type="text/javascript">
    function loadURL(u) {
        document.getElementById("web-panel").innerHTML = '<iframe src="' + u + '" width="100%" height="100%" border="0"></iframe>';
    }
</script>

This function should be triggered by combo bo onChange function. So, here is the complete code.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Loading URL into a DIV</title>
   
    <style type="text/css">
   
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
   
    #web-panel {
        height: 100%;
        float: right;
        width: 100%;
        overflow: hidden;
    }
   
    #control {
        background: #fff;
        padding: 5px;
        font-size: 14px;
        font-family: Arial;
        border: 1px solid #ccc;
        box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
    }

    </style>

  <script type="text/javascript">
    function loadURL(u) {
        document.getElementById("web-panel").innerHTML = '<iframe src="' + u + '" width="100%" height="100%" border="0"></iframe>';
    }
  </script>
  </head>
  <body>
    <div id="control">
      <strong>URL:</strong>
      <select id="url" onchange="loadURL(this.value);">
          <option value="">Please select</option>
        <option value="http://www.apple.com">Apple</option>
        <option value="http://www.yahoo.com">Yahoo</option>
        <option value="http://www.google.com">Google</option>
      </select>

    </div>
    <div id="web-panel"></div>
  </body>
</html>

Monday, August 15, 2011

[jQuery] Using jQuery to extract data from XML

jQuery is a wonderful tool for developers for developing dynamic content in the web. Before you can enjoy all wonderful features by it, you must initiate jQuery at the beginning of your web page first. You can download the whole copy to your hosting, or just using Google libraries API.




<script language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Assumed that you want to extract the data from a XML file, called "data.xml".

data.xml
<?xml version="1.0" encoding="utf-8"?>
<books>
    <book id="001">
        <title>Book1</title>
        <content>ABC</content>
    </book>
    <book id="002">
        <title>Book2</title>
        <content>DEF</content>
    </book>
</books>

Here is js code for you to extract the data, and display it at result DIV.
<script language="Javascript">
<!--
jQuery(document).ready(function() {

    var dataUrl = "data.xml";

    jQuery.ajax({
        // get the collections XML
        type: "GET",
        url: dataUrl,
        dataType: "xml",
        error: function (request, error) {
            // do this on AJAX error
        },
        success: function(data) {

            jQuery(data).find('book').each(function() {
                var id = jQuery(this).attr('id');
                var title = jQuery(this).find('title').text();
                var content = jQuery(this).find('content').text();

                var htmlString = 'ID:' + id + '<br>' + 'Title:' + title + '<br>' + 'Content:' + content;
                jQuery('<div></div>').html(htmlString).appendTo('#result');

            });

        }
    });

});
//-->
</script>
<div id="result"></div>

Sunday, August 14, 2011

[Javascript] Adding custom markers and icons at Google Map

You may want to make a map at your website to indicate the location of your shop. Google map API absolutely can do your favor.



Demonstration:

First of all, you have to initiate Google map API at the beginning of the page .
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

The parameter "sensor" means that whether detecting your current location or not. Then place a DIV container for the map, and name it as "scene".

<div id="scene"></div>

Using CSS to control the width and height of that DIV.

<style>
#scene{width:480x;height:320px;margin:0 0 10px 0;display:block;}
</style>

In order to load Google Map, we should define a center point of the map first.
        var MongKok = {
            name : "Mong Kok",
            latlng : new google.maps.LatLng(22.319183,114.169353),
            zoom : 17,
        }

I define a point that is Mong Kok at Hong Kong, and name it as a variable "MongKok". You can extract latitude and longitude point from the linkage of the point in the map.



OK, we can load the map into the DIV now.

        function showMap(district) {
            var settings = {
                streetViewControl: false,
                zoomControl: false,
                mapTypeControl: false,
                panControl: false,
                zoom: district.zoom,
                center: district.latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("scene"),settings);
           
            setMarkers(map, markers);
        }
        window.onload = function() {
            showMap(MongKok);
        }

The second step, set your shop location and put a maker on it now. Here is the location and the function to set marker.

        var markers = [
            ['Langham Place', 22.318905, 114.168538, 4],
        ];
        function setMarkers(map, locations) {
       
            var image = new google.maps.MarkerImage('http://server2.iconfinder.com/data/icons/socialnetworking/32/google.png',
                new google.maps.Size(30, 30),
                new google.maps.Point(0,0),
                new google.maps.Point(15, 15));
           
            var shape = {
                coord: [1,1,30,30],
                type: 'rect'
            };
           
            for (var i = 0; i < locations.length; i++) {
                var marker = locations[i];
                var latLng = new google.maps.LatLng(marker[1], marker[2]);
                var marker = new google.maps.Marker({
                    clickable: true,
                    position: latLng,
                    map: map,
                    icon: image,
                    flat: true,
                    shape: shape,
                    title: marker[0],
                    zIndex: marker[3]
                });
               
                google.maps.event.addListener(marker, 'click', function(e) {
                    //
                });
            }
           
        }

So, put it all together and here you go.
<style>
#scene{width:480x;height:320px;margin:0 0 10px 0;display:block;}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
<!--
// district
var MongKok = {
    name : "Mong Kok",
    latlng : new google.maps.LatLng(22.319183,114.169353),
    zoom : 17,
}

// marker
var markers = [
    ['Langham Place', 22.318905, 114.168538, 4],
];

function setMarkers(map, locations) {

    var image = new google.maps.MarkerImage('http://server2.iconfinder.com/data/icons/socialnetworking/32/google.png',
        new google.maps.Size(30, 30),
        new google.maps.Point(0,0),
        new google.maps.Point(15, 15));
   
    var shape = {
        coord: [1,1,30,30],
        type: 'rect'
    };
   
    for (var i = 0; i < locations.length; i++) {
        var marker = locations[i];
        var latLng = new google.maps.LatLng(marker[1], marker[2]);
        var marker = new google.maps.Marker({
            clickable: true,
            position: latLng,
            map: map,
            icon: image,
            flat: true,
            shape: shape,
            title: marker[0],
            zIndex: marker[3]
        });
       
        google.maps.event.addListener(marker, 'click', function(e) {
            //
        });
    }
   
}

function showMap(district) {
    var settings = {
        streetViewControl: false,
        zoomControl: false,
        mapTypeControl: false,
        panControl: false,
        zoom: district.zoom,
        center: district.latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("scene"),settings);
   
    setMarkers(map, markers);
}
window.onload = function() {
    showMap(MongKok);
}
//-->
</script>

<div id="scene"></div>

Here's for you to learn more google map usages:

Thursday, August 11, 2011

Make cache-friendly image path

A content delivery network or content distribution network (CDN) is a system of computers containing copies of data placed at various nodes of a network. When properly designed and implemented, a CDN can improve access to the data it caches by increasing access bandwidth and redundancy and reducing access latency. The price of this service is quite high, so it is not common for normal user.

However, if you can add more alias for your domain, your web page download speed can also be improved. For example,

http://static0.yourdomain.com/images/yourimage1.jpg
http://static1.yourdomain.com/images/yourimage2.jpg
http://static2.yourdomain.com/images/yourimage3.jpg
http://static3.yourdomain.com/images/yourimage4.jpg

Here is the function for making cache-friendly image path,

PHP:
function path_to_origin_suffix($path,$NUM_ALIASES=6){
    if (1 == $NUM_ALIASES)
        return 0 ;
    $hex = md5($path);
    return ord($hex[31]) % $NUM_ALIASES;
}


function make_url($path,$origin="static.yourdomain.com"){

    $pos = strpos($path,'/');
   
    if ($pos === FALSE || $pos != 0) {
        $path = sprintf('/%s',$path);
    }
    $suffix = path_to_origin_suffix($path);
   
    $array= explode('.',$origin,2);
    $domain1 = $array[0];
   
    $host = "$domain1$suffix.$array[1]";

    $abs_href = "http://$host$path";
    echo $abs_href;
}

Usage:
<img src="<?=make_url('/images/yourimage.jpg')?>">

This function is using MD5 to transform image path to hex value, and using ord to change to decimal number. Then, determine which alias domain should be used by MOD value

Javascript:
function make_url(path, origin) {
  
    if (typeof origin == "undefined") {
        origin = "static.yourdomain.com";
    }
  
    var pos = path.indexOf("/");
    if (pos == -1 || pos != 0) {
        path = "/"+path;
    }
    var suffix = (path.length+1) % 6
    var array= origin.split(".");
    var subDomain = array.shift();
    var domain = array.join(".");
  
    var host = "";
    host = subDomain+suffix+"."+domain;

  
    abs_href = "http://"+host+path;
    return abs_href;
}
Usage:
make_url('/images/yourimage.jpg')

Since there is not MD5 build-in function for Javascript, I just simply using the length of URL to determine which alias domain should be used.

Flash Actionscript 2:
function make_url(path, origin) {
    var origin = origin==undefined ? origin="static.yourdomain.com" : origin;
   
    var pos = path.indexOf("/");
    if (pos == -1 || pos != 0) {
        path = "/"+path;
    }
    var suffix = (path.length+1) % 6
    var array= origin.split(".");
    var subDomain = array.shift();
    var domain = array.join(".");
   
    var host = "";
   
    host = subDomain+suffix+"."+domain;
   
    abs_href = "http://"+host+path;
    return abs_href;
}

At last, please be careful that cross-domain issue after using this function to modify your JS path or SWF path.
Related Posts Plugin for WordPress, Blogger...