Sunday, 22 December 2013

HTML Textbox to accept Numbers only using Javascript

Posted at  17:24  |  in  

How to allow HTML Textbox to accept Numbers only using Javascript?


While web development, you often encounter the need of functionality where your textboxes should be filled with numbers only.

For example, you want your users to fill the quantity of anything, ID (if it is composed on integers only), price of anything (excluding decimal) etc. In short, you want only numbers plus some keys like backspace, delete. left and right arrow to be typed in the textbox. You can use javascript to restrict your users to fill only numbers in the textbox. It is very simple. On the KeyPress event of any HTML text, just call a simple javascript function which checks the keycodes for the numbers and on the basis of keycodes, it returns true or false. Here is how?

HTML Text

<input type="text" id="txtSample" name="txtSample" onkeypress="return CheckNumeric(event)" />

Javascript 

function CheckNumeric(event)
{
       var key = window.event ? event.keyCode : event.which;

        //Check for backspace, delete, left arrow and right arrow keys

if (event.keyCode == 8  || event.keyCode == 46 ||  
           event.keyCode == 37 || event.keyCode == 39) 
{
return true;
}

        //All other keys excluding numeric keys 
else if ( key < 48 || key > 57 ) 
{
return false;
}

else return true; //Numeric keys from 0 to 9
};

HTML5 <menu> Tag Redefined

The <menu> tag provides an easy way to create menus on a web page. The HTML <menu> element was deprecated in HTML 4.01 but is redefined in HTML5. The HTML <menu> tag defines a list/menu of commands. The <menu> tag is used for context menus, toolbars and for listing form controls and commands.

<li> tag is used within the <menu> tag. For example:

Which pet do you own?
<menu>
 <li>Dog</li>
 <li>Cat</li>
</menu>

You can also place radio buttons and check boxes inside <menu> tags. Have a look at following simple example of <menu> tag

radiobuttons inside <menu> tag

<menu>
   <li><input type="radio" id="radDog" class="radPets" name="radDog"/>Dog</li>
   <li><input type="radio" id="radCat" class="radPets" name="radCat"/>Cat</li>
</menu>

checkboxes inside <menu> tag

<menu>
   <li><input type="checkbox" id="cbDog" class="cbPets" name="cbDog"/>Dog</li>
   <li><input type="checkbox" id="cbCat" class="cbPets" name="cbCat"/>Cat</li>
</menu>

<menu> tag is used instead of <ul> tag

Earlier we used to make an unordered list by using <ul> tag like this:

<ul class="toolbar">
  <li>New</li>
  <li>Open</li>
  <li>Save</li>
  <li>Quit</li>
</ul>

But as I earlier said, <menu> is redefined in HTML5. The <menu> element represents an unordered list of commands. It has a type attribute, which can be set to popup or toolbar.

<menu type="toolbar">
  <li>New</li>
  <li>Open</li>
  <li>Save</li>
  <li>Quit</li>
</menu>

Please note: The <menu> tag is valid within blockquote, body, button, center, dd, div, fieldset, form, iframe, li, noframes, noscript, object, td and th tags.

How to secure jQuery AJAX calls in PHP from hackers?

If you are making jQuery AJAX calls in your PHP website, please ensure that those jQuery AJAX calls are secure from website hackers. Your code should not be vulnerable to hackers. Below are some methods and steps which need to be taken to secure your jQuery AJAX calls to PHP files. I am writing this post because I had written a simple post "How to call PHP function from JavaScript function? Always use AJAX." without mentioning any security code. I got following comment on that post:

"Your code is very vulnerable. You're not filtering the $_POST variable at all. This opens yourself to HTML injection. A hacker could pwn your web site very quickly if you used this code. Careless examples like yours is exactly why so many web sites are hacked."

That's why this is my small attempt to make your jQuery AJAX calls secure. 

1. Use $_SERVER['HTTP_X_REQUESTED_WITH']

This is a basic check to see if the request is an Ajax request or not?

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

2. Use $_SERVER['HTTP_REFERER']

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

But not all browsers set it. So don't properly rely on it but yes, to some extent it can secure your webpage.

Nobody can AJAX your site from other domain, but always can connect and drieclty send http request, for example by cURL.

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

3. Generate Access Tokens

$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable

You can create some token in cookies, that will be also seen from jquery request, but that solution can also be hacked.

4. Always check $_POST variables in your PHP file whether those are set or not? Whether there is valid value in $_POST or not before executing the actual PHP code.

Basic code snippet for securing your jQuery AJAX calls in PHP

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = 
{
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: form_data,
  success: function(response)
  {
    //do further
  }
});

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); 
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') 
{
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) &&    $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else
   {
      header('Location: http://yourdomain.com');
    }
  }
  else 
  {
    header('Location: http://yourdomain.com');
  }
}
else 
{
  header('Location: http://yourdomain.com');
}

How to call PHP function from JavaScript function? Always use AJAX.

Recently, I was developing a web application in PHP. I get into the need of calling my PHP function from my Javascript function. This is the common thing when you are developing a web application in PHP and have to call a PHP code from Javascript to refresh only a certain portion of your web page with server results. Always use AJAX to achieve this functionality. Using AJAX you can call server side code / functions (your PHP code) from client side (Javascript). Below is the PHP and Javascript code snippet to illustrate this concept. 

This is very simple example on how to call server side functions of PHP from client browsers (Javascript)? In following example, I have a PHP file named myscript.php which has function named myfunction(). This function uses two $_POST variables and just echoes them. I have mydiv HTML div anywhere on my webpage which I want to refresh with the result which is returned from my PHP script. In my Javascript code, I am using AJAX to call my PHP script with parameters and POST method. The result which is getting returned, I am showing that in mydiv HTML div. 

Have a look at this very simple PHP AJAX example:

PHP code

<?php

myfunction();

function myfunction()
{
$myvar = $_POST['q']." how are you?";
$myvar2 = $_POST['z'];
echo $myvar."\n".$myvar2;
}
?>

HTML code

<div id="mydiv"></div>

Javascript code

var data =" hello world";
var data2=" hello all";
function run()
{
$.ajax(
{
                   url: 'myscript.php',
                data: {'q': data,'z':data2},
                   type: 'post',
                   success: function(output) 
                {
                          //alert(output);
                          document.getElementById("mydiv").innerHTML += output; //add output to div  
                }
}
          );
}

How to put images in HTML text and password fields?

You can easily place images inside text fields in HTML. To explain this, I am making a registration form in which I have text and password fields like name, email, password and confirm password. I want to put user image inside name text field, email image inside email field and so on. I have kept images(32*32 png icons) of user, email and password in images folder.

HTML file

<form action="register.php" name="register" id="register" method="post">
     
  <input type="text" name="name" id="name" placeholder="Your name" autocomplete="off" tabindex="1" class="txtinput">

  <input type="email" name="email" id="email" placeholder="Your e-mail address" autocomplete="off" tabindex="3" class="txtinput">

  <input type="password" name="password" id="password" placeholder="Your password" autocomplete="off" tabindex="5" class="txtinput">

 <input type="password" name="confirmpassword" id="confirmpassword" placeholder="Confirm password" autocomplete="off" tabindex="6" class="txtinput">

   <input type="submit">     

</form>

CSS file

#register input#name 
{
  background: #fff url('../images/user.png') 5px 4px no-repeat;
}

#register input#email 
{
  background: #fff url('../images/email.png') 5px 4px no-repeat;
}

#register input#password 
{
  background: #fff url('../images/password.png') 5px 4px no-repeat;
}

#register input#confirmpassword 
{
  background: #fff url('../images/password.png') 5px 4px no-repeat;
}

How to make stylish Submit and Reset HTML buttons with CSS3?

Recently, I had to create a registration form which had submit and reset buttons. I wrote some CSS3 code to look submit and reset html buttons stylish. I thought of sharing this code with all you guys so that it might help someone. If you have any better CSS tips to make these submit and reset buttons more stylish, do share it.

My HTML file:

<div id="buttons">
    <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">
    <input type="submit" name="submit" id="submitbtn" class="submitbtn" value="Register">
</div>

My CSS file:

#buttons 
  display: block; padding-top: 10px; 
}

#buttons #resetbtn 
{
  display: block;
  float: left;
  color: #515151;
  text-shadow: -1px 1px 0px #fff;
  margin-right: 20px;
  height: 3em;
  padding: 0 1em;
  outline: 0;
  font-weight: bold;
  font-size: 1.3em;
  white-space: nowrap;
  word-wrap: normal;
  vertical-align: middle;
  cursor: pointer;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
  background-color: #fff;
 background-image: -moz-linear-gradient(top,  rgb(255,255,255) 2%, rgb(240,240,240) 2%, rgb(222,222,222) 100%);
 background-image: -webkit-gradient(linear, left top, left bottom, color-stop(2%,rgb(255,255,255)), color-stop(2%,rgb(240,240,240)), color-stop(100%,rgb(222,222,222)));
  background-image: -webkit-linear-gradient(top,  rgb(255,255,255) 2%,rgb(240,240,240) 2%,rgb(222,222,222) 100%);
  background-image: -o-linear-gradient(top,  rgb(255,255,255) 2%,rgb(240,240,240) 2%,rgb(222,222,222) 100%);    background-image: -ms-linear-gradient(top,  rgb(255,255,255) 2%,rgb(240,240,240) 2%,rgb(222,222,222) 100%);
  background-image: linear-gradient(top,  rgb(255,255,255) 2%,rgb(240,240,240) 2%,rgb(222,222,222) 100%); 
 filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#dedede',GradientType=0 );
  border: 1px solid #969696;
  box-shadow: 0 1px 2px rgba(144, 144, 144, 0.4);
  -moz-box-shadow: 0 1px 2px rgba(144, 144, 144, 0.4);
  -webkit-box-shadow: 0 1px 2px rgba(144, 144, 144, 0.4);
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
}

#buttons #resetbtn:hover 
{
  text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
  color: #818181;
  background-color: #fff;
  background-image: -moz-linear-gradient(top,  rgb(255,255,255) 2%, rgb(244,244,244) 2%, rgb(229,229,229) 100%);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(2%,rgb(255,255,255)), color-stop(2%,rgb(244,244,244)), color-stop(100%,rgb(229,229,229)));
  background-image: -webkit-linear-gradient(top,  rgb(255,255,255) 2%,rgb(244,244,244) 2%,rgb(229,229,229) 100%);background-image: -o-linear-gradient(top,  rgb(255,255,255) 2%,rgb(244,244,244) 2%,rgb(229,229,229) 100%); background-image: -ms-linear-gradient(top,  rgb(255,255,255) 2%,rgb(244,244,244) 2%,rgb(229,229,229) 100%); background-image: linear-gradient(top,  rgb(255,255,255) 2%,rgb(244,244,244) 2%,rgb(229,229,229) 100%); 
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 );
  border-color: #aeaeae;
  box-shadow: inset 0 1px 0 rgba(256,256,256,0.4),0 1px 3px rgba(0,0,0,0.5);
}

#buttons #submitbtn 
{
  display: block;
  float: left;
  height: 3em;
  padding: 0 1em;
  border: 1px solid;
  outline: 0;
  font-weight: bold;
  font-size: 1.3em;
  color:  #fff;
  text-shadow: 0px 1px 0px #222;
  white-space: nowrap;
  word-wrap: normal;
  vertical-align: middle;
  cursor: pointer;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
  border-color: #5e890a #5e890a #000;
  -moz-box-shadow: inset 0 1px 0 rgba(256,256,256, .35);
  -ms-box-shadow: inset 0 1px 0 rgba(256,256,256, .35);
  -webkit-box-shadow: inset 0 1px 0 rgba(256,256,256, .35);
  box-shadow: inset 0 1px 0 rgba(256,256,256, .35);
  background-color: rgb(226,238,175);
  background-image: -moz-linear-gradient(top, rgb(226,238,175) 3%, rgb(188,216,77) 3%, rgb(144,176,38) 100%);
  background-image: -webkit-gradient(linear, left top, left bottom, color-stop(3%,rgb(226,238,175)), color-stop(3%,rgb(188,216,77)), color-stop(100%,rgb(144,176,38))); 
  background-image: -webkit-linear-gradient(top, rgb(226,238,175) 3%,rgb(188,216,77) 3%,rgb(144,176,38) 100%);
  background-image: -o-linear-gradient(top, rgb(226,238,175) 3%,rgb(188,216,77) 3%,rgb(144,176,38) 100%);
  background-image: -ms-linear-gradient(top, rgb(226,238,175) 3%,rgb(188,216,77) 3%,rgb(144,176,38) 100%);
  background-image: linear-gradient(top, rgb(226,238,175) 3%,rgb(188,216,77) 3%,rgb(144,176,38) 100%); 
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e2eeaf', endColorstr='#90b026',GradientType=0 );
}

#buttons #submitbtn:hover, #buttons #submitbtn:active 
{
  border-color: #7c9826 #7c9826 #000;
  color: #fff;
  -moz-box-shadow: inset 0 1px 0 rgba(256,256,256,0.4),0 1px 3px rgba(0,0,0,0.5);
  -ms-box-shadow: inset 0 1px 0 rgba(256,256,256,0.4),0 1px 3px rgba(0,0,0,0.5);
  -webkit-box-shadow: inset 0 1px 0 rgba(256,256,256,0.4),0 1px 3px rgba(0,0,0,0.5);
  box-shadow: inset 0 1px 0 rgba(256,256,256,0.4),0 1px 3px rgba(0,0,0,0.5);
  background: rgb(228,237,189);
  background: -moz-linear-gradient(top, rgb(228,237,189) 2%, rgb(207,219,120) 3%, rgb(149,175,54) 100%); 
  background: -webkit-gradient(linear, left top, left bottom, color-stop(2%,rgb(228,237,189)), color-stop(3%,rgb(207,219,120)), color-stop(100%,rgb(149,175,54))); 
  background: -webkit-linear-gradient(top, rgb(228,237,189) 2%,rgb(207,219,120) 3%,rgb(149,175,54) 100%); 
  background: -o-linear-gradient(top, rgb(228,237,189) 2%,rgb(207,219,120) 3%,rgb(149,175,54) 100%); background: -ms-linear-gradient(top, rgb(228,237,189) 2%,rgb(207,219,120) 3%,rgb(149,175,54) 100%); background: linear-gradient(top, rgb(228,237,189) 2%,rgb(207,219,120) 3%,rgb(149,175,54) 100%); 
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e4edbd', endColorstr='#95af36',GradientType=0 );
}

How to pause javascript setInterval method for sometime and restart again?

I was using javascript setInterval method to display different divs after a regular interval of time. In between, I fell into the requirement of pausing the javascript setInterval method for sometime, do some stuff and restart it again. So, I repeatedly used setInterval and clearInterval to acheive my functionality. 

I have 3 divs: div0 (green), div1 (yellow), div2 (red). All are overlapping each other. I am using setInterval to hide and show div1 and div2 after every second. if index = 4 or 6, I am showing red div else yellow div. 

My requirement is that, When index becomes 8, I want to pause the setInterval for 5 seconds and till then show div0 (green) and afterwards resume the loop of setInterval until clearInterval is called.

Below is the code snippet for pausing and restarting setInterval method which is self explanatory.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sample Application</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    var index=0;    
    var auto_refresh = 0;
    $(document).ready(function(){
    hideDiv();
    auto_refresh = setInterval(function(){myTimer()}, 1000);

    });

    function myTimer() 
    {
            index+=1;

            if(index == 4 || index==6)
            {
              showDiv2();
            }   

            else if (index == 8) 
            {
              clearInterval(auto_refresh);
              showDiv0();
              auto_refresh = setInterval(function(){myTimer()}, 5000);  //Now run after 5 seconds
            }

            else if (index > 12) 
            {
              clearInterval(auto_refresh);
            }       

            else
            {
              showDiv1();
            }

        }

    function hideDiv()
    {
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
    }

    function showDiv0()
    {
      document.getElementById("div0").style.visibility="visible";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
    }

    function showDiv1()
    {
      document.getElementById("div1").style.visibility="visible";
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div2").style.visibility="hidden";
      document.getElementById("div1").innerHTML=index;
    }

    function showDiv2()
    {
      document.getElementById("div2").style.visibility="visible";
      document.getElementById("div0").style.visibility="hidden";
      document.getElementById("div1").style.visibility="hidden";
      document.getElementById("div2").innerHTML=index;
    }

    </script>

  </head>
  <body>
    <div id="container" style="position:relative;">

<div id="div0"     style="background:green;height:200px;width:200px;margin:0;position:absolute">
Relaxing for 5 seconds
</div>
         
<div id="div1" style="background:yellow;height:200px;width:200px;margin:0;position:absolute">
This is div1
</div>

<div id="div2" 
style="background:red;height:200px;width:200px;margin:0;position:absolute">
This is div2</div>
</div>

</body>
</html>

Note: I had discussed this problem on stackoverflow and written the conclusion of the discussion here in this post.

How to show / hide images randomly at regular intervals in javascript by shuffling the array?

I had one requirement in one of my projects that I had an image which I had to show randomly in 4 places (div) in my webpage at regular intervals using javascript. I had asked this problem in stackoverflow. I got good help from a guy named "Hiral" there. With his/her help, I was able to implement this functionality. For implementing my functionality, I am shuffling an array and using javascript setInterval() and clearInterval() methods. Let me explain you my requirement and solution. Maybe you encounter similar requirement in future, then it might be helpful to you!

I have following 4 divs (bulb1, bulb2, bulb3, bulb4) and the image bulb.png in images folder of my project.

<div id="bulb1" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb2" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb3" class="lightbulb"><img src=".\images\bulb.png" /></div>
<div id="bulb4" class="lightbulb"><img src=".\images\bulb.png" /></div>

Initially, I will hide all these divs by calling my following function:

function hideBulbImages()
{
        document.getElementById('bulb1').style.visibility = "hidden";
        document.getElementById('bulb2').style.visibility = "hidden";
        document.getElementById('bulb3').style.visibility = "hidden";
        document.getElementById('bulb4').style.visibility = "hidden";
}

Now lets say I have an html button on the click of which I am calling below function showBulbImages. As I said I have 4 divs (places in html page) where I have to light the bulb randomly, so I am shuffling the array "myArray" in the below function so that array gets randomized by calling the function "shuffleArray". When array gets shuffled or randomized, I use javascript setInterval() method to turn on the visibility of bulbs randomly at regular intervals, 1 second in my case. When setInterval() method runs 4 times, I call clearInterval() to stop the show.

function showBulbImages()
    { 
        var blink_count = 0;
        var myArray = ['1', '2', '3', '4'];
        var randomArray = shuffleArray(myArray)
        var blink_the_bulbs = setInterval(function() {      
            var blinking_bulb = "bulb" + randomArray[blink_count];
            document.getElementById(blinking_bulb).style.visibility = "visible";
            blink_count+=1;
            if (blink_count > 3) 
            {
                 clearInterval(blink_the_bulbs);
            }
        }, 1000);
    }

    function shuffleArray(array) 
    {
        for (var i = array.length - 1; i > 0; i--) 
        {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }

HTML5 Interview Questions and Answers for Web Designers and Developers

Below is the list of HTML5 basic interview questions and answers. These HTML5 interview questions and answers are meant for freshers as well as for experienced web designers and developers. So, If you going for an interview on HTML5,  I suggest you to must give a look at following HTML5 interview questions. These HTML5 interview questions are based on basic introduction to HTML5, why we need HTML5doctype of HTML5, media elements in HTML5, embedding audio and video to HTM5, canvas element in HTML5, types of storage in HTML5 like localStorage and sessionStorage, new Form elements in HTML5, deprecated elements in HTML5, HTML5 APIs etc. So lets have a look on following basic HTML5 interview questions and answers.

1. What's new HTML5 DocType and Charset?

As HTML5 is now not a subset of SGML, its DocType is simplified as follows:
<!doctype html>

And HTML5 uses UTF-8 encoding as follows:
<meta charset="UTF-8">

2. How can we embed Audio in HTML5?

HTML 5 comes with a standard way of embedding audio files. Supported audio formats are MP3, Wav and Ogg.
<audio controls>
<source src="jamshed.mp3" type="audio/mpeg">
Your browser doesn't support audio embedding feature.
</audio>

3. How can we embed Video in HTML5?

Same like audio, HTML 5 defined standard way of embedding video files. Supported video formats are MP4, WebM and Ogg.
<video width="450" height="340" controls>
<source src="jamshed.mp4" type="video/mp4">
Your browser does'nt support video embedding feature.
</video>

4. What are the new media elements in HTML5 other than audio and video?

HTML 5 has strong support for media. Other than audio and video tags, it comes with the following tags:

<embed> acts as a container for external application.
<track> defines text track for media.
<source> is helpful for multiple media sources for audio and video.

5. What is the usage of canvas element in HTML5?

<canvas> is an element in HTML5 which we can use to draw graphics with the help of scripting (which is most probably JavaScript). 

This element behaves like a container for graphics and rest of the things will be done by scripting. We can draw images, graphs and a bit of animations etc. using <canvas> element.
<canvas id="canvas1" width="300" height="100">
</canvas>

6. What are the different types of storage in HTML5?

HTML5 has the capability to store data locally. Previously, it was done with the help of cookies. The exciting thing about this storage is that it's fast as well as secure.

There are two different objects which can be used to store data:

localStorage object stores data for a longer period of time even if the browser is closed.
sessionStorage object stores data for a specific session.

7. What are the new Form Elements introduced in HTML5?

There are a number of new form elements that have been introduced in HTML 5 as follows:

datalist
datetime
output
keygen
date
month
week
time
number
range
email
url

8. What are the deprecated Elements in HTML5 from HTML4?

Elements that are deprecated from HTML 4 to HTML 5 are:

frame
frameset
noframe
applet
big
center
basefront

9. What are the new APIs provided by HTML5 standard?

HTML 5 standard comes with a number of new APIs. Few of them are as follows:

Media API
Text Track API
Application Cache API
User Interaction
Data Transfer API
Command API
Constraint Validation API
History API
and many more....
10. What is the difference between HTML 5 Application Cache and regular HTML Browser Cache?

One of the key features of HTML 5 is "Application Cache" that enables us to make an offline version of a web application. It allows to fetch few or all of website contents such as HTML files, CSS, images, JavaScript, etc. locally. This feature speeds up the site performance. This is achieved with the help of a manifest file defined as follows:
<!doctype html>
<html manifest="example.appcache">
.....
</html>

As compared with traditional browser caching, it's not compulsory for the user to visit website contents to be cached.

11. Can you give an example of Canvas element and how it can be used?

<canvas id=“myCanvas” width=“500″ height=“400″>
</canvas>
<script type=“text/javascript”>
var myCanvas=document.getElementById(“myCanvas”);
var myText=myCanvas.getContext(“2d”);
myText.fillStyle=“#82345c”;
myText.fillRect(0,0,150,75);
</script>

12. What is the purpose of HTML5 versus XHTML?

HTML5 is the next version of HTML 4.01, XHTML 1.0 and DOM Level 2 HTML. It aims to reduce the need for proprietary plug-in-based rich internet application (RIA) technologies such as Adobe Flash, Microsoft Silverlight, Apache Pivot, and Sun JavaFX. Instead of using those plugins, it enables browser to serve elements such as video and audio without any additional requirements on the client machine.
13. What is the difference between HTML and HTML5?

HTML5 is nothing more then upgraded version of HTML where in HTML5 supports the innovative features such as Video, Audio/mp3, date select function , placeholder , Canvas, 2D/3D Graphics, Local SQL Database added so that no need to do external plugin like Flash player or other library elemenents.

14. What are some other advantages of HTML5?

a) Cleaner markup than earlier versions of HTML
b) Additional semantics of new elements like <header>, <nav>, and <time>
c) New form input types and attributes that will (and in Opera’s case, do) take the hassle out of scripting forms.

15. What is the  <!DOCTYPE>? Is it mandatory to use in HTML5?

The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. The <!DOCTYPE> tag does not have an end tag. It is not case sensitive.

The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag.  As In HTML 4.01, all <! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). WHERE AS HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD).

16. What are the New Media Elements in HTML5?

New Media Elements in HTML5 are :
<audio> For multimedia content, sounds, music or other audio streams
<video> For video content, such as a movie clip or other video streams
<source> For media resources for media elements, defined inside video or audio
elements
<embed> For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers

17. What is the major improvement with HTML5 in reference to Flash?

Flash is not supported by major mobile devices such as iPad, iPhone and universal android applications. Those mobile devices have lack of support for installing flash plugins. HTML5 is supported by all the devices, apps and browser including Apple and Android products. Compared to Flash, HTML5 is very secured and protected. That eliminates major concerns that we have seen with Flash.

18. What is the sessionStorage Object in HTML5 ? How you can create and access that?

The HTML5 sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. We can create and access a sessionStorage, created “name” as session

<script type=“text/javascript”>
sessionStorage.name=“mySessionStorage”;
document.write(sessionStorage.name);
</script>

19.  What is the use of localStorage in HTML5?

Before HTML5 LocalStores was done with cookies. Cookies are not very good for large amounts of data, because they are passed on by every request to the server, so it was very slow and in-effective. 

In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website's performance.and The data is stored in different areas for different websites, and a website can only access data stored by itself.

And for creating localstores just need to call localStorage object like below we are storing name and address

<script type="text/javascript">
localStorage.name="myLocalStorage";
document.write(localStorage.name);
</script> 
<script type="text/javascript">
localStorage.address="The Professionals Point.";
document.write(localStorage.address);
</script>

20. How many new Markup Elements you know in HTML5?

Following are the new markup elements introduced in HTML5:

<article> Specifies independent, self-contained content, could be a news-article, blog post, forum post, or other articles which can be distributed independently from the rest of the site.

<aside> For content aside from the content it is placed in. The aside content should be related to the surrounding content

<bdi> For text that should not be bound to the text-direction of its parent elements

<command> A button, or a radiobutton, or a checkbox

<details> For describing details about a document, or parts of a document

<summary> A caption, or summary, inside the details element

<figure> For grouping a section of stand-alone content, could be a video

<figcaption> The caption of the figure section

<footer> For a footer of a document or section, could include the name of the author, the date of the document, contact information, or copyright information

<header> For an introduction of a document or section, could include navigation

<hgroup> For a section of headings, using <h1> to <h6>, where the largest is the main heading of the section, and the others are sub-headings

<mark> For text that should be highlighted

<meter> For a measurement, used only if the maximum and minimum values are known

<nav> For a section of navigation

<progress> The state of a work in progress

<ruby> For ruby annotation (Chinese notes or characters)

<rt> For explanation of the ruby annotation

<rp> What to show browsers that do not support the ruby element

<section> For a section in a document. Such as chapters, headers, footers, or any other sections of the document

<time> For defining a time or a date, or both

<wbr> Word break. For defining a line-break opportunity.

21.  Do you know New Input Type Attribute in HTML5?

Yes, we can use below new input type Attribute in HTML5:

tel The input is of type telephone number
search The input field is a search field
url a URL
email One or more email addresses
datetime A date and/or time
date A date
month A month
week A week
time The input value is of type time
datetime-local A local date/time
number A number
range A number in a given range
color A hexadecimal color, like #82345c
placeholder Specifies a short hint that describes the expected value of an input field

22. What does a <hgroup> tag do?

The <hgroup> tag is used to group heading elements. The <hgroup> element is used to group a set of <h1> to <h6> elements.

<hgroup>
<h1>Hello</h1>
<h2>How r u?</h2>
</hgroup>
23. Which video formats are used for the video element?
Internet Explorer 9+: MP4
Chrome 6+: MP4, WebM, Ogg
Firefox 3.6+ : WebM, Ogg
Safari 5+ : MP4,
Opera 10.6+ : WebM,Ogg

Share this post

About Naveed Iqbal

Nulla sagittis convallis arcu. Sed sed nunc. Curabitur consequat. Quisque metus enim venenatis fermentum mollis. Duis vulputate elit in elit. Follow him on Google+.

0 comments:

About-Privacy Policy-Contact us
Copyright © 2013 fulluptodate. Blogger Template by Bloggertheme9
Proudly Powered by Blogger.
back to top