HTML5 web storage – offline storage solution for the web

Using HTML5 you can store data into user’s browser. Before HTML5, there was only one way to store data using cookies. This web storage stores data in key/value pair. You can use this technique to store data offline.

How to check that browser supports web storage?

if(typeof(Storage) !== “undefined”)
{
// Browser supports web storage. So you can use local and session storage
}
Else
{
// Browser does not support web storage.
}

There are two types of the web storage

  1. Local Storage
  2. Session Storage

Local Storage

You can store data into local storage like

localStorage.key = “value”;

And you can retrieve it as

var localStorageValue = localStorage.key;

This storage is persisted even you closes and reopen the browser.

Session Storage

This storage is same as the local storage. One thing differs from local storage is that, the data will be lost if user closes the browser. So if you want to store data per session, go with this storage.

You can store data as follows

sessionStorage.key = “value”;

After you can retrieve as

var sessionStorageValue = sessionStorage.key;
 

How to check/debug web storage is working or not?

Developer tools of the browser will show data stored into the web storage. Following image taken from w3schools.com describes the where you can find the web storage.

HTML5 web storage

 

You can check your browser supports how many HTML5 features just opening http://html5test.com/ into your browser.

jQuery Mobile Introduction

Touch-Optimized Web Framework for Smartphones & Tablets

Recently I worked on mobile application based on HTML5 and JQuery. I have used jQuery mobile framework. It is very simple to learn and use, if you already know jQuery. You can find out more stuff from below site.

http://jquerymobile.com/

You can view documentation from below site. This site optimized to open in all mobile browsers.

http://demos.jquerymobile.com/1.4.0/

You can download necessary files to use jQuery mobile from below site.

http://jquerymobile.com/download/

jQuery mobile also provide CDN-hosted versions. These are minified and compressed with host images.

You need to copy and paste following lines into your project to use jQuery mobile framework.

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>

jQuery mobile supports theme based UI. This framework also provides default themes. You can create your own custom theme by theme roller.

http://themeroller.jquerymobile.com/

Metro style context menu using JavaScript and CSS

What is context menu?

When you right click on browser window, browser will show you a menu containing some common functions.
See following image for reference.

Metro style context menu using JavaScript and CSS

If you want to build your own custom context menu, follow the easy steps below.

Step 1 – HTML

<div id="context-menu">
<ol>
<li><a href="#">menu 1</a> </li>
<li><a href="#">menu 2</a> </li>
<li class="list-devider">
<hr />
</li>
<li><a href="#">menu 3</a> </li>
<li><a href="#">menu 4</a> </li>
<li><a href="#">menu 5</a> </li>
<li class="list-devider">
<hr />
</li>
<li><a href="#">menu 6</a> </li>
<li><a href="#">menu 7</a> </li>
</ol>
</div>

Step 2 – CSS

Following is CSS declaration for above context menu structure. This will give metro style look to context menu.

#context-menu
{
z-index: 1000;
position: absolute;
border: solid 2px black;
background-color: white;
padding: 5px 0;
display: none;
} #
context-menu ol
{
padding: 0;
margin: 0;
list-style-type: none;
min-width: 130px;
width: auto;
max-width: 200px;
}
#context-menu ol li
{
margin: 0;
display: block;
list-style: none;
zoom: 0;
padding: 5px 5px;
}
#context-menu ol li:hover
{
background-color: #efefef;
}
#context-menu ol li:active
{
color: White;
background-color: #000;
}
#context-menu ol .list-devider
{
padding: 0px;
margin: 0px;
}
#context-menu ol .list-devider:hover
{
/*background-color: #efefef;*/
}
#context-menu ol .list-devider hr
{
margin: 2px 0px;
}
#context-menu ol li a
{
color: Black;
text-decoration: none;
display: block;
padding: 0px 5px;
}
#context-menu ol li a:active
{
color: White;
}

Step 3 – JavaScript

To enable context menu, write down following script.

$(document).ready(function () {
try {
$(document).bind("contextmenu", function (e) {
e.preventDefault();
$("#context-menu").css({ top: e.pageY + "px", left: e.pageX + "px" }).show(100);
});
}
catch (err) {
alert(err);
}
});

Note: Above script require JQuery to be included in document.

In above script we have set context menu function to our custom function. This function will prevent default context menu of browser and
will show custom context menu.

Here we can add following function when user clicks on document, will hide context menu.

$(document).bind("click", function (event) {
$("#context-menu").hide();
});

look at the beautiful metro style context menu tested in IE9.

Metro style context menu using JavaScript and CSS

Enjoy JavaScript…

Convert Text to Image using canvas

With using canvas we can export image with dynamic text. Let see example below.

HTML code

<h2>Text</h2>
<div id="contentToWrite1" style="border: solid 1px gray; padding: 5px;">
first line
</div>
<br />
<br />
<div id="contentToWrite2" style="border: solid 1px gray; padding: 5px;">
second line
</div>
<h2>Canvas</h2>
<canvas id="canvas" width="200" height="200" style="border: solid 1px gray;">
</canvas>
<br />
<h2>Exported Image</h2>
<img id="exportedImage" width="200" height="200" src="#" />
<br />
<input type="button" name="name" value="export canvas to image" onclick="exportImage();" />

JavaScript code

window.onload = function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.font = "20px Georgia";
var ele = document.getElementById("contentToWrite1");
var ele1 = document.getElementById("contentToWrite2");
if (ele.textContent) {
// for firefox
context.fillText(ele.textContent, 10, 90);
context.fillText(ele1.textContent, 10, 110);
} else {
// for other browser
context.fillText(ele.innerText, 10, 90);
context.fillText(ele1.innerText, 10, 110);
}
}
function exportImage() {
var img = document.getElementById("exportedImage");
img.src = canvas.toDataURL('image/png');
}

On windows load function creates object of canvas and context of canvas. We will use different properties and method of context to
render content on canvas.

  • context.font : This property used to set font style to content on canvas.
  • context.fillText(textToWrite,x,y): this method used to render text on canvas.

By using above methods we have rendered content on canvas, looks like below.

Convert Text to Image using canvas

When we click on button export ‘canvas to image’ image will be set to html image element below to canvas.

  • canvas.toDataURL: This is canvas method to render it as image.

Enjoy JavaScript…

Call function of the parent window from iframe window from JavaScript

You can call code of the parent window form child window.

f you open window by using iframe, you can communicate from child window with the parent.

Let’s see an example

Page1.html (Parent window)
<script>
        function HelloFromChild(name) {
            alert("Hello " + name + " , (called from child window)");
        }
    </script>
<iframe src="Page2.html" width="200"></iframe>
Page2.html (child window opened in iframe)
<script>
        function onClick() {
            parent.HelloFromChild(document.getElementById("name").value);
        }
</script>
Iframe page
<input type="text" name="name" value="techie" id="name" />
<button onclick="onClick();">Call Parent Window Function</button>

When you open Page1.html in browser you will see the output as below. Click on the button to call parent function.

When you click on the button, onClick event will be fired. onClick event will call function from parent window by using parent variable. By using parent variable you can call function from parent window.

Call function of the parent window from iframe window from JavaScript

 

Check internet connection using JavaScript

Sometimes you need to check device have internet connection or not.

This can be done by simple JavaScript function

var connectionMessage = "Your device have internet connection.";
var noConnectionMessage = "Ohh! It seems that your device dont have internet connection.";
window.onload = checkInternetConnection;
function checkInternetConnection() {
  var isOnLine = navigator.onLine;
  if (isOnLine) {
    alert(connectionMessage);
  } else {
    alert(noConnectionMessage);
  }
}

Enjoy JavaScript…

Making Field Read only in SharePoint 2010

Many times you need to disable the fields in SharePoint form for ‘New Item’. By using JavaScript we can disable field in easier way. Lets
discuss an example.

Using JavaScript

Find field id by inspecting element in browser’s developer tools. The filed id is something like this
‘ctl00_m_g_efe2ea91_242b_4746_bb44_5a67e8cbc5c2_ff331_ctl00_ctl00_DateTimeField_DateTimeFieldDate’

Then write down few steps to disable it.

function DisableField()
{
  try
  {
    var element = document.getElementById('ctl00_m_g_efe2ea91_242b_4746_bb44_5a67e8cbc5c2_ff331_ctl00_ctl00_DateTimeField_')
    element.disabled=true;
  }
  catch(err)
  {
  }
}

Now you need to call the function ‘DisableField()’ on body load.

SharePoint gives out of the box functionality for JavaScript developer to inject custom function into function list of SharePoint function lists.

You can push ‘DisableField()’ function as follows.

_spBodyOnLoadFunctionNames.push("DisableField()");

Enjoy JavaScript…

Fixed width, centered design in SharePoint site using css

By default SharePoint gives 100% width to sites created. We can fixed width of site by using custom css and changing some class names
in master page.

Lets have look to the solution.

div.s4-title.s4-lp, body #s4-mainarea, #s4-topheader2, #s4-statusbarcontainer
{
width: 960px;
margin: auto;
padding: 0px;
float: none;
background-image: none;
background-color: white;
}

To get fixed width design add css classes to the following element.

Default

<div id="s4-workspace">

Fixed Width

<div id="s4-workspace">

Default

<div id="s4-titlerow" class="s4-pr s4-notdlg s4-titlerowhidetitle">

Fixed Width

<div id="s4-titlerow"  class="s4-pr s4-notdlg s4-titlerowhidetitle s4-nosetwidth">

Fixed width, centered design in SharePoint site using css

JavaScript – Strict mode

Strict mode is new feature in ECMA Script 5. This mode allows you to run program, piece of program (context) in strict mode.

This mode will help your code by throwing error if your program violets standard.

Let’s see example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Use Strict mode</title>
</head>
<body onload="loadDoc()">
<div id="content1"></div>
<div id="content2"></div>
<script type="text/javascript">
var ele1 = document.getElementById("content1");
foo1 = "Hello";
ele1.innerHTML = "" + foo1;
function loadDoc() {
"use strict";
var ele2 = document.getElementById("content2");
foo2 = "Hello from page load";
ele2.innerHTML = "" + foo2;
}
</script>
</body>
</html>

In above example we have used foo1 and foo2 variables without declarations.
Here we put “use strict”; statement in loadDoc() function then it will throw error like below(tested in chrome). Uncaught
ReferenceError: foo2 is not defined Just add declaration of foo2 in loadDoc() function and browser will not throw any error.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Use Strict mode</title>
</head>
<body onload="loadDoc()">
<div id="content1"> </div>
<div id="content2"> </div>
<script type="text/javascript">
var ele1 = document.getElementById("content1");
foo1 = "Hello";
ele1.innerHTML = "" + foo1;
function loadDoc() {
"use strict";
var ele2 = document.getElementById("content2");
var foo2 = "Hello from page load";
ele2.innerHTML = "" + foo2;
}
</script>
</body>
</html>

Output is:

JavaScript Strict Mode

If you put “use strict” at top of file, then it will enable strict mode in entire file. It keeps your code safe and standard.

Note: You will not see any error in IE9 or below browser. IE 10 will support strict mode.

http://msdn.microsoft.com/en-us/library/ie/hh673540(v=vs.85).aspx

JavaScript – Ternary Operator

Following is syntax of ternary operator in JavaScript.

test?expression1:expression2

Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ternary Operator</title>
</head>
<body> <p id="demo"> </p>
<script type="text/javascript">
var ele = document.getElementById("demo");
var now = new Date();
var greeting = "Current time: " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " " + ((now.getHours() < 11) ? "am" : "pm"); 
ele.innerHTML = "" + greeting;
</script>
</body>
</html>

Output is:

Current time: 17:33:14 pm

Here we have used ternary operator to show ‘am’ or ‘pm’ next to current time. It checks hours is less than 11 then it add am or add pm next to time