HTML 5 TutorialsWEB STORAGE Part - 2

WEB STORAGE Part – 2

Today we will learn how to use web storage practically. For this we will use our “Blue Developer Directory” website project. Let us get a short idea of the task that we are going to perform.
We are going to have a small form at the left side of “homepage.html” page of “Blue Developer Directory” website project. This form will take name and email as an input. We are going to store the name and email-id entered by the user using localStorage(). This stored name and email-id will be retrieved and shown on the webpage. This is just an overview of the task. Now let’s start the task and understand it more deeply in a step by step manner.

  1. So first, create a new folder on the desktop with name webstorage.
  2. Copy all the content from the “Blue Developer Directory” project previous folder and paste it in the newly created webstorage folder.
  3. Now open the “homepage.html” page with notepad++ and then run it. The output will be seen as shown below:
  4. homepage_initial_output
    fig 1

  5. Now next step is that we want to create a small “NewsLetter” form at the left side of homepage, below the vertical leftmenu. So write the following code below the un-ordered list of leftmenu, i.e. between
    </ul> and </nav>

    tags of leftmenu, so that the form appears below leftmenu.

  6. <div>
      <br><br>
      <h3>NewsLetter</h3>
      <p>Please enter youremail address</p>
      <form id="news" onsubmit="initStorage()">
        Name: <input type="text" id="name" name="name">
        Email: <input type="email" id="email" and name="name">
        <input type="submit" value="Send">
      </form>
    </div>
    
    • This code will draw a small form containing input elements for taking name and email-id as input as shown below.

    Newletter_form_without_styling
    fig 2

  7. We need to change the black fore-colour to white and provide some spacing between the elements. For this we have to open “style.css“ file and do some styling for the “id“ given to the form i.e. “news”.
    • We have the aside tag which is generally used to reference the side bars, so we will style the aside tag. So write the following styling code above the “menu” styling or anywhere you like.
    • aside
      {
      	color:#fff;
      }
      
    • The text in black colour will get white colour. The output is shown below.
    • NewsLetter_styled_with_white_colour
      fig 3

    • But we don’t have any spacing between the input elements. To provide spacing between the elements we will again apply styling.
    • Write the following code below the aside tag styling in “style.css”.
    • aside input
      {	
      	margin-bottom:10px;
      }
      
    • This above written code will provide the bottom margin space of 10 pixels for all the input elements present inside the aside tag. The word “input” indicates all the input types.
    • The page after this code is shown below:
    • spacing_provided_between_input_elements
      fig 4

    • In the above output, 10 pixel bottom margin is left for every input element. If we did not want the space to be left below the email input element, i.e. if we wanted to apply the styling to only a specific input element, we can do the same by specifying the input type.
    • For an example, if I want the space to be left only below the “text“ input type. I will specify it with the following code.
    • aside input[type="text"]
      {
      	margin-bottom:10px;
      }
      
    • Output of the code is shown below:
    • styling_specific_input_element
      fig 5

    • Just observe figures 4 and 5 with respect to submit button. You will notice that, there is some space left above submit button in fig 4, but no space is left above submit button in fig 5. This is because in fig 4 styling is applied to all input elements, but in fig 5 styling is applied only to the “text” input element.
    • If we want the styling to be applied to “email” input field in fig 5 , we should modify the above code as follows:
    • aside input[type="text"],aside input[type="email"]
      {
      	margin-bottom:10px;
      }
      
    • By adding the “email” input type to the code, the styling will be applied to email input field also and we will get the same output as figure 4.
    • Note that, you can use any attribute, not just “type”. In this case “NewsLetter” form has a “name” attribute for “text” and “email” input field. You can use “name” attribute also.

    Here we finished designing our form. Now we want to have some processing. After entering his/her name and email-id user will click on “Send” button. When he clicks on the button a message “Welcome Back xxx” (xxx is user’s name) should appear at the right top corner of the horizontal menu and “Subscribed email [email protected]” should appear in place of “Please enter your email address”.

  8. All the above described working will be achieved using webstorage, by storing the values of name and email in the localStorage or sessionStorage. We will have to take help of javascript code for the following.
    • So let’s write the following code in
      <script>-----</script>

      tag inside the head section.

    • <script type="text/javascript">
        function initStorage()
        {
          function saveName()
          {
            var name=document.getElementById('name');
            localStorage.setItem('name',name.value);
            alert(localStorage.getItem('name'));
          }
          function saveEmail()
          {
            var email=document.getElementById('email');
            localStorage.setItem('email',email.value);
            alert(localStorage.getItem('email'));
          }
          saveName();
          saveEmail();
        }
      </script>
      
    • The above code is a javascript code, hence the type=”text/javascript” is specified in the script tag.
    • It contains a function initStorage() which indicates the storage initialization. This function is called at the onsubmit event of the NewsLetter form.
    • This function consists of 2 more functions inside it. saveName() and saveEmail().
    • saveName() function is used to store the name entered by user in the “text” input element in the localStorage.
    • The logic used is that, the “id” of the input element is retrieved and stored in a variable by the following statement:
    • var name=document.getElementById('name');
    • The “id” gets stored in the variable “name”. Now this key with its value is stored in the localStorage using setItem() method .The statement shows the operation:
    • localStorage.setItem('name',name.value);
    • Here, first paramenter of setItem() method, name is the key and name.value will retrieve the value in the particular input element whose “id” is stored in the variable “name”.
    • Then just to check if the value is stored, an alert message is shown by the following statement.
    • alert(localStorage.getItem('name'));
    • Here, getItem() method is used to retrieve the value of the particular key.
    • The saveEmail() function contains the same logic for storing email-id.
    • These functions cannot run without calling, so they are called in function initStorage().
    • After opening the page in a browser, if you enter the name and email-id in the NewsLetter input elements, and click on “Send” button, the initStorage() function will be called and we will see alerts containing name and email-id. Alert for name is shown in the figure below:
    • alert_for_stored_name
      fig 6

    • Similarly, when you click on “OK” button of the alert box, you will get the alert showing email id.
    • Now after receiving alerts, we now know that values are stored in localStorage successfully. So we can comment the alert message statements.
  9. Now our next task is to display the stored “name” on the horizontal menubar at top right corner.
    • For that let’s write another function displayName() in the script tag below initStorage() function.
    • function displayName()
      {
        if(localStorage.getItem('name')!=null)
        {
          document.write('Welcome Back, ' + localStorage.getItem('name'));
        }
      }
      
    • In this function, we need to check first if the localStorage is empty or not and display the welcome message only if it is not empty/null.
    • So the condition for null is checked in “if” block.
    • If localStorage is not null, then the “Welcome Back, xxx” message (xxx indicates the name entered by the user, stored in localStorage) is displayed using the document.write() method of javascript where, “Welcome Back, ” is a string and the localStorage.getItem(‘name’) gets the name stored with the key name in localStorage. These two things are concatenated with “+” (concatenation operator).
    • But just writing this function won’t do, it should be called where it has to be processed.
    • We have to display it on the horizontal menu. So call this function below the un-ordered list of horizontal menu, i.e. between
      </ul> and </nav>

      tags of menu as shown below.

    • <div id="displayname">
        <script>
          displayName();
        </script>
      </div>
      
    • This function calling is not an html statement, it is a javascript statement, hence written in
      <script>---</script>

      tag.

    • And a div tag with “id” as “displayname” is defined to style the welcome message, to give it a proper appearance.
    • The styling to the “id”, “displayname” is done in “style.css”. Write the following styling code below aside tag styling.
    • #displayname
      {
      	color:#fff;
      	float:right;
      	font-weight:bold;
      	font-size:14px;
      	padding:30px ;
      }
      
    • Since displayname is an id it is preceeded by an hash symbol(#).
    • The welcome statement is applied padding of 30 pixels to all sides with bold font. Font size is 14 pixels and the fore-color is white. It is shifted to right side using float:right.
    • The output is shown below:
    • displayed_welcome_message
      fig 7

  10. As the name entered in the NewsLetter is displayed at the top right corner, we need to display the email-id if entered as the Subscribed Email in the place where the statement “Please enter your email address” is displayed.
    • For this we will write a javascript function showText() below the function displayName() inside tag and give it a call in the body section.
    • The code is given below:
    • function showText()
      {
        if(localStorage.getItem('email')==null)
        {
      	document.write('<p>Please enter your email address</p>');
        }
        else
        {
      	document.write('<p><strong>Subscribed Email : </strong>' + localStorage.getItem('email') + '</p>');
        }
      }
      
    • Here, the logic of showText() function is shown. The purpose of the logic is that if the user had entered the email-id and had clicked on the “Send” button, his email-id will be shown as a Subscribed Email replacing the paragraph Please enter your email address whenever he opens or refreshes the browser, because it has been stored in the localStorage. But if the email has not been saved in localStorage, the Please enter your email address paragraph will only be shown instead of Subscribed Email.
    • So, if—else conditional statements are used in the above function.
    • It is checked in if statement whether the localStorage is null. If it is null then the paragraph Please enter your email address is displayed below the NewsLetter heading of Newsletter form.
    • In the else part, I mean if the localStorage is not null then the text Subscribed Email concatenated with the email-id of user stored in localStorage is displayed.
    • The output is shown below:
    • displaying_saved_subscribed_email
      fig 8

    You can use sessionStorage also, but it will store things till you close the browser. Once you close the browser, the stored data will be lost. In contradiction if you use localStorage, things will be stored even after you close the browser. Try closing the browser and then again opening it, the data you had stored will be displayed with the page load.

  11. If you have entered name and email in the NewsLetter form and you want to clear it. You will just reload the page. But instead of that we will have some clearing mechanism on the NewsLetter form.
    • For this we will create a hyperlink named Clear, which will not take us to any other page but will clear the name and email input elements. This hyperlink is to be placed besides Send button of NewLetter form, so write the following code in NewsLetter form below the input tag of submit button “Send”.
    • <a href="#" onclick="clearAll()">Clear</a>
    • Here, the “Clear” hyperlink is created using anchor tag. The value of href attribute i.e. “#” will not allow to go to new page.
    • This link Clear defines an event onclick and calls a function clearAll() when the user clicks on the Clear link.
    • This function is not inbuilt, we have to write it yet.
  12. Let’s write the logic for function clearAll() inside the
    <script>----</script>

    tag below showText() function.

  13. function clearAll()
    {
      localStorage.clear();
      window.location.reload();
    }
    
    • When you click on the Clear link, this clearAll() function will be called.
    • I request you to do one thing to understand this code more precisely. Just comment the statement window.location.reload(); for some time.
    • Now only one active statement is present in your function i.e. localStorage.clear(); Its purpose is to clear all the data from localStorage. clear() is an inbuilt function used to clear the localStorage or sessionStorage.
    • We will first see the output after execution of the function clearAll() without window.location.reload(); statement.
    • output_of_clearAll_without_reload_code
      fig 9

    • After observing the output in figure 9 we come to the point that if localStorage.clear(); statement clears all the data from localStorage, then why is it still displayed on the webpage.
    • This is just because the page is not refreshed.
    • Now it’s time to un-comment the statement window.location.reload(); This statement will reload the page in the browser thus refreshing it.
    • Now again repeat the process, I mean enter your name and email-id and click on Send button, this data will be displayed on the webpage. Now click on Clear link, you will see that the data displayed on the webpage has been vanished.
    • This indicates that the data is cleared from the localStorage and then the page is reloaded to show the updated page.

    Here, in this tutorial we have seen the actual processing of webstorage as to how is the data stored, retrieved and used.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -