Using the contentEditable attribute
is used to make the text of an element as editable
<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>HTML5 content editable example</TITLE> <SCRIPT> function getUserScribble() { var scribble = '<i style="color:magenta;font-family:Geneva, Arial; font-size:5;">Write here....</i>'; document.getElementById('scribble').innerHTML = scribble; } </SCRIPT> </HEAD> <BODY onload="getUserScribble()"> <P> <TABLE width="320" height="450" border="0" cellspacing="0" cellpadding="62"> <TD background="np.jpg" contentEditable="true" id="scribble"></TD> </TABLE> <SCRIPT> getUserScribble(); </SCRIPT> <P> </BODY> </HTML>
Implementing the spell check attribute
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>HTML5 spell check example</TITLE>
- </HEAD>
- <BODY>
- <FORM>
- <TEXTAREA style="width:300px;height:150px;border: 1em solid black" spellcheck="false" contentEditable="true">Spell check off</TEXTAREA><BR />
- <TEXTAREA style="width:300px;height:150px;border: 1em solid black" spellcheck="true" contentEditable="true">Spell check on</TEXTAREA><BR />
- </FORM>
- </BODY>
- </HTML>
Creating Custom Data Attributes
HTML 5 enables you to embed custom data attributes with HTML elements
the custom data attributes are prefixed with the data-text, such data-xxx and data-yyy.
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>HTML5 custom attributes example</TITLE>
- </HEAD>
- <BODY>
- <IMG src="bike3.jpg" data-out="bike5.jpg" data-over="bike4.jpg" />
- <IMG src="bike3.jpg" data-out="bike5.jpg" data-over="bike4.jpg" />
- <IMG src="bike3.jpg" data-out="bike5.jpg" data-over="bike4.jpg" />
- <SCRIPT type="text/javascript">
- function imagerollover(){
- var allimages=document.getElementsByTagName("img")
- var preloadimages=[]
- for (var i=0; i<allimages.length; i++){
- if (allimages[i].getAttribute("data-over"))
- {
- preloadimages.push(new Image())
- preloadimages[preloadimages.length-1].src=allimages[i].getAttribute("data-over")
- allimages[i].onmouseover=function(){
- this.src=this.getAttribute("data-over")
- }
- allimages[i].onmouseout=function(){
- this.src=this.getAttribute("data-out")
- }
- }
- }
- }
- imagerollover()
- </SCRIPT>
- </BODY>
- </HTML>
Implementing session storage
the seessionstorage object is used to store data till the duration of the browser session.
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>Session storage example</TITLE>
- <style type="text/css">
- #todolist{
- width:350px;
- height: 200px;
- font:normal 14px Arial;
- background:lightyellow;
- border:5px groove gray;
- overflow-y:scroll;
- padding:4px;
- }
- #todolist ol{
- margin-left:-15px;
- }
- #todolist li{
- border-bottom:1px solid gray;
- margin-bottom:8px;
- }
- </STYLE>
- </HEAD>
- <BODY>
- <DIV id="todolist" contentEditable="true">
- <DIV contentEditable="false"><B>Enter your tasks in the following To Do List:</B></DIV>
- <OL>
- <LI>Take breakfast in ABC hotel</LI>
- <LI>Meeting with Aggrawal and group company manager</LI>
- <LI>Set alarm to 5:30 am</LI>
- </OL>
- </DIV>
- <INPUT type="submit" value="Reset To Do List" onClick="resetlist();return false" />
- <script type="text/javascript">
- var defaulthtml='<div contentEditable="false"><b>Enter your tasks in the following To Do List:</b></div>\n'
- defaulthtml+='<ol>\n'
- defaulthtml+='<li>Take breakfast in ABC hotel</li>\n'
- defaulthtml+='<li>Meeting with Aggrawal and group company manager</li>\n'
- defaulthtml+='<li>Set alarm to 5:30 am</li>\n'
- defaulthtml+='</ol>'
- function resetlist(){
- todolistref.innerHTML=defaulthtml
- domstorage.todolistdata=defaulthtml
- }
- var todolistref=document.getElementById("todolist")
- var domstorage=(window.sessionStorage)? sessionStorage[location.hostname] : null
- if (domstorage){
- if (domstorage.todolistdata){
- todolistref.innerHTML=domstorage.todolistdata
- }
- todolistref.onkeyup=function(e){
- domstorage.todolistdata=this.innerHTML
- }
- }
- </SCRIPT>
- </HTML>
Implementing local storage
local storage is same as session storage, except for the feature of persistency
local storage stores the saved data on a user's computer even after closing the browser window
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>HTML5 local storage example</TITLE>
- <style type="text/css">
- #todolist{
- width:350px;
- height: 200px;
- font:normal 14px Arial;
- background:lightyellow;
- border:5px groove gray;
- overflow-y:scroll;
- padding:4px;
- }
- #todolist ol{
- margin-left:-15px;
- }
- #todolist li{
- border-bottom:1px solid gray;
- margin-bottom:8px;
- }
- </STYLE>
- </HEAD>
- <BODY>
- <DIV id="todolist" contentEditable="true">
- <DIV contentEditable="false"><B>Enter your tasks in the following To Do List:</B></DIV>
- <OL>
- <LI>Take breakfast in ABC hotel</LI>
- <LI>Meeting with Aggrawal and group company manager</LI>
- <LI>Set alarm to 5:30 am</LI>
- </OL>
- </DIV>
- <INPUT type="submit" value="Reset To Do List" onClick="resetlist();return false" />
- <script type="text/javascript">
- var defaulthtml='<div contentEditable="false"><b>Enter your tasks in the following To Do List:</b></div>\n'
- defaulthtml+='<ol>\n'
- defaulthtml+='<li>Take breakfast in ABC hotel</li>\n'
- defaulthtml+='<li>Meeting with Aggrawal and group company manager</li>\n'
- defaulthtml+='<li>Set alarm to 5:30 am</li>\n'
- defaulthtml+='</ol>'
- function resetlist(){
- todolistref.innerHTML=defaulthtml
- domstorage.todolistdata=defaulthtml
- }
- var todolistref=document.getElementById("todolist")
- var domstorage=window.localStorage|| (window.globalStorage? globalStorage[location.hostname] : null)
- if (domstorage){
- if (domstorage.todolistdata){
- todolistref.innerHTML=domstorage.todolistdata
- }
- todolistref.onkeyup=function(e){
- domstorage.todolistdata=this.innerHTML
- }
- }
- </SCRIPT>
- </HTML>
Implementing Database storage
HTML 5 enables you to store your data in database on a client's machine using a real SQL database
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE> Database storage example</TITLE>
- <STYLE>
- #websqldb-example .record-list li:nth-child(odd) { background-color: lightgreen; }
- #websqldb-example .record-list li:nth-child(even) { background-color: pink; }
- #websqldb-example .record-list li {
- padding-left: 5px;
- }
- #db-results {
- max-height: 150px;
- overflow: auto;
- text-align: left;
- }
- #websqldb-example .error {
- color: red;
- }
- </STYLE>
- </HEAD>
- <BODY>
- <DIV class="slide" id="web-sql-db">
- <HEADER><h1>Web SQL Database</h1></HEADER>
- <SECTION>
- <DIV class="center" id="websqldb-example">
- <BUTTON onclick="webSqlSample.createTable()">create table</BUTTON> <BR />
- <INPUT type="text" id="todoitem" />
- <BUTTON onclick="webSqlSample.newRecord()">Add new item to the table</BUTTON> <BR />
- <BUTTON onclick="webSqlSample.dropTable()">drop table</BUTTON>
- <P>The generated database is given as follows:</P>
- <UL class="record-list" id="db-results"></UL>
- <DIV id="db-log"></DIV>
- </DIV>
- <SCRIPT defer>
- var webSqlSample = (function() {
- var db;
- var log = document.getElementById('db-log');
- if (window.openDatabase) {
- db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
- showRecords();
- }
- document.getElementById('db-results').addEventListener('click', function(e) { e.preventDefault(); }, false);
- function onError(tx, error) {
- log.innerHTML = '<p class="error">Error: ' + error.message + '</p>';
- }
- function showRecords() {
- document.getElementById('db-results').innerHTML = '';
- db.transaction(function(tx) {
- tx.executeSql("SELECT * FROM Test", [], function(tx, result) {
- for (var i = 0, item = null; i < result.rows.length; i++) {
- item = result.rows.item(i);
- document.getElementById('db-results').innerHTML +=
- '<li><span contentEditable="true" onkeyup="webSqlSample.updateRecord('+item['id']+', this)">'+
- item['text'] + '</span> <a href="#" onclick="webSqlSample.deleteRecord('+item['id']+')">[Delete]</a></li>';
- }
- });
- });
- }
- function createTable() {
- db.transaction(function(tx) {
- tx.executeSql("CREATE TABLE Test (id REAL UNIQUE, text TEXT)", [],
- function(tx) { log.innerHTML = '<p>"Test" table created!</p>' },
- onError);
- });
- }
- function newRecord() {
- var num = Math.round(Math.random() * 10000); // random data
- db.transaction(function(tx) {
- tx.executeSql("INSERT INTO Test (id, text) VALUES (?, ?)", [num, document.querySelector('#todoitem').value],
- function(tx, result) {
- log.innerHTML = '';
- showRecords();
- },
- onError);
- });
- }
- function updateRecord(id, textEl) {
- db.transaction(function(tx) {
- tx.executeSql("UPDATE Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
- });
- }
- function deleteRecord(id) {
- db.transaction(function(tx) {
- tx.executeSql("DELETE FROM Test WHERE id=?", [id],
- function(tx, result) { showRecords() },
- onError);
- });
- }
- function dropTable() {
- db.transaction(function(tx) {
- tx.executeSql("DROP TABLE Test", [],
- function(tx) {
- showRecords();
- log.innerHTML = '<p>Table deleted!</p>' },
- onError);
- });
- }
- return {
- newRecord: newRecord,
- createTable: createTable,
- updateRecord: updateRecord,
- deleteRecord: deleteRecord,
- dropTable: dropTable
- }
- })();
- </SCRIPT>
- </SECTION>
- </DIV>
- </BODY>
- </HTML>
the createable(),
newRecord(),
deleteRecord(),
updateRecord(),
showRecord(), and dropTable() functions are created using javaScript
these functions are using the transaction() and executeSql() functions to insert and access the data stored in a database
Implementing ddrag and drop features
draggable and dropzone attributes are used to implement the drag and drop feature
- <!DOCTYPE HTML>
- <HEAD>
- <STYLE>
- #drag-zone {
- list-style: none;
- float: left;
- }
- #drag-zone li * {
- border: 4px solid #888;
- display: block;
- }
- #drag-zone, #drop-zone, #drop-data { width: 30%; }
- #drop-zone, #drop-data {
- padding: 40px;
- border: 5px solid #888;
- float: right;
- height: 200px;
- overflow: auto;
- }
- #drop-zone.hovering {
- border: 5px solid #aaa;
- background-color: rgba(255, 0, 0, 0.199219);
- }
- #drop-data {
- background-color: #eee;
- font-family: Monospace;
- -ms-word-wrap: break-word;
- word-wrap: break-word;
- }
- .datatypes {
- font-weight: bold;
- }
- .draggable-text {
- padding: 5px;
- }
- </STYLE>
- </HEAD>
- <BODY>
- <H1>Drag and Drop example</H1>
- <SECTION id="dnd-section">
- <OL id="drag-zone">
- <LI><SPAN class="draggable-text" draggable>Select and drag and drop text 1</SPAN></LI>
- <LI><SPAN class="draggable-text" draggable class="overwrite">Select and drag and drop text 2</SPAN></LI>
- <LI><IMG src="bike3.jpg" draggable class="copy" /></LI>
- <LI><IMG src="bike4.jpg" draggable class="copy" /></LI>
- </OL>
- <DIV id="drop-data">Details of the dragged item</DIV>
- <DIV id="drop-zone">Drop Area</DIV>
- <SCRIPT defer>
- (function() {
- var dragZone = document.querySelector('#drag-zone');
- var dropZone = document.querySelector('#drop-zone');
- dragZone.addEventListener('dragstart', function(event) {
- if (event.target.className) {
- event.dataTransfer.effectAllowed = event.target.className;
- event.target.style.border = "4px solid #cc3300";
- }
- else {
- if (event.target.parentNode.className == 'overwrite') {
- event.dataTransfer.setData("text", "<strong>Overwritten Content</strong>");
- }
- event.target.parentNode.style.border = "4px solid #cc3300";
- }
- return true;
- }, true);
- dragZone.addEventListener('dragend', function(event) {
- if (event.target.className) {
- event.target.style.border = "4px solid #888";
- }
- else {
- event.target.parentNode.style.border = "4px solid #888";
- }
- return true;
- }, true);
- dropZone.addEventListener('dragenter', function(event) {
- if (event.preventDefault) event.preventDefault();
- event.dataTransfer.dropEffect = 'copy';
- this.className = 'hovering';
- return false;
- }, false);
- dropZone.addEventListener('dragover', function(event) {
- if (event.preventDefault) event.preventDefault();
- event.dataTransfer.dropEffect = 'copy';
- return false;
- }, false);
- dropZone.addEventListener('dragleave', function(event) {
- if (event.preventDefault) event.preventDefault();
- this.className = '';
- return false;
- }, false);
- dropZone.addEventListener('drop', function(event) {
- if (event.preventDefault) event.preventDefault();
- var imgPassed = null;
- var dropdata = document.querySelector('#drop-data');
- var types = event.dataTransfer.types;
- document.querySelector('#drop-data').textContent = '';
- this.innerHTML = '';
- for (var i = 0; i < types.length; i++) {
- if (types[i] == 'Files') {
- var files = event.dataTransfer.files;
- for (var j = 0; j < files.length; j++) {
- dropdata.textContent += 'File Name: '+files[j].fileName;
- dropdata.textContent += 'File Size: '+files[j].fileSize;
- }
- }
- else {
- if (typeof event.dataTransfer.getData(types[i]) !== 'undefined') {
- dropdata.innerHTML += '<p><em class="datatypes">'+types[i]+'</em>: <br />'+event.dataTransfer.getData(types[i]).replace(/</g, '<') + '</p>';
- }
- }
- if (types[i] == 'text/uri-list') {
- imgPassed = event.dataTransfer.getData('text/uri-list');
- }
- }
- if (imgPassed) {
- var cEl = document.createElement('canvas');
- cEl.width = 200;
- cEl.height = 100;
- var ctx = cEl.getContext('2d');
- var img_buffer = document.createElement('img');
- img_buffer.src = imgPassed;
- img_buffer.style.display = 'none';
- document.body.appendChild(img_buffer); // this line only needed in safari
- img_buffer.onload = function() { ctx.drawImage(img_buffer,0,0,100,100); }
- this.appendChild(cEl);
- } else {
- if (event.dataTransfer.getData('text')) {
- this.innerHTML = event.dataTransfer.getData('text');
- }
- else if (event.dataTransfer.getData('text/plain')) {
- this.innerHTML = event.dataTransfer.getData('text/plain');
- }
- }
- return false;
- }, false);
- })();
- </SCRIPT>
- </SECTION>
- </DIV>
- </BODY>
- </HTML>
Implementing the geolocation feature
HTML 5 provides the support for the geolocation feature to locate a position on google maps
- <!DOCTYPE HTML>
- <HEAD>
- <META charset="utf-8" />
- <TITLE>GeoLocation Demonstrated</TITLE>
- </HEAD>
- <BODY>
- <SECTION id="wrapper">
- <SCRIPT type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></SCRIPT>
- <ARTICLE>
- <P><SPAN id="status">Please wait..we are trying to locate you...</SPAN></P>
- </ARTICLE>
- <SCRIPT>
- function success(position) {
- var s = document.querySelector('#status');
- if (s.className == 'success') {
- return;
- }
- s.innerHTML = "found you!!!!! Your latitude is:"+position.coords.latitude+" and longitude is:"+position.coords.longitude;
- s.className = 'success';
- var mapcanvas = document.createElement('div');
- mapcanvas.id = 'mapcanvas';
- mapcanvas.style.height = '400px';
- mapcanvas.style.width = '560px';
- document.querySelector('article').appendChild(mapcanvas);
- var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
- var myOptions = {
- zoom: 15,
- center: latlng,
- mapTypeControl: false,
- navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
- var marker = new google.maps.Marker({
- position: latlng,
- map: map,
- title:"You are here!"
- });
- }
- function error(msg) {
- var s = document.querySelector('#status');
- s.innerHTML = typeof msg == 'string' ? msg : "failed";
- s.className = 'fail';
- // console.log(arguments);
- }
- if (navigator.geolocation) {
- navigator.geolocation.getCurrentPosition(success, error);
- } else {
- error('not supported');
- }
- </SCRIPT>
- </SECTION>
- </BODY>
- </HTML>
Implementing web worker
web workers are scripts that work in background and do not interrupt user interface scripts.
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>Worker example</TITLE>
- </HEAD>
- <BODY style="background-color:gold;">
- <H3>The highest prime number discovered so far is: <OUTPUT id="result"></OUTPUT></H3>
- <SCRIPT>
- var worker = new Worker('worker.js');
- worker.onmessage = function (event) {
- document.getElementById('result').textContent = event.data;
- };
- </SCRIPT>
- </BODY>
- </HTML>
worker.js
var n = 1;
search: while (true) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage(n);
}
Implementing notifications
HTML 5 provides desktop notifications feature that allows websites to send notifications to your desktop .
you need to run this webpage from internet information services (IIS) server
you need to copy the notification.html file in the inetpub/wwwroot folder
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>HTML5 Notification Example</TITLE>
- <SCRIPT>
- function RequestPermission (callback) {
- window.webkitNotifications.requestPermission(callback);
- }
- function add(){
- if (window.webkitNotifications.checkPermission() > 0) {
- RequestPermission(add);
- }
- else {
- var num1 = parseInt(document.getElementById('num1').value);
- var num2 = parseInt(document.getElementById('num2').value);
- var num3=num1+num2;
- window.webkitNotifications.createNotification("", "Sum of "+num1+" and "+num2+" is", num3).show();
- }
- }
- </SCRIPT>
- </HEAD>
- <BODY>
- <H1>HTML5 Notification Example</H1>
- number 1:<INPUT type="text" id="num1" value=" " ><BR/>
- number 2:<INPUT type="text" id="num2" value=" " ><BR/>
- <BUTTON onclick="add()">add</BUTTON>
- </BODY>
- </HTML>
Creating 2D Graphics
SVG element is used to create 2D graphics in HTML 5
- <!DOCTYPE HTML>
- <HEAD>
- <TITLE>SVG</TITLE>
- </HEAD>
- <BODY>
- <H2>HTML5 SVG Example</H2>
- <SVG id="svgelem" xmlns="http://www.w3.org/2000/svg">
- <CIRCLE id="redcircle" cx="50" cy="50" r="50" fill="red" />
- <LINE x1="200" y1="10" x2="200" y2="100"
- style="stroke:purple;stroke-width:4"/>
- <POLYGON points="50,100 30,20, 170,50" fill="lime" />
- <DEFS>
- <RADIALGRADIENT id="gradient" cx="50%" cy="50%"
- r="50%"
- fx="50%" fy="50%">
- <STOP offset="0%" style="stop-color:rgb(100,250,150);
- stop-opacity:0"/>
- <STOP offset="100%" style="stop-color:rgb(0,100,255);
- stop-opacity:1"/>
- </RADIALGRADIENT>
- </DEFS>
- <ELLIPSE cx="500" cy="50" rx="100" ry="50"
- style="fill:url(#gradient)" />
- <RECT x="50" y="50" width="250" height="250"
- style="fill:blue;stroke:pink;stroke-width:5;
- fill-opacity:0.1;stroke-opacity:0.9;padding:10,50;"/>
- </SVG>
- </HTML>
Implementing Modernizr
Modernizr helps to detect whether the browser supports CSS 3 or HTML 5 features
- <!DOCTYPE HTML>
- <HTML>
- <HEAD>
- <meta charset="utf-8">
- <TITLE>Modernizr Use</title>
- <SCRIPT src="modernizr-1.6.min.js"></script>
- </HEAD>
- <BODY>
- <DIV id="music">
- <AUDIO>
- <SOURCE src="audio.mp3" />
- </AUDIO>
- <BUTTON id="play">Play</button>
- <BUTTON id="pause">Pause</button>
- </DIV>
- <SCRIPT>
- if (Modernizr.audio) {
- alert("Your Browser supports audio.");
- }else{
- alert("Your Browser does not support audio.");
- }
- </SCRIPT>
- </BODY>
- </HTML>
No comments:
Post a Comment