Subscribe Now: Feed Icon

Sunday, February 17, 2013

HTML5+MVC Course, Day 1

My company is having a HTML5 and MVC course by E4D. As is my habit I like to write things down – for review and prosperity…
The course is presented by Yair Siwek.
The first day was more an overview on HTML5, JavaScript and quick uses of jQuery.

Overview

The course started with an overview about what we are going to go over:
Html5MvcCourseOverview
JavaScript is the language we use in the Browser, it advantage is in the fact that it is text so it passes the Firewall. Firewalls hate everyone, but text somehow passes…
JavaScript gives events on: the DOM, button click, data loaded, etc.
But it’s script that might cause Memory Leaks.
jQuery is a JavaScript library that started as a simple selector library to search for elements in the DOM tree. Then you can change those elements: text, CSS classes, events, etc. A lot of inline code, anonymous types/functions.
jQueryUI is a JavaScript library that uses jQuery as it’s base and adds gadget code like AutoComplete text box, calendar, tabs, accordion, drag & drop, etc.
The problem in jQueryUI is that the process of creating a new control is very long (gets out once per year), so other people started creating open source plugins in GitHub.
Knockout is a MVVM framework for JavaScript. There are other frameworks that are better for other usages (such as Backbone, Angular, Ember…).
The mobile world is different. For example in Facebook they have a Java (Android) team, Objective C (IOS) team and HTML5 for all the rest.

Tools:
Visual Studio 2012 – has intellisense for HTML5
With NuGet installed: insures all the dependencies and references are working together. Can be set so that the source of the files sits inside the organization.
Browsers: Chrome, Firefox, IE9

MVC
MVC = Model View Controller
The course is going to use Controller and (maybe) Model from MVC and the view in the client will be receiving JSON data from MVC.

Why not use WCF?
WCF uses SOAP which include a lot of metadata in the header (like security, transaction, reliable messaging, etc. ).
The browsers allow xml of type POX (Plain Old Xml) but not SOAP.
Microsoft implemented WCF-Ajax that returns JSON but that causes Cross Side Scripting problems. There is a pipeline in WCF that in the end cuts all the data to JSON – you are doing a lot of work but in the end just take a pips of the data. JSONP solved the problem but not all the controls know how to work with it.
The final point: it’s too much work when MVC is so much simpler.

HTML games

Open a new ASP.NET MVC4 project
Open a new HTML page
<!DOCTYPE html>
The tag means this is HTML5

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
Can be and should be cleaned up to just <html>.
In Chrome – F12 for Developer Tools, the best tool to play with the HTML and CSS of the page.
ChromeDeveloperToolsStyles
Under Styles are the CSS values we specified in the page.
Under Computed Style are the actual values in the browser.
For example: font-size: 1.5em is 1.5 of the default font size in the operating system, but in the browser that value means 24px.

Options of writing styles:

1. inline
<p style="font-family:Aharoni">Bad inline: Hello World2</p>
2. header
<head>
    <style>
        .MyClass1
        {
            background-color:gray;
            color:white;
            font-size:1.5em
        }
      
        p.MyClass1
        {
            background-color:gray;
            color:yellow;
            font-size:1.5em
        }      
    </style>
</head>
<div class="MyClass1">I am div 1</div>
Got the class MyClass1
<p class="MyClass1">Hello World1</p>
Got the class p.MyClass1. Because it was explicitly created for <p> tags it is stronger than just MyClass1.
<p class="MyClass1 MyClass2">Hello World3</p>
Got both MyClass1 and MyClass2 styles.
ID specific styles
#pId
{
    background-color:maroon
}
Only relevant for the tag with the id pId:
<p id="pId">pId</p>
3. Style for outside CSS file:
<head>
    <link href="Application.css" rel="stylesheet" />
</head>
Using it is the same as using header styles.

Rule: inline style is stronger than header style who in turn stronger than an outside CSS file.

Solution order conventions:

Content folder for application styles.
Scripts folder already contains NuGet scripts.
Scripts\App folder for application scripts

Demo Core JavaScript: Playing with the Page’s Layout

From 3 DIVs
<body>
    <div id="Div1">header</div>
    <div id="Div2">left</div>
    <div id="Div3">main</div>
</body>
To (just using styles):
HtmlCourseDemoExerciseLayout
  • No white in the margins only have the 3 colors.
  • Header should be 40px in height
  • Left should be 20% of the width and Main should be the other 80%
  • Left and Main should have all the rest of the screen
The next step is for the Header and the Left not to move when scrolling.

In Chrome the body tag has a default margin of 8px, to have no white in the page we need to change that to a margin of 0px. In other browsers the defaults might be different.
To make Main be on the right of left and not be a line below it we need to use the float style.

The end result is:
<style>
    body
    {
        margin: 0px;
    }
    #Div1
    {
        background-color: green;
        height: 40px;
        width: 100%;
        float: left;
        position: fixed;
    }
    #Div2
    {
        background-color: blue;
        width: 20%;
        float: left;
        position: fixed;
        top: 40px;
        height: 100%;
    }
    #Div3
    {
        background-color: orange;
        width: 80%;
        float: left;
        left: 20%;
        top:  40px;
        position: fixed;
        height: 100%
    }
</style>
HtmlCourseDemoLayoutResult

 

Demo in Core JavaScript: playing with z-index

<style>
    #div1
    {
        background-color:red;
        width:200px;
        height:100px;
        position:absolute;
        top:50px;
        left:50px;
        z-index:101;
    }
    #div2
    {
        background-color:blue;
        width:200px;
        height:100px;
        position:absolute;
        top:100px;
        left:100px;
        z-index:102;
    }
</style>
<div id="div1">div1</div>
<div id="div2">div2</div>
HtmlCourseZIndexDemo
One DIV is above the other, events such as on click for div2 will not fire when clicked on the area that div1 takes.

If we want to change the z-index on click then we have several options of writing methods:
1. The simplest option:
onclick="Div2_OnClick()"
2. For if we want to escape the function with return false:
onclick="return Div1_OnClick()"
3. With a timer (only mentioned not shown)


The script Tag should be after the the style tag if you want to use styles in the script.
<script>
    function WindowOnLoad() {
        //div1. - Might not work in all browsers
        //should have been:
        //document.getElementById("div1").style.zIndex = 102;
        //because its cross browsers
        div1.style.zIndex = 102;
        div2.style.zIndex = 101;
    }

    function Div1_OnClick() {
        div1.style.zIndex = 102;
        div2.style.zIndex = 101;
    }
    function Div2_OnClick() {
        div2.style.zIndex = 102;
        div1.style.zIndex = 101;
    }
</script>
<body onload="WindowOnLoad()">
    <div id="div1" onclick="return Div1_OnClick()">div1</div>
    <div id="div2" onclick="Div2_OnClick()">div2</div>
The setting of the zIndex in the WindowOnLoad method is an alternative way to set the styles but should not be used. The body onload will only fire when all the page loads – that includes downloading all the images.

Demo Hello jQuery

Showing manipulation of the following HTML:
<body>
    <button id="btn1">Click me</button>
    <div class="MyClass" id="div1">this is div1</div>
    <div id="div2">
        this is div2
        <div class="MyClass" id="div3">
            this is div3
        </div>
        <div class="MyClass" id="div4">
            this is div4
        </div>
    </div>
</body>
Adding the jQuery library by drag and drop from the Scripts folder to the <head> tag (after getting it from NuGet or from the jQuery site), or by writing:
<script src="Scripts/jquery-1.9.1.js"></script>
When working with jQuery you have the option of working with:
  1. The min version (jquery-#.#.#.min.js) which weights a lot less, has no documentation and better performance.
  2. The regular version (jquery-#.#.#.js) which has documentation and is generally better for debug.
  3. The intellisense version (jquery-#.#.#.intellisense.js) for people working with the min version , they can add intellisense using this file (if you are working with the regular version you don’t need the intellisense version).

jQuery has several selector options (i.e. $() ):
  1. Using object: $(document) returns the DOM object
  2. Tag name: $(‘div’) selects all the DIV tags
  3. Tag ID: $'(‘#Tag_Id’) selects the tag that has the Id Tag_Id
  4. Tag Class: $(‘.Tag_Class’) selects all the tags that use the class Tag_Class
There are more selectors which can be read here.

jQuery has an event for OnLoad minus, for when the DOM has loaded but the images haven’t:
<script>
    $(document).ready(function() {
        alert("hello"); //Will jump before images
All the operation in jQuery are done with functions. The event ready receive an anonymous function that does the action (you can also write a regular JavaScript function but it is usually done with Anonymous types):
  • Set the value into html:
$("#div3").html("can you see me?")
  • Returns the html text:
$("#div3").html()

The previous example of:
div1.style.zIndex = 102;
Is bad code because it might not work in all browsers, the right code should be:
document.getElementById("div1").style.zIndex = 102;
In jQuery we can simply do $(“div1”) and it will work in all browsers because jQuery insures it.
//bad code (will go over the tree a few times to get div3):
$("#div3").addClass("redStyle");
$("#div3").html("can you see me?");
alert($("#div3").html());
If you open debugger and step into all the $(“#div3”) you will see that jQuery iterates through the DOM tree for each call of $(“#div3”) and after each action returns the original selection (i.e. Fluent Interface).
The good ways:
  • Using a temporary variable:
var $div3 = $("#div3");
$div3.addClass("redStyle");
$div3.html("can you see me?");
Using the variable name $div3 is a jQuery convention of saying this variable is from jQuery.
  • Better way of doing everything inline:
$("#div3")
    .addClass("redStyle")
    .html("can you see me?");

Demo – Change Class
Register to the click event of the button so the class is changed on every click of div3:
$("#btn1").click(function() {
    $("#div3")
        .removeClass("redStyle")
        .addClass("boldStyle")
But on the next click nothing will happen, another option is using toggle (which uses the current state):
$("#btn1").click(function() {
    $("#div3")
        .toggleClass("boldStyle")
        .toggleClass("redStyle")

Adding a style to a given class (if the class already contained a color than this definition will override it):
$(".MyClass")
    .css("color", "red");

Hiding an element slowly and in the end change the text of the button to “Done”:
$("#div4").toggle("slow", function() {
    $("#btn1").html("Done");
});
jQuery behind the scenes changes the style of the display to none (and if clicked again to block).

Multiple Selectors:
$(".MyClass, #div2")
    .css("font-family", "serif");
All the tags that their Id is div2 or have the class MyClass.
$("#div2 .MyClass")
    .css("color", "blue");
All the tags that their ancestor is div2 and have the class MyClass.
$(".MyClass.redStyle")
    .css("color", "purple");
All the tags that have the both class MyClass and redStyle.

Resources:
jQuery, and API Documentation
The 30 CSS Selectors you Must Memorize
jQuery Fundamentals
CSS3 - Intro, Guides & Resources
W3School CSS – not very useful