Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, 11 April 2014

How to use Javascript localStorage to retain values of HTML input elements on Page Refresh?

How to use Javascript localStorage to retain values of HTML input elements on Page Refresh?

localStorage in Javascript is used to retain the values of the HTML input elements on the page refresh. setItem() and getItem() methods are used to set and get the data from the localStorage. clear() method is used to clear the data from the localStorage.

Suppose I have following 2 textboxes and buttons in my HTML page. 

<input type="text" id="text1" value="" />
<button type="button" id="myButton1" onclick="myButtonClicked('text1')">Click Me</button>

<input type="text" id="text2" value="" />
<button type="button" id="myButton2" onclick="myButtonClicked('text2')">Click Me</button>

I fill some data in each textbox. Now when I refresh the page, the data is lost. I want to retain that data on the page refresh. I will use localStorage for this purpose. 

//Store values on button click
function myButtonClicked(id)
{
var aLocalStorage = [];
if(localStorage.getItem('myLocalStorage') != null)
{
aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));
//get stored item from localStorage by json parsing
}
    aLocalStorage.push(id);
    aLocalStorage.push(document.getElementById(id).value);
    localStorage.setItem('myLocalStorage', JSON.stringify(aLocalStorage));
    //stored the entered element id and value in localStorage by doing stringify
}

Now when the page is refresh, call the following function on $(Idocument).ready event like this

$(document).ready(function()
{
retainValues();
});

function retainValues()
{
if(localStorage.getItem('myLocalStorage') != null)
{
var aLocalStorage =[];
aLocalStorage = JSON.parse(localStorage.getItem('myLocalStorage'));

var i = 0;
while (i < aLocalStorage.length)
{   
if (document.getElementById(aLocalStorage[i]) != null)
{
document.getElementById(aLocalStorage[i]).value = shoppingCartList[i+1];
}
i = i + 2;
}
}
}

How to call both Javascript function with PHP file on the click on HTML link?

How to call both Javascript function with PHP file on the click on HTML link?

Recently, I was trying to implement logout functionality while working with PHP website. I had put logout logic in logout.php file and I was calling that file on the click of logout link like following:

<a href="logout.php">Logout</a>

This was working fine. But later on I realised that I also have to clear localstorage maintained by using Javascript before logging out the user. So, I had to call the javascript function that clears the localstorage before calling the logout.php file. 

Javascript function for clearing the localstorage:

function ClearMyLocalStorage()
{
localStorage.clear();
}

I investigated two approaches to accomplish my task.

Approach 1:

<a href="logout.php" onclick="ClearMyLocalStorage()">

Approach 2:

<a href="javascript:;" onclick="ClearMyLocalStorage();">Logout</a>

And in your function you have to write like

function ClearMyLocalStorage()
{
    localStorage.clear();
    window.location.href = 'logout.php';
}

How to change InnerHTML of all the HTML Buttons in one go using jQuery?

How to change InnerHTML of all the HTML Buttons in one go using jQuery?

Suppose, I have 5 buttons on my page. How can I change the innerHTML of the buttons in one go using jQuery? I want that buttons having text "Clicked" should get changed to "Click me" when Change InnerHTML button is clicked. I will use jQuery to solve this problem. Refer the following example.

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function ChangeInnerHTML()
{
//Iterate all the buttons with innerHTML = "Clicked" in the DOM and set them to "Click me".
}
</script>
</head>
<body>
<button type="button" id="myButton1">Click me</button>
<button type="button" id="myButton2">Clicked</button>
<button type="button" id="myButton3">Click me</button>
<button type="button" id="myButton4">Clicked</button>
<button type="button" id="myButton5">Click me</button>

<button type="button" id="btnChangeInnerHTML"      onclick="ChangeInnerHTML()">Change InnerHTML</button>

</body>
 </html>

 There are many approaches for doing this task.

Approach 1:

 function ChangeInnerHTML() {
    $('button').each(function() {
        if ($.trim($(this).html()) == "Clicked") 
            $(this).html('Click me');
    });
}

Approach 2:

Use Attribute selector in jquery.

function ChangeInnerHTML() 
{
$("[id^=myButton]:contains('Clicked')").click(function() {
$(this).text("Click Me");

});
}

Approach 3:

function ChangeInnerHTML()
{
document.body.innerHTML=
document.body.innerHTML.replace(/Clicked/g,'Click me');
}

Approach 4:

Without jQuery

function ChangeInnerHTML() 
{
    var btns = document.querySelectorAll('button[id^=myButton]');
    for (var i = 0; i < btns.length; i++) {
        if (btns[i].innerHTML.trim() == 'Clicked') {
            btns[i].innerHTML = 'Click Me'
        }
    }
}

Approach 5:

This will change the innerHTML of all the buttons.

function ChangeInnerHTML()
{
    $("button[id*=myButton]").html("Click me");
}

Friday, 4 April 2014

How to return value from child window to parent window using window.open in Javascript?

How to return value from child window to parent window using window.open in Javascript?

It is very easy to return a value from a child window to parent window which has been opened from parent window using window.open method in Javascript. In many scenarios, it is possible to do some calculations on the child window and parent window need the result of that calculations to perform some task. So, let's try to resolve this problem.

In Parent Window

I have following Javascript function which will open a child window named childWin. I also have a function which will catch the value returned by the child window.

function openChildWin() 
{   
    var childWin = window.open("childWin.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no); 
}

function setValue(val1) 
{
   //you can use the value here which has been returned by your child window
}

ChildWin.html page

Following is my childWin HTML page. There is a button on this HTML page which when clicked will return a value to the parent window which has setValue function. Basically, child window is accessing parent's setValue function here. After this, child window is closed.

<!DOCTYPE html>
<html lang="en">
  <head>

<script type="text/javascript">

function OKClicked()
{
window.opener.setValue('Hello');; //I want to return true here
window.close(); //Close this child window  
}

</script>

  </head>
  <body>
<button type="button" id="OKButton" onclick="OKClicked()">Click ME</button>
  </body>
 </html>

Friday, 20 December 2013

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

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
};

Wednesday, 27 November 2013

HTML5 MENU Tag Redefined

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.

Saturday, 23 November 2013

How to secure jQuery AJAX calls in PHP from hackers?

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');
}

Wednesday, 20 November 2013

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

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  
                }
}
          );
}

Thursday, 24 October 2013

How to put images in HTML text and password fields?

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?

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 );
}

Monday, 21 October 2013

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

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.