Friday 16 November 2012

Getting the Longitude and Latitude from a particular address or postcode with Google Maps Api v3.

Google API v3 supports unlimited calls, and doesn’t need the complexity of creating keys like the version 2, Bing maps or Yahoo maps.

I have created a small, but useful function to get the Latitude and Longitude of a particular address or postcode. It looks pretty simple, but this is a nice start if you want to build something big with the Google API.

In this example I target the Buckingham Palace, in London (UK).

<html>
<head>
    <script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>
    <script type="text/javascript">
        //########################################
        function GetLongitudeAndLatitude(_sAddress) {
            var mygc = new google.maps.Geocoder();
            mygc.geocode({ 'address': _sAddress }, function (results, status) {
                alert("latitude : " + results[0].geometry.location.lat());
                alert("longitude : " + results[0].geometry.location.lng());
            });
        }
        //########################################
    </script>
</head>
<body onload="GetLongitudeAndLatitude('SW1A 1AA');">
</body>
</html>

Thursday 15 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Box element

The box element is one of the most awaited elements in HTML5. It is going to facilitate the task of creating boxes in our web site. At this point we are going to start forgetting border-… with divs or tables and concentrate in a really good implementation called box.

I am going to list all the elements compatible with almost all browsers and add some examples:

  1. display:box : To define an element as a flexbox we set the display to box.
    .flexbox {
    display: -moz-box;
    display: -webkit-box;
    display: box;
    }

  2. box-orient: Lay out the children of a div element horizontally.
    .rule {
    -moz-box-orient: vertical;
    -webkit-box-orient: vertical;
    box-orient: vertical;
    }

  3. box-ordinal-group: Specify the display order of the child element of a box, We can reorder elements as we like, using box-ordinal-group.
    .box
    {
    display:-moz-box; /* Firefox */
    display:-webkit-box; /* Safari and Chrome */
    display:box;
    border:1px solid black;
    }
    .ord1
    {
    margin:5px;
    -moz-box-ordinal-group:1; /* Firefox */
    -webkit-box-ordinal-group:1; /* Safari and Chrome */
    box-ordinal-group:1;
    }
    .ord2
    {
    margin:5px;
    -moz-box-ordinal-group:2; /* Firefox */
    -webkit-box-ordinal-group:2; /* Safari and Chrome */
    box-ordinal-group:2;
    } 

  4. box-flex: Define two flexible p elements. If the parent box has a total width of 300px, #p1 will have a width of 100px, and #p2 will have a width of 200px. Box-flex allow the content to expand to fill the available space.
    div
    {
    display:-moz-box; /* Firefox */
    display:-webkit-box; /* Safari and Chrome */
    display:box;
    width:300px;
    border:1px solid black;
    }
    #p1
    {
    -moz-box-flex:3.0; /* Firefox */
    -webkit-box-flex:3.0; /* Safari and Chrome */
    box-flex:3.0;
    border:1px solid red;
    }
    #p2
    {
    -moz-box-flex:1.0; /* Firefox */
    -webkit-box-flex:1.0; /* Safari and Chrome */
    box-flex:1.0;
    border:1px solid blue;
    }

  5. box-align: Center the child elements of a div box by using the box-align and box-pack properties together.
    div
    {
    width:350px;
    height:100px;
    border:1px solid black;
    /* Firefox */
    display:-moz-box;
    -moz-box-orient:horizontal;
    -moz-box-pack:center;
    -moz-box-align:center;
    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-orient:horizontal;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    /* W3C */
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
    } 

  6. box-direction: This reverses the order of elements. We can use normal, reverse and inherit.
    #main {
    -moz-box-direction: reverse;
    -webkit-box-direction: reverse;
    box-direction: reverse;
    }

  7. box-pack: Box-pack controls alignment in the direction set by orient. it centers the child elements of a div box by using the box-align and box-pack properties together.
    div
    {
    width:350px;
    height:100px;
    border:1px solid black;
    /* Firefox */
    display:-moz-box;
    -moz-box-orient:horizontal;
    -moz-box-pack:center;
    -moz-box-align:center;
    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-orient:horizontal;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    /* W3C */
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
    } 

HMTL 5, CSS3 and JavaScript for Windows 8 – text-transform

This property will be used with CSS3. The text-transform property controls the capitalization of text.

Value Description
none No capitalization. The text renders as it is. This is default
capitalize Transforms the first character of each word to uppercase
uppercase Transforms all characters to uppercase
lowercase Transforms all characters to lowercase
inherit Specifies that the value of the text-transform property should be inherited from the parent element

Example:

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:  <style>
   5:  p.uppercase {text-transform:uppercase;}
   6:  p.lowercase {text-transform:lowercase;}
   7:  p.capitalize {text-transform:capitalize;}
   8:  </style>
   9:  </head>
  10:   
  11:  <body>
  12:  <p class="uppercase">This is some text.</p>
  13:  <p class="lowercase">This is some text.</p>
  14:  <p class="capitalize">This is some text.</p>
  15:  </body>
  16:  </html>
  17:   

HMTL 5, CSS3 and JavaScript for Windows 8 – Media Types

One of the key features we are going to be using in Windows 8 it is Media Types.

Media Types allows you to set different types of screens of devices. It is really useful to create full accessibility to your site, so for example, if the person which is going to read the site can’t see properly, we can use the tag braille next to @media, in that way, if this person has a special device capable of translating sites into braille, it will work.

Other useful case will be having to deal with mobile devices or especial screens, then we can use handheld or screen and (min-width:480px)

Some other properties can be used for different media types. For example, the "font-size" property can be used for both screen and print media, but perhaps with different values. A document usually needs a larger font-size on a screen than on paper, and sans-serif fonts are easier to read on the screen, while serif fonts are easier to read on paper.

Media Types

Media Type Description
all Used for all media type devices
aural Used for speech and sound synthesizers
braille Used for braille tactile feedback devices
embossed Used for paged braille printers
handheld Used for small or handheld devices
print Used for printers
projection Used for projected presentations, like slides
screen Used for computer screens
tty Used for media using a fixed-pitch character grid, like teletypes and terminals
tv Used for television-type devices

Example:
This example displays screen,print and custom screens for a mobile device:

<html>
<head>
<style>
@media screen
   {
   p.test {font-family:verdana,sans-serif;font-size:14px;}
   }
@media print
   {
   p.test {font-family:times,serif;font-size:10px;}
   }
@media screen,print
   {
   p.test {font-weight:bold;}
   }
@media screen and (min-width:200px) and (max-width:480px)
   {
      #navar{
       float: none;
       width: 200px;
      }
   }
@media screen and (min-width:480px)
   {
      #navar{
       float: left
       width: 500px;
      }
   }
</style>
</head>

<body>
....
</body>
</html>

Wednesday 14 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – sessionStorage vs localStorage

HTML5 has introduced a new paradigm in the save state or save objects world for HTML5. Unfortunately this is not available for all the browsers yet, but it is available for the whole Windows 8 platform, including apps.

There are two types of Web Storage so far, and these are the localStorage, and the sessionStorage. The main difference is that the localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit. The antagonist is the sessionStorage object which follows this rule:

When a new HTMLDocument is created, the user agent must check to see if the document's top-level browsing context has allocated a session storage area for that document's origin. If it has not, a new storage area for that document's origin must be created.

Each Document object must have a separate object for its Window's sessionStorage attribute.

sessionStorage object will not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window. As summary, as soon as we are in our tab the session storage allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie. This is what my implementation is trying to do with browsers that do not implement this special object. If you have doubts, you can directly test the demo link, and come back whenever you want.

To create applications which requiere to remember past data localStorage is our object. For other purposes we can use sessionStorage which at the end of the day is like Session in ASP.NET.

Tuesday 13 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Calling a Web Service with AJAX

There are different ways to call a web service in JavaScript, but the best ones are done with AJAX. I have decided to add the same call but with different formats, so you can’t get lost and choose your favourite.

url: Web service address
type: Protocol, you can choose between GET and POST
timeout: Who long it is your application waiting for the web service.
dataType: Type of data, it could be text , json etc.
contentType: The content type you want, ie: "application/json; charset=utf-8",
cache: Read example below…
datafilter: Read example below…
Accepts:
Read example below…

METHOD 1

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text'
     }).done(function (responsetext) {
         //do something
     }).fail(function () {
         //do something
     });



METHOD 2

     $.ajax({
         url: '/sdsd/sdsd',
         type: 'GET',
         timeout: 1000,
         dataType: 'text',
         success: function (responsetext) {
             //do something
         },
         error: function (e) {
             //do something
         }
     });




If you don’t specify an error handling jQuery will keep running.



To work with JSON so you can pass data across, JavaScript provides JSON.stringify and JSON.parse.



If you want to send JSON data , you can use something like this (Thanks Bobby):

 function InfoByDate(sDate, eDate) {
        var divToBeWorkedOn = "#AjaxPlaceHolder";
        var webMethod = "http://MyWebService/Web.asmx/GetInfoByDates";
        var parameters = "{'sDate':'" + sDate + "','eDate':'" + eDate + "'}";
        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $(divToBeWorkedOn).html(msg.d);
            },
            error: function (e) {
                $(divToBeWorkedOn).html("Unavailable");
            }
        });
    }



The onreadystatechange event is key in AJAX. This is the only way to monitor what is going on. We have three core properties. Please check the values and the example.



onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes

readyState
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status
200: "OK"
404: Page not found

<html>
<head>
<script>
    function loadXMLDoc() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "ajax_info.txt", true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I recently show this question in a what it could be a Microsoft exam, and I think it will be quite useful to try to understand ajax calls, it is based on the accepts and datafilter parameter:

You are developing a web application that retrieves data from a web service. The data being retrieved is a custom binary datatype named bint. The data can also be represented in XML. Two existing methods named parseXml() and parseBint() are defined on the page. The application must:
· Retrieve and parse data from the web service by using binary format if possible
· Retrieve and parse the data from the web service by using XML when binary format is not possible



You need to develop the application to meet the requirements. What should you do? (To answer, drag the appropriate code segment to the correct location. Each code segment may be used once, more than once, or not at all. You may need to drag the split bar between panes or scroll to view content.)

          var request = $.ajax({
            uri:'/',
            accepts: 'application/bint, text/xml',
            datafilter: function(data,type){
                if(request.getResponseHeader("Content-Type")=="application/bint")
                   return parseBint(data);
                else
                   return parseXml();
                 },            
            success: function (data) {
              start(data);
            }
        });


Another interesting example is the way you can display on-line stock rates in real time. One of the features we should use to get a time stamp in the header is cache set to false. This will force requested pages not to be cached by the browser. I attach an example:

var stockRate;
function getResults(){
$.ajax({
            async: false,
            cache:false,
            type: "POST",
            url: "stockrates.asmx/rates"
            data: {'stockname':stockName},
            dataType: "json",
            success: function (msg) {
               stockRate=result;
        });
        ShowRate();
}

HMTL 5, CSS3 and JavaScript for Windows 8 – User Input Validation

HTML 5 Supports new validation fields and new input types. This new features are going to make the life really easy for us if we know what we have and what we can use.

The <input> tag supports in the type attribute, the following values:

button
checkbox
color
date
datetime
datetime-local
email
file
hidden
image
month
number
password
radio
range
reset
search
submit
tel
text
time
url
week

There are some tips you should know:

    • If one of the types is not supported by the browser, the field will be displayed anyway, but not in the correct format.
    • Use the form event to validate instead the input event.
    • HTML likes to emphasize the name and id attributes. id for CSS and name when the form is submitted.

We also have the required attribute. This attribute is completely new and allow us to validate client-side. A good validation will include server-side validation as well, so don’t forget to do that.

ie:  <input type="text" name="username" required="required" />

We can set maximum and minimum values with our input control. To do that we will be using the max attribute and the min attribute.

ie: <input type="text" name="price" type=”number” required="required" min=”5” max=”100” />

There is an excellent attribute it is going to help us formatting numbers or any character, very useful for phone numbers by the way. The attribute is called pattern.

The pattern attribute specifies a regular expression against which the control's value, or, when the multiple attribute applies and is set, the control's values, are to be checked.

If specified, the attribute's value must match the JavaScript Pattern production. [ECMA262]

If an input element has a pattern attribute specified, and the attribute's value, when compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled (see ECMA262 Edition 5, sections 15.10.7.2 through 15.10.7.4), compiles successfully, then the resulting regular expression is the element's compiled pattern regular expression. If the element has no such attribute, or if the value doesn't compile successfully, then the element has no compiled pattern regular expression. [ECMA262]

Constraint validation: If the element's value is not the empty string, and either the element's multiple attribute is not specified or it does not apply to the input element given its type attribute's current state, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of the element's value, then the element is suffering from a pattern mismatch.

Constraint validation: If the element's value is not the empty string, and the element's multiple attribute is specified and applies to the input element, and the element has a compiled pattern regular expression but that regular expression does not match the entirety of each of the element's values, then the element is suffering from a pattern mismatch.

The compiled pattern regular expression, when matched against a string, must have its start anchored to the start of the string and its end anchored to the end of the string.

Note:
This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

When an input element has a pattern attribute specified, authors should include a title attribute to give a description of the pattern. User agents may use the contents of this attribute, if it is present, when informing the user that the pattern is not matched, or at any other suitable time, such as in a tooltip or read out by assistive technology when the control gains focus.

ie: <label> Part number: <input pattern="[0-9][A-Z]{3}" name="part" title="A part number is a digit followed by three uppercase letters."/> </label>

It will produce the following:

A part number is a digit followed by three uppercase letters.
You cannot submit this form when the field is incorrect.

How to create a nice border validation?
The best practice for validation logic is to add a red border when the validation has not been done properly. In CSS 3 you can add the valid/invalid into the input element.

For validation you could have the following:
input {
  border: solid 1px;
}
input:invalid{
   border-color: #f00;
}
input:valid{
  border-color: #0f0;
}

Monday 12 November 2012

HMTL 5, CSS3 and JavaScript for Windows 8 – Little JavaScript tips

In this post I am going to add these small things I always forget when I work with JavaScript and are quite useful:

  1. How do you put a message in the browser’s status bar?: windows.status(“hello world”);
  2. What do you use to comment in JavaScript?: // and /* */
  3. What is the correct way to write a JavaScript array?: var txt = new Array (“Hello”,”World”, “how”);
  4. How do you write something with JavaScript?: document.write(“Hello World”);
  5. How does a “while” loop start?: while(i<=10);
  6. What is the purpose of DOM (Document Object Model)?: The DOM represents the structure of a web page. You use it to add dynamic functionality to the page.
  7. DOM core methods to create new objects for a document:
      • document.createElement(tagname)
      • document.createTextNode(string)
      • document.createAttribute(name,value)
      • document.createDocumentFragment
  8. How do you round a number to the nearest integer?: Math.round(7.25);
  9. How do you find the Maximum number between two numbers?: Math.max(x,y);
  10. How to pass a JavaScript reference into a website: <script type=”text/javascript” src=”alertme.js”></script>
  11. Internet Explorer 6,7 and 8 do not support addEventListener() and removeEventListener(). Use similar attachEvent() and detachEvent() functions instead.
    Some events in the HTML DOM ‘bubble’ meaning that if the event occurs on an element (and it is or isn’t handled), the event will then also fire on the element’s parent node and then on its grandparent node and so on until the event reaches an element where it may not bubble any further or it reaches the root node. Both addEventListener and removeEventListener have an optional third Boolean parameter indicating whether or not this is the case.
  12. How do you find clients browser name?: navigator.appName
  13. How do you open a new window in JavaScript?:mywindow=window.open(“http://www.google.com”);
  14. How do you split a large string in two lines in Javascript?:
    document.write(“hello my name is \
    prince”);
  15. Microsoft implementation of JavaScript is called JScript.
  16. <noscript> tag Alerts the users that your page uses JavaScript, and so the user should enable JavaScript in the browser in order to display your page correctly.
  17. Having the following code what does this code returns….(this is a nice exercise):

<script>
var a=””
var b=0;
var c=false;
document.write(a==c);//true
document.write(a===c);//false
document.write(b==c);//true
document.write(b===c);//false
</script>



</script>

HMTL 5, CSS3 and JavaScript for Windows 8 - IMG

This is a nice question I remembered for one of my Microsoft exams, I have just wanted to blog it:

Which is mandatory attribute in this line?

<img src=”lalala.png” alt"=”this is lalala” height=”100” width=”100”>

Answer… src!

Enjoy your day…

HMTL 5, CSS3 and JavaScript for Windows 8 – The magic of the <SECTION> and <ARTICLE> tags in HTML 5.

<Section>:
There is a new kid on the block in HTML5, and that is called <Section>. The <Section> tag has been introduced to make the life easier to the web developers. It is basically a notation, but a really useful and powerful one, especially if it is combined withe the <Article> tag.

The <Section> tag defines sections in a document. Such as chapters, headers, footers, or any other sections of the document. One of the best things about the <Section> Tag, it is the fact it supports all the Globals Attributes in HTML and of course the Event Attributes.

So this:
<section>
  <h6>WWF's Panda symbol</h6>
  <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
</section>

It will generate:

WWF's Panda symbol

The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.

<Article>:
The <Article> tag is much more independent than the section one,self-contained content. An article normally comes embedded into a section.

An article should make sense on its own and it should be possible to distribute it independently from the rest of the site.

Potential sources for the <article> element:

  • Forum post
  • Blog post
  • News story
  • Comment

So this:
<article>
  <h1>Internet Explorer 9</h1>
  <p>Windows Internet Explorer 9 (abbreviated as IE9) was released to
  the  public on March 14, 2011 at 21:00 PDT.....</p>
</article>

It will generate:

Internet Explorer 9

Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14, 2011 at 21:00 PDT.....

HMTL 5, CSS3 and JavaScript for Windows 8 – [href] attribute.

A good question and easy to answer in the href attribute in HTML 5. Well just to let you know, it keeps doing the same thing than HTML 4, always with its sister <a>.

The [href] attribute is the most important part of linking one online resource to another.

HMTL 5, CSS3 and JavaScript for Windows 8 – What is an Ordered List?

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked with numbers.

In the HTML 5 paradigm, only the following attributes are supported:

 

Attribute

Vale

Description

compact compact Not supported
reversed reversed Specifies that the list order should be descending (9,8,7...)
start number Specifies the start value of an ordered list
type

1
A
a
I
i

Specifies the kind of marker to use in the list.

An example like this:
<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
<ol start="50">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Will produce the following:

  1. Coffee
  2. Tea
  3. Milk
  1. Coffee
  2. Tea
  3. Milk

HMTL 5, CSS3 and JavaScript for Windows 8 – Heading Tags in a HTML 5 Document.

Html 5 is keeping the old fashion HTML heading tags, but this time they are going to be used extensible. Remember larger the number, smaller the header.

<H1> Hello World </H1>:

Hello World

<H2> Hello World </H2>:

Hello World

<H3> Hello World </H3>:

Hello World

<H4> Hello World </H4>:

Hello World

<H5> Hello World </H5>:

Hello World

<H6> Hello World </H6>:

Hello World

HMTL 5, CSS3 and JavaScript for Windows 8 – An unofficial collaboration of Web browser manufacturers and interested parties

WHATWG has become a large community where vendors and users have become key in the project. The Web Hypertext Application Technology Working Group (WHATWG) is a community of people interested in evolving HTML and related technologies. The WHATWG was founded by individuals from Apple, the Mozilla Foundation and Opera Software in 2004.

Since then, the editor of the WHATWG specifications, Ian Hickson, has moved to Google. Chris Wilson of Microsoft was invited but did not join, citing the lack of a patent policy to ensure all specifications can be implemented on a royalty-free basis.

The DOCTYPE declaration for this new standard is:
<!DOCTYPE html>