javascript – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Working with JSON in MVC /working-with-json-in-mvc/ /working-with-json-in-mvc/#respond Fri, 01 Apr 2016 19:05:10 +0000 /?p=547 Introduction

JSON Java Script Object Notation , a very familiar and commonly used concept. It is a data interchange medium and is very lightweight. It is one kind of a syntax for storing and passing data. Since it is Java script object notation, it uses the java script style of syntax, but actually is text only. It also is language independent. The format would look like below:

{"Books":[
    {"name":"Asp.Net Mvc", "code":"111"},
    {"name":"Angular Js", "code":"112"},
    {"name":"Javascript", "code":"113"},
    {"name":"CLR", "code":"114"}
]}

Now this, JSON object can be created and used to POST or GET in MVC application. Usually, when we do an ajax call, we get the HTML fragments and send them to the browser or append to any DOM elements. That is acceptable, but sending HTML elements with data is not advisable, so would not that be great to send data in a specific format and the browser assigns the data into the HTML. Here, JSON comes in handy. Lets see how. I will explain in simple terms and snippets for better understanding as this topic is not complex at all.

Peek into Snippets!!

I will proceed with an anticipation that readers are aware of MVC (Model, View & Controller), as I will not be sharing the steps to create an MVC project. So, Lets start.
When we create a controller in an MVC project, we know the default type added is ActionResult, which is generic to other types of method types pre-defined like: ViewResult, JsonResult, etc.. Thus, for returning a JSON data, we can use either ActionResult or JsonResult,but preferably use JsonResult as we already know the type, the method will return. JsonResult, is actually a special ActionResult, which suggests the ViewEngine that an object of JSON type will be returned rather than normal HTML.
Lets see the snippet and then try and understand.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.MVC;
using DemoJsonTest.Models;

namespace DemoJsonTest.Controllers {
    public class EmployeeController : Controller {
        private Employee[] employeeData = {
            new Employee {Name:"Suraj Sahoo",EmpCode:"EMP042"},
            new Employee {Name:"Suraj Sharma",EmpCode:"EMP044"},
            new Employee {Name:"Suraj Ray",EmpCode:"EMP041"}
        };

    public ActionResult Index() {
        return View();
    }
   
    public JsonResult GetEmployeeDataJson(string empCode) {
        var employee = employeeData.Where(emp => emp.EmpCode == empCode).SingleOrDefault();
        return Json(employee, JsonRequestBehaviour.AllowGet);
    }

Thus,in the above code, we have shown a normal controller, in whose constructor we have explicitly initialized a model named Employee with few dummy data. Then the main part is the JsonReult method using which, we are filtering the data based on the parameter passed, here EmpCode and then returning the Json object. Mark here, we have used JsonRequestBehaviour.AllowGet. Now whats this. This has an interesting concept behind it. Usually, the browsers to avoid malicious sites trying to intercept JSON data returned, in response to a GET request, it does not respond to GET requests by default.

System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

The above is a part of the error thrown when we miss AllowGet. That is self explanatory actually. πŸ˜›
We usually us ajax options, i.e. success method to process the JSON data received from the GET request and append or set to the HTML DOM elements.

<script type="text/javascript">
$.ajax({
    url: "GET REQUEST URL",
    type:"GET",
    success: function(empData) {
            var trgt = $("#tblEmployee");
            target.append("<tr><td>" + empData.Name + "</td><td>" + empData.EmpCode + "</td></tr>");
        },
    error: function() {
      //Do something..
        }

});
// ]]></script>

Thus, in the above snippet, we are fetching the data in JSON format from the GET response and binding to the table html dom.
A point to note here is that, when we assign/cast (actually) a model into JSON object and we explicitly specify few properties of the model and miss out on others, MVC framework is clever enough to first convert the model with each property into JSON and then assign default values to those properties which we have missed. Lets see an example of conversion:

{ "EmployeeId":0, "Name":"Suraj Sahoo", "EmpCode":"042",
     "IsActiveEmployee": false, "DepartmentId": null }

Mark here,that we have only specified the values of Name and the EmpCode, all other values assigned after JSON conversion by the MVC smart framework.

Conclusion

We saw and discussed a very simple and interesting topic regarding the JSON in MVC and how smartly MVC handles the conversion. This helps when we use API and then return JSON,XML to interchange and expose our data. JSON is actually an alternative to XML form of data exchange. For angular JS now a dayswhich is in demand,we use the API controller, return JSON data and take the advantage of Angular two-way binding.
I hope this helps the beginners out there learning MVC. This is a part of it. Enjoy coding. Open to suggestions. Don’t miss to add your feedback. πŸ™‚

]]>
/working-with-json-in-mvc/feed/ 0
Hands on Angular Js-III /hands-on-angular-js-iii/ /hands-on-angular-js-iii/#respond Fri, 25 Mar 2016 09:33:51 +0000 /?p=482 Introduction

Hello folks!! Lets continue our journey of learning Angular JS. We have seen & discussed few topics already!

In this article we will discuss few concepts that are very essential to build an MVC project with Angular.
thinkzooLets see the topics we will be covering in thisΒ article:

  • Angular Model
  • Angular Scopes
  • Angular Services
  • Angular Http
  • Angular Dependency Injection

Angular Model

This as the name suggests binds the values to the model associated to an element. This shows a two-way binding, i.e. when the value suppose in the textbox changes, the value for the model also binds and changes. The attribute used is ng-model, the code would be like:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div>Name : <input type="text" />
<h1>Welcome {{name}}</h1>
</div>

This will update the value of text entered inside the text box and gets displayed in real time.
1
Interesting fact about the ng-model directive is that, the directive watches the model by reference not by value. It also provides validation to the particular field.

Angular Scopes

Angular scopes are the execution-context generated during the creation of a controller. We pass the scope object to the controller function. The scope is generally denoted as $scope. This is actually an object to which we add the properties to be accessed in the HTML page using the controller reference.
As the angular doc rightly says, it is actually the glue between the controller and the view. It comes with two referring API i.e. $watch (used to observe the model mutations) and $apply (used to propagate the changes done to the scope object property) Lets have a glance at the snippet:

angular.module('scopeTest', []).controller('TestController', function($scope) {
  $scope.username = Suraj;
 });

This is how the scope object is passed and initialized and assigned properties to be used inside the view.
Interesting Facts:
Controller function in Angular is a constructor function. Now what is a constructor function?
A constructor function in simple terms is when the new keyword is used before a function.

var constructorFunction = new Funciton(Parameters..);

Thus everytime a controller is instantiated it gets associated with a new Scope.

Angular Services

There are many in-built services provided by the Angular and also we can explicitly create our own services to have a loose coupling while using the Http Get Post services. These are actually singleton functions that are required to perform certain specified tasks. What singleton means is restricting the instantiation to a single object only.
As in MVC we follow Separation of concern, here also these services can be used to follow the loose coupling and binding.
2
As we can see here the reuse of the services can also be followed here. This is done using the injection of dependency into the controller function. We will look into the dependency in the next points.
Lets see how we declare a service in Angular.

var module = angular.module('TestApp', []); 
module.service('TestService', function(){
    this.users = ['Suraj', 'CsharpCorner', 'Angular'];
});

Here comes another concept known as Factory, which also behaves as a service function only.

var module = angular.module('TestApp', []); 
module.factory('TestFactory', function(){     
    var testFactory = {};     
    testFactory.users = ['Suraj', 'CsharpCorner', 'Angular'];
    return testFactory; 
});

The behavior is the same for both service and factory, but the difference is interesting. For the difference, take a closer look at the snippets mentioned above. In the first snippet where we have declared the service and we have added the ‘users’ to the reference of the service i.e. this keyword. Whereas, in the .factory declaration, we have used the testFactory object and assigned property users to it. While using the Services in the injection, we will have the object instance of the service becomes the reference to the methods and can be used in the injection for other controllers or services, while in case of factory, when that is injected, the value is directly provided which is returned by the function within.
The above discussed are explicit or user-defined services, now lets see the in-built services provided by the Angular. (Some of them)

  • $http:- This is the Http server requesting service, which is one of the most commonly used and important service.
    var app = angular.module('TestApp', []);
    app.controller('TestCtrl', function($scope, $http) {
        $http.get("url").then(function (response) {
            $scope.testData= response.data;
        });
    });

    As we see in the above snippet, the $http service used to make a get request to the URL specified and then the data retrieved is assigned to the scope. As we see the $http is passed into the controller function as an argument. It is recommended to use the $http, server request inside the service as we are in a way interacting with the data. Then the service is injected into the Controller.
  • $interval:- This as the name suggests, is an angular type for window.setInterval
    var app = angular.module('TestApp', []);
    app.controller('TestCtrl', function($scope, $interval) {
        $scope.theTime = new Date().toLocaleTimeString();
        $interval(function () {
            $scope.theTime = new Date().toLocaleTimeString();
        }, 1000);
    }); //reference for use from https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_interval
  • $location:- Same as above, angular version of window.location.
  • $timeOut:- Same as above, angular version of window.setTimeOut.

Dependency Injection

This is an interesting and most debated topic and angular provides this out of the box concept.
3Β Out of the box.. πŸ˜€
Dependency is required when we are looking for the loosely coupled codes, i.e. without directly exposing our services. The separation of concern is the major concern when DI comes into picture. Once our service is ready, we can inject to any other service or controller in Angular. The best example would be a Bakery shop. πŸ˜€
Lets chalk out the plan with a simple snippet:

var app = angular.module('BakeryApp', []);
 
app.service('BakeryService', function() {
    //Declare or pass the prices as arg 
    this.Pizza = function(quantity) { return quantity * pizzaPrice };     
    this.Pastries =function(quantity) { return quantity * pastriesPrice };     
    this.Cakes= function(quantity) { return quantity * cakePrice};
});

//Injected Bakery Service to the 'BakeryCalculateService'
app.service('BakeryCalculateService', function(BakeryService){     
    this.PizzaPrice = function(qty) { return BakeryService.Pizza(qty); };
    this.CakePrice= function(qty) { return BakeryService.Cakes(qty); };
 
});

//Injected BakeryCalculateService.
app.controller('BakeryPriceController', function($scope, BakeryCalculateService) { 
    $scope.CalcPizzaRate= function() {
        $scope.PizzaRate = BakeryCalculateService.PizzaPrice ($scope.quantity);
    } 
    $scope.CalcCakeRate= function() {
        $scope.answer = BakeryCalculateService.CakePrice($scope.quantity);
    }
});

We can very well in the above example see the Dependency Injection and the separation of the main service, the layering that is set between the controller and the actual operations. This is very handy during maintenance as well. This is by law which every developer should abide by πŸ˜›

Do’s & Dont’s

Another interesting fact when we use the injection is the minification breakage. The angular code breaks when the injection is not done properly when the script files are usually bundled and minified.
The above Dependency Injection snippet we discussed, will break when the script is minified, bundled & deployed. The reason being, when minification takes place, it re-frames the variable names as ‘a’,’b’,’c’.., thus the parameters injected as $scope,$http will be now treated as a, b. Thus this will break as there is no meaning injecting a b, may it be a controller or a service.
To avoid that, we usually modify the snippet and use the Angular attribute $inject, wherever Dependency is injected.

var testController= function(myCtrlScope, $http) {
  //We included $scope and the $http service into our controller.
  }
testController.$inject = ['$scope', '$http']

Since we are using $inject attribute on our controller,it would not be an issue using any name of the parameters to it.

Conclusion

Thus, we have discussed few interesting concepts this time and work around with live snippets. Still we have not discussed the integration of angular with an MVC app using API. We will discuss in the upcoming articles of the series, before that we will be clear on the basic stuffs that needs to be covered. πŸ™‚
I hope this article helps. I am always open for corrections and suggestions.
Lets learn and share together.

]]>
/hands-on-angular-js-iii/feed/ 0
Hands on Angular Js – II /hands-on-angular-js-ii/ /hands-on-angular-js-ii/#respond Sun, 10 Jan 2016 17:51:29 +0000 /?p=462 Introduction

AngLogo
As we discuss in the previous part of Hands on Agular Js-I about the basic and the architecture of the Angular Js and few directives. Here in this part we will check out the other important directives and how Angular interaction with Controller and model is being done on the go. The directives we will discuss in this part of series are very important in order to start and feel the magic of Angular. Here, actually, we get into the depth and controls of Angular. Let’s watch out. πŸ™‚

Angular directives

Here we start with the other important directives that would come handy while working on the Angular.

ng-module

Angular modules are the most important directive, they define an angular application. They are the parent set for the other directives or functions of the application, like controllers. Controllers are always contained withing the modules, along with other dependencies. This is the modular approach in Angular. Creating modules for separate section segregates it and create partition/module wise applications.
The modules are defined syntactically as below:

var app = angular.module("app-Services", []);

As per the above snippet, we have created an angular module and assigned it to the variable named app. The module name is app-Services. The module is actually defined in the document function of a separate Module script file and reference added to the file wherever required. The definition provided by the Angular Doc is that Module is required to configure the $injector and it contains the services, directives, controllers and other dependencies.
$injectors are the service used to retrieve the pre-defined object instances, invoke methods and load the required modules.

ng-controller

This is another set of directives that defines the controller of the application, which controls the data of the application. They are simple objects defined under the scope of the module. There can be any number of controllers for a specific module. Controllers are defined syntactically as:

var app = angular.module('app-Services', []);
app.controller('myFirstController', function($scope) {
    $scope.firstName = "Suraj";
    $scope.lastName = "Sahoo";
});

The above snippet is a simple controller defined under the module app-Services. The name of the controller is myFirstController and under its scope, two members are initialized, that is firstName & lastName. Thus, when an object of controller is created in the html, which we will see below:

<html>
<body>
<div ng-app="app-Services" ng-controller="myFistController as ctrlFirst">
<span>{{ctrlFirst.firstName}} {{ctrlFirst.lastName}}</span>
</div>
</body>
</html>

Thus, as we see above, the html tag div has the scope for the Module we defined above and the controller defined for the module with the members firstName & lastName. When the controller is instantiated inside the scopr of the div and Module, we have th right to access the data defined inside the controller function. $scope defined within the controller function is is the context via which the model execution is implemented inside the controller. It actually acts as a watch on the model values while binding to the DOM element in the HTML. The $scope can also be used using the this object. The controller also accepts the $http to execute the http services in order to call the api’s to get post and delete any data through the services. Lets see how the controller function can be separated from the declaration and defined as a function.

var app = angular.module('app-Services', []);
app.controller('myFirstController', myFirstController);
function myFirstController($http, $scope) {
    $scope.firstProperty = 'XYZ';
    $http.get('your url').then(function (){ 
                          //do whatever..
                  }).catch(function (){
                         //do whatever..
              }).finally(function (){
                       //do whatever..
          });
}
});

Now the above, $http is the http module which is used to call the get and post methods or to interact with the server to fetch the records. Call the url, like in ajax we have success and error methods, here we have, then() block, which after fetching successful response, has the logic what to do next. Actually, the $http returns a promise, so we catch that in the then block and attach the response to the scope. The different $hhtp methods are:

  • $http.get:- To retrieve information from server for a url requested by the user
  • $http.head:- Transfers only the header and the status line only, but is same as GET
  • $http.post:- As self explanatory it is, it is used to send the information entered by user to the server.
  • $http.put:- This is same as the POSt but is used to create the current reprsentation of the target resource or overwrite it for the same URL
  • $http.delete:- This ensures that the current resource for the requested URL is deleted by the server.

The catch finally is same as the try.. catch.. blocks, where inside the catch we can also have the ‘then’ block in order to perform tasks after catch and similarly the ‘finally’ block to ensure what finally the code block will execute.

Filters in Angular JS

These are very interesting features provided by the Angular, which can be frequently used and with ease. We will discuss below the pre-defined filters provided by the framework. We will see the use syntactically after the line by line explanation.

  • currency:- This is used as the name suggests, convert a simple number into the format of a currency.
  • date:- This is used to format dates in different formats.
  • filter:- An interesting filter which actually filters few data from a set of result set data.
  • json:- formats an normal object into JSON format
  • limitTo:- limits an set of array to specified number of elements or objects.
  • lowercase:- converts/formats an string to lower case character.
  • number:- formats a simple number into a string.
  • orderby:- Orders an array based on an expression.
  • uppercase:- Formats the string into a upper case character.

Lets see the work around using the snippets:

var app = angular.module('app-Services', []);
app.controller('myFirstController', function($scope) {
    $scope.firstName = "Suraj";
    $scope.lastName = "Sahoo";
});
<html>
<body>
<div ng-app="app-Services" ng-controller="myFistController as ctrlFirst">
<span>{{ctrlFirst.firstName | uppercase}} {{ctrlFirst.lastName \ lowercase}}</span> //Displays firstName is UPPERCASE and lastName in lowercase
<ul>
  <li ng-repeat="name in names | orderBy:'age'">
    {{ x.name + ', ' + x.age}}
  </li>
</ul>
<span>{{price | currency}}</span>
<li ng-repeat="name in names | filter : 'S'">
    {{ name }} //Filters names based on names containing 'S'
  </li>
</div>
</body>
</html>

In the above snippets, we have used another directive i.e. ng-repeat, that is used to loop through the list of records just like foreach loop.
Another thing here to note is that the filter used in the above snippet, if we use the object containing the data or list of records/names suppose like:

<p><input type="text" ng-model="nameFilter"></p>
<ul>
  <li ng-repeat="name in names | filter:nameFilter">
    {{ name }}
  </li>
</ul>

What the above snippet does is, it loops through the names and based on the entry in the textbox or the user input, Like suppose user enters ‘S’, then the data listed are filtered on the object with the names that Starts With ‘S’.
Thus, we saw how these filters become handy and really useful.

Conclusion

Thus, here in this part we discussed about most of the great features of Angular and saw a few snippets to be used in progress. As I said earlier, in the succeeding modules we will gradually come across more interesting features and overall use of Angular.

Whats Next??

We will next come across how to build applications using Asp.NET MVC, EF Code First, Angular JS. That I assure would be interesting.

References

W3 schools
docs.angularjs.org

]]>
/hands-on-angular-js-ii/feed/ 0
Hands on AngularJs – I /hands-on-angularjs/ /hands-on-angularjs/#respond Mon, 04 Jan 2016 09:17:47 +0000 /?p=445

Introduction

The stand out hero in the market now. AngularJs it is from Google, intensifying the effectiveness of the plain HTML. There has been a constant and roaring buzz in the market on this. We have heard of MVC (Model-View-Controller), MVVM (Model-View-ViewModel) and many more framework. This is simple Javascript framework based on MVW framework.

MVW??

thinkzoo
Ok now what is MVW!! It stands for Model-View-Whatever . Like Salman Khan says, Whatever you want to do man!! Just Do! So Angular says, Add Whatever you want man!! πŸ˜€
The reason being is, it is actually close to MVC, MVVM and MVP as well. Earlier it had concepts related to MVC, but after the modification and enhancements and addition of the $scope, it came closer to MVVM framework as well. Thus, the framework became MVW.

Before we start hand on Angular, we need to have the resources required by it and start experimenting in a normal text editor like Notepad++ or Sublime Text. So is it time taking hectic!! Not at all, just navigate now to Angular JS Resources Download add the resources and just start. Even better way!! Just add the below CDN resources and just start. πŸ™‚

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

Some concepts

Now we have seen a lot of resources explaining the concepts thats new and interesting in Angular JS. Lets get a brief over view on each of the important concepts.

Angular Expressions

This is actually how Angular binds data onto the HTML and makes it dynamic in seconds. The syntax is {{ exp }}. Whatever is written in the braces, that data is bound to the HTML element.

<div ng-app="">
My age is: {{ 15 + 10 }}
</div>

Output would be:
My age is: {{ 15 + 10 }} //Actual angular is used here.

This will display My age is 25 in normal HTML as well.
But one thing, please read further, only this will not let you display the evaluated value. πŸ˜›

Angular directives

These are kinds of attributes added to the HTML elements, thus extending a new range of attributes to the HTML. ng- is the attribute syntax, just like data- attributes. There are flexibility in the directives as well. There are few in-build directives and there are directives we can create explicitly. Few of them are listed below along with a detailed example of their usage. Lets follow:

  • First and foremost directive is ng-app: This is utmost important directive as it starts/initiates the Angular application inside the HTML. If we remove the ng-app directive then the evaluation will fail as the Angular will not initiate.
  • ng-model: This is another important directive which actually makes our HTML dynamic as it stores the data/handles the data for the form or HTML controls which we add n the web pages.
  • ng-init: This is responsible to initiate the data for the model properties, in order to have some values pre-populated.

Let’s have a look at a simple code snippet:

<div ng-app="">
<input type="text" ng-model="firstName">
<input type="text" ng-model="lastName">
<span>{{firstName}} {{lastName}}</span>
</div>

Here the ng-model binds the firstName and the lastName as you type in the text box to give a dynamic feel.
To make the default names appear on the screen on the page load, we can use the ng-init to initiate the data for the model, just like below:

<div ng-app="" ng-init="firstName='Suraj';lastName='Sahoo'">
<input type="text" ng-model="firstName">
<input type="text" ng-model="lastName">
<span>{{firstName}} {{lastName}}</span>
</div>

Angular JS – MVC

Angular JS, as we mentioned above follows MVC architecture in the background. In the above simple snippets as we saw, how the data is bound to the view from the model values and presented on the UI.
AngMVC
Thus when the event is fired the Angular Controller is reponsible to fetch the data from http services using the $http.get(url) which in turn then binds data to the model using the ng-model and then data is dynamically bound to the view/html element. The concept here is similar and we will learn more on this once we follow up with the controllers and modules in Angular.

Conclusion

This was all about the start and simple directives to get your hands on Angular JS. In the succeeding modules and blogs, we will discuss more in details.

Hand on Snippet

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<h2>Welcome To Angular World</h2>
<div ng-app="" class="form-group">
<label>First Name</label><br>
<input type="text" ng-model="firstName" class="form-control"><br>
<label>Last Name</label><br>
<input type="text" ng-model="lastName"><br>
<br>
<span> Your Name is: {{firstName}} {{lastName}}</span>
</div>
</body>
</html>

What’s Next

  • Modular approach: Creating Modules in Angular ng-module
  • Controllers in Angular ng-controller
  • Scope in Angular $scope
  • Server interaction and binding data from APIs in MVC & Http Services $http
]]>
/hands-on-angularjs/feed/ 0
Simple way to learn HTML5 & CSS3 /simple-way-to-learn-html5-css3/ /simple-way-to-learn-html5-css3/#respond Sun, 25 Jan 2015 17:59:34 +0000 /?p=148 Download Demo Code

Topics to be covered

  • What is HTML5
  • Semantic Markup
  • Forms
  • Audio & Video
  • Data Storage
  • What is CSS
  • Inheritance & Cascading
  • Style Sheets
  • Page Layout & Nav bars
  • Web Matrix & Demo

What is HTML5?

HTML5 is the 5th version of HTML. Now wonder what is HTML!!think
HYPER TEXT MARKUP LANGUAGE. Caps means I am shouting, but it is a shout that needs to be done. Lets understand each word of it.
Hyper as we all know means to get exaggareted or tempered on something. Here it also has a similar meaning, when taken together with
Hyper Text. This means it gives a simple text a hyper meaning. For instance, a simple text video written changes to a iframe where a video is played when rendered on a browser.
HTML is used to create web pages in web applications. WebPages!! In a simple way, a page that gets rendered on web is called web page.
Let get some brief on the history also. πŸ™ . Though the sadpart but lets get into it a bit.
timeline
The above image says it all. But I would like to brief something interesting here. HTML4 was to be suppressed by XHTML but W3C(World Wide Web Consortium) never got heavily biased by XHTML.
HTML5 was being secretly developed by WHATG group. HTML5 is a combination of number of technologies and techniques and approaches to web. Thus the HTML5 was so convincing that it was approved by the W3C recently.

Semantic Markup

First lets know what is semantic! Semantic in dictionary means it is related to meaning in language and logic. That means what logic/idea you get you derive text out of it and HTML5 gives you the desired output. Like for instance,
You think of a logic where you want user to show the amount of download/upload done or progressed. So here we derive the word progress, and HTML5 gives the tag element that gives a gui letting user know the progress
done in the process.
Thus, Semantic markup means that mark up language does not only have syntax/sntactical meaning but also has a semantic meaning.

Doctype html simplified

<!Doctype html> has been simplified prior to the previously used has been replaced. Just for information, the syntax is case-insensitive.
html
The image shows, the html starts with the doctype that lets the web browser know that the document being loaded is of type “html”.
Then is thethat states that the html doc is written in english language.

Forms in HTML

HTML Forms are required when you want to collect some data from the site visitor. For example during user registration you would like to collect information such as name, email address, credit card, etc. A form takes the input from the user and stores them
in the server.
Different attributes are:-

  • Action:- Backend/Server side code for storing the records.
  • Method:- GET/POST, suggests whether to post data/input or get the data input into the form elements.
  • Target:- Specify the window/frame where the end result script will be shown, _blank,_self,_parent.

We will see the example in the demo codes.
formHtml

Audio & Video

In HTML5, there is no need anymore to use the iframes and load the videos/audios. The HTML5 audio and video tags make simple to add media files to website. We just need to set src attribute to let the frame know which video or audio to play, and also set the other attribute
like loop which plays the media file continously, autoplay lets the media file play when the page loads, controls let the controls icons to view on the frame and height width.
audiovideo

Data Storage

This is a very new concept that has been introduced in HTML5 that helps store data incase there is slow connection. Thus this introduces a balance between server side and the client side processing. This is an extension to cookies.
There are two types of data storage schemes,

  • Session Storage
  • Local Storage

 

Local Storage

Before HTML5 was introduced, data was stored in cookies and code was maintained on the server only. But now in HTML5, local storage is introduced where data can be stored in large bulk, without affecting the performance of the website. Unlike the cookies, the storage limit is 5MB.
The Local storage is based on the domain. All pages can access the stored data those are from the same domain as the data gets stored locally.
window.localStorage: (stores without expiration time)

function initiate(){
    var saveButton = document.getElementById("save");
    var retrieveButton = document.getElementById("retrieve");
    var deleteBUtton = document.getElementById("delete");
    saveButton.addEventListener('click', saveItem);
    retrieveButton.addEventListener('click', retrieveItem);
    deleteBUtton.addEventListener('click', deleteItem);
}

function saveItem(){
    var firstName = document.getElementById("fName").value;
    var lastname = document.getElementById("lName").value;
    var email = document.getElementById("eMail").value;
    var address = document.getElementById("add").value;
    var comments = document.getElementById("comments").value;
    localStorage[firstName] = address;
    document.getElementById("fName").value = "";
}

function retrieveItem(){
    var data = document.getElementById("retrieveData");
    var firstName = document.getElementById("fName").value;
    var add = localStorage[firstName];
    data.innerHTML =  add;
}
function deleteItem(){
    if (confirm('Delete?')) {
        var firstName = document.getElementById("fName").value;
        localStorage.removeItem(firstName);
        alert("Deleted");
        document.getElementById("retrieveData").value = '';
    }
}
addEventListener("load", initiate);

Session Storage

Before HTML5 was introduced, data was stored in cookies and code was maintained on the server only. But now in HTML5, session storage is introduced where data can be stored, without affecting the performance of the website. Unlike the Local Storage, in the session storage, the data
gets stored in session and also depends on the session. Once the session expires, the data is lost. But this not the case in the local storage the data persists without time limit, where as in the session storage the data is lost once the session expires or the browser is closed.
window.sessionStorage:-(stores with session expire time)

function initiate(){
    var saveButton = document.getElementById("save");
    var retrieveButton = document.getElementById("retrieve");
    var deleteBUtton = document.getElementById("delete");
    saveButton.addEventListener('click', saveItem);
    retrieveButton.addEventListener('click', retrieveItem);
    deleteBUtton.addEventListener('click', deleteItem);
}

function saveItem(){
    var firstName = document.getElementById("fName").value;
    var lastname = document.getElementById("lName").value;
    var email = document.getElementById("eMail").value;
    var address = document.getElementById("add").value;
    var comments = document.getElementById("comments").value;
    sessionStorage[firstName] = address;
    document.getElementById("fName").value = "";
}

function retrieveItem(){
    var data = document.getElementById("retrieveData");
    var firstName = document.getElementById("fName").value;
    var add = sessionStorage[firstName];
    data.innerHTML =  add;
}
function deleteItem(){
    if (confirm('Delete?')) {
        var firstName = document.getElementById("fName").value;
        sessionStorage.removeItem(firstName);
        alert("Deleted");
        document.getElementById("retrieveData").value = '';
    }
}
addEventListener("load", initiate);

Here we end discussing on the HTML5, now lets move onto the CSS

What is CSS

CSS- Cascading Style Sheet. Lets discuss the definition word by word.

“Cascading” in this context means that because more than one stylesheet rule could apply to a particular piece of HTML, there has to be a known way of determining which specific stylesheet rule applies to which piece of HTML.

Style sheet as it explains itself is a sheet where styles are specified for the HTML elements on the pages. Descendents inherit style from ancestors. More Specific styles win over the inherited style.

Identifiers, Class & Pseudo Elements

Identifiers are represented in an element as id=”IDENTIFIER NAME”. These are the unique peices that can only be attached/added to a specific element. These are accessed through the character “#”.
Classes are represented in an element as class=”CLASS NAME”. These are the peices that are defined once in the Style sheet and can be used in multiple elements. These are accessed through the charachter “.”(dot).

Pseudo elements are :first-child
:last-child
:nth-child(odd/even)
These elements are predefined and are accompanied or they succeed the letters of the html tag elements, like:-
pseudoelements

Specificity Rule

A very nice concept to know for using CSS in an effective manner. Lets look into the concept.

Id : a ex:- ul ol li .red
Class: b a = 0; b=1; c=3 => sp = 013
Pseudo Elements: c

As you can see in the above example, we can see ID has the highest specificity. see in the example i.e. ul ol li .red, there is one class so b=1, pseudo elements are 3, so c=3. Thus the specificity turns out to be 013.

Taking another example, ul #listID .redList, here the specificity turns out to be a=1;b=1;c=1 so 111.

Page Layout

  • Layout contain boxes, that is block-level elements
  • Use HTML Semantic tags
  • Else if Semantic tag don’t work, use
  • For making a column: set width
    set float
  • For Layout, start with content & Identify boxes.
  • Nav Bars

    • Is a set of links
    • List of different areas/pages using
    • Remove the bullets {list-style:none}
    • Eliminate padding & margins
    • Set display to inline-block to eliminate new lines
    • Style the links (as you wish)

    nav

    WebMatrix

    This is a very light weight, opensource tool provided by Microsoft that can be downloaded from the link below:-
    For Web Matrix

    Web Matrix can be downloaded also from the Microsoft Web Platform Installer from the below link:-

    For Web Platform Installer
    Finally the demo codes will look like below when run on browser:-
    layout

    ]]> /simple-way-to-learn-html5-css3/feed/ 0