95
Getting Started with Web Akshay Mathur

Getting Started with Web

Embed Size (px)

DESCRIPTION

This is the content of first workshop os a 3 workshop series for learning to create Single Page Web Apps. This focuses on introducing the HTML, CSS and Javascript to the newbies.

Citation preview

Page 1: Getting Started with Web

Getting Started with Web

Akshay Mathur

Page 2: Getting Started with Web

@akshaymathu 2

Ground Rules• Post on FB and Tweet now• Disturb Everyone during the

session– Not by phone rings– Not by local talks– By more information and questions

Page 3: Getting Started with Web

@akshaymathu 3

Let’s Know Each Other

• Do you code?• OS?• Programing Language?• HTML?• Javascript?• JSON?• Why are you attending?

Page 4: Getting Started with Web

@akshaymathu 4

Akshay Mathur

• Founding Team Member of– ShopSocially (Enabling “social” for retailers)– AirTight Neworks (Global leader of WIPS)

• 15+ years in IT industry– Currently Principal Architect at ShopSocially– Mostly worked with Startups• From Conceptualization to Stabilization• At different functions i.e. development, testing, release• With multiple technologies

Page 5: Getting Started with Web

What is Web?

Page 6: Getting Started with Web

@akshaymathu 6

The Web

• Many computers world wide connect to each other

• Information stored in one computer can be viewed from other computer

Page 7: Getting Started with Web

Involved SoftwareWeb Browser

Core Engine

JavaScript Runtime

DOM Renderer

Web Server

Web Server

Application Server

Database Server

Message Queuing ServerTask Workers

Caching Engine

Page 8: Getting Started with Web

@akshaymathu 8

The Evolution

Static PagesInput FormsDynamic Pages

Interactive Apps

Rich Internet Apps

Page 9: Getting Started with Web

@akshaymathu 9

Web 1.0 - Static

• Static pages – Were Read Only and B&W– Colors and other simple formatting came in

• Input Forms – Came in just for data collection to start with– Server side response based on input came in

Page 10: Getting Started with Web

@akshaymathu 10

Web 1.0 - Dynamic

• Client Side Dynamism– With DHTML, color changing web pages became

popular– Changing other basic properties of the text also

became possible• Server Side Dynamism– Dynamically generated pages made the web

responsive to inputs– Embedded scripting languages gave it a boost

Page 11: Getting Started with Web

@akshaymathu 11

Web 2.0: The Power

• Changing part of the webpage– Programmatically reading and writing DOM

elements– Rich event handling

• Communicating with server without refreshing entire page– AJAX

Page 12: Getting Started with Web

@akshaymathu 12

Understanding URL

https://sub.domain.com:8086/a/folder/file.html?key=val&key=val2#some_place

• Protocol• Sub-domain, Domain and TLD• Port• Path• File• Query string• Fragment

Page 13: Getting Started with Web

Understanding Web Page

Page 14: Getting Started with Web

@akshaymathu 14

Overall Structure

Page 15: Getting Started with Web

@akshaymathu 15

Doctype and DTD

• Tell browser what standards this document is following– How to parse

• HTML or XHTML• HTML version 1.0 or 1.1

– Show strict errors or not

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 16: Getting Started with Web

@akshaymathu 16

Html

• Only the content within <html> and </html> is parsed

• xmlns tells where the tags being used in the document are described

• Multiple xmlns attributes can be used

<html xmlns:fb="http://ogp.me/ns/fb#" xmlns="http://www.w3.org/1999/xhtml">

Page 17: Getting Started with Web

@akshaymathu 17

Head

• Typically Contains invisible items– Title– Meta– Link

– Script– Style

Page 18: Getting Started with Web

@akshaymathu 18

Title

• Title of the page• Shows up on title bar of browser

<title>ShopSocially | Engage Convert Amplify</title>

Page 19: Getting Started with Web

@akshaymathu 19

Meta

• Additional metadata of the page• Multiple meta tags can be used

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="keywords" 

content="social platform, conversion"><meta property="fb:app_id" 

content="213036345945">

Page 20: Getting Started with Web

@akshaymathu 20

Content Type

• Tells browser how to parse and execute the content– Character set info is also incuded

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

• ‘text/html’ is used for HTML pages– A few others are text/csv, application/pdf etc.

Page 21: Getting Started with Web

21

Link

• Link to external files• Typically used for CSS

@akshaymathu

Page 22: Getting Started with Web

@akshaymathu 22

Script

• Tells browser that the content is an executable script– Javascript, vbscript etc.

Page 23: Getting Started with Web

@akshaymathu 23

Style

• Embeds CSS on the page

<style type="text/css">.fb_reset

div{overflow:hidden} .fb_link img{border:none}

</style>

Page 24: Getting Started with Web

@akshaymathu 24

Body

• Contains all visible elements• Different elements can be used for laying out

the page– Look and feel can be controlled by style elements– Some elements can not contain anything inside

them e.g. input, br etc.

Page 25: Getting Started with Web

HTML Tags

Page 26: Getting Started with Web

@akshaymathu 26

Types

• Containers– Have opening and closing tags of same name– ‘/’ is used for closing e.g. <html>…</html>

• Non-containers– Don’t have a closing tag– ‘/’ is used at the end of same tag for closing e.g. <br />, <input type=“text” />

Page 27: Getting Started with Web

@akshaymathu 27

Display

• Block– Take up complete available width by default– Consecutive elements stack vertically

• Inline– Take up width only equal to the content– Consecutive elements stack horizontally– Typically word-wrap

Page 28: Getting Started with Web

@akshaymathu 28

Writing Text

• Text can be written directly in body• It is a good to have it in blocks– <p>…</p>

• Block display• Some default style

– <div>…</div>• Block display• No default style

– <span>…</span>• Inline display• No default style

Page 29: Getting Started with Web

@akshaymathu 29

Headings

• Preformatted text size– Seven sizes are available i.e. h1 … h7– Defaults can be overridden by CSS

• Important for SEO

<h1>This is heading</h1>

Page 30: Getting Started with Web

@akshaymathu 30

Bulleted List

• Can be un-ordered (<ul>) or numbered (<ol>)• List items (<li>) are shown indented• Can be multilevel and mixed<ol>

<li>item1</li><ul>

<li>sub item1</li></ul>

</ol>

Page 31: Getting Started with Web

@akshaymathu 31

Taking Input via Form Elements

• Text box: <input type=“text” />• Radio button: <input type=“radio” />• Check box: <input type=“checkbox” />• Button: <input type=“button” />• Hidden: <input type=“hidden” />• Multiline Text box: <textarea></textarea>• Dropdown/List:

<select><option>…</option>…

</select>

Page 32: Getting Started with Web

Styling Elements

Page 33: Getting Started with Web

@akshaymathu 33

Making it Look Different

• Look can be defined in style attribute of an element

<h3 style=“color: #aaa; background-color: #eee;

font-size: 16px; width: 100%; padding: 5px;>This is

Heading3 as I want</h3>

Page 34: Getting Started with Web

@akshaymathu 34

Font

• Font-face– Name of font to be used

• Font-family– Multiple font names in order

• Font-size– Text size in any unit i.e. px, percentage, em

• Font-weight– Bold or regular

Page 35: Getting Started with Web

@akshaymathu 35

Changing Colors

• Color value can be specified in many ways– Hex RGB is mostly used i.e. #rrggbb

• Background-color– Specifies color of background fill

• Color– Specifies color of text

• Border-color– Specifies color of border line

Page 36: Getting Started with Web

@akshaymathu 36

Box Model

• Width• Padding• Border• Margin• Position• Z-index• Top/Bottom• Left/Right

Page 37: Getting Started with Web

@akshaymathu 37

Where to write style?

• Inline– As ‘style’ attribute of an element

• Style block– On page in <style>…</style> block

• CSS file– In an external file

• This is also the preference order for applying style

Page 38: Getting Started with Web

@akshaymathu 38

Defining CSS

• Multiple styling properties can be grouped together

• Element(s) where to apply style is determined by CSS selector– Multiple CSS selectors may refer to an element

• All properties are applied to the element

Page 39: Getting Started with Web

@akshaymathu 39

CSS Selectors

• Tag namea {color: blue;}

• ID#my_unique_a {color: red;}

• Class.common_class {color:#ccc; margin:5px;}• Compound

.common_class a {color: green;}• Psudo

a:hover, a:visited {color: #ccc;}

Page 40: Getting Started with Web

@akshaymathu 40

CSS Frameworks

• Provide ready-to-use collection of classes for common requirements– Grid– Navigation bars– Form elements– Buttons– …

• Bootstrap is the great one

Page 41: Getting Started with Web

@akshaymathu 41

Page 42: Getting Started with Web

JavaScript

Page 43: Getting Started with Web

@akshaymathu 43

JavaScript

• Born in 1995 at Netscape• Not at all related to Java• Syntax influenced by C• Interpreted ECMA scripting lanuage• Dynamically typed• Object Oriented as well as Functional• Prototype based

Page 44: Getting Started with Web

@akshaymathu 44

Javascript

• Object Oriented– But different from other OO languages

• Single threaded• Runs in its sandbox– Has full access to the objects on the page– Has restricted access to other pages or client

machine file-system

Page 45: Getting Started with Web

@akshaymathu 45

Typical Usage

• Web programing– Client side

• Web pages• Browser plugins

– Server side• SSJS (not in use)• NodeJS

• PDF documents• Desktop Widgets• MongoDB

Page 46: Getting Started with Web

JavaScript Language Reference

Page 47: Getting Started with Web

@akshaymathu 47

Comments

• Single line– Starts with //– Can also be used after a statement

• Multi line– Starts with /* and ends with */

Page 48: Getting Started with Web

@akshaymathu 48

Statements

• Case sensitive• Ignore whitespace• Semicolon (;) is used as delimiter for

statements• Block of statements is delimited by curly

braces ({})

Page 49: Getting Started with Web

@akshaymathu 49

Output

• Visible to all using DOM functionsdocument.write(‘Hello’);alert(‘How are you’);

• For developers in consoleconsole.log(“This is working”);

Page 50: Getting Started with Web

@akshaymathu 50

Variable

• Explicitly defining is optional– JS runtime automatically defines as needed– Defining all variables with ‘var’ keyword is good

• Loosely typed– No need to define the type (int, str etc.)

• Dynamically typed– Type changes at runtime as the value changes

var my_var = ‘Hello’;my_var = 6;

Page 51: Getting Started with Web

@akshaymathu 51

Data Types

• String: “1”, “Hello! How are you”• Number: 1, 2, 121.22• Boolean: true, false• Array: [1, “1”, false, {a: 10}]• Object: {lang: “JS”, val: my_var}• Null: null• Undefined: undefined• Functions: function(){}• Date: Mon, 23 Sep 2013 12:18:54 GMT

typeof “1” // String

Page 52: Getting Started with Web

@akshaymathu 52

Operators

• Arithmetic+, -, *, /,%, ++, --

• Assignment=, +=, -=,*=, /=, %=

• Concatenation+

• Comparison==, ===, !=,!==, >, <,<=, >=

• Logical&&, ||, !

• Conditional() ? :

Page 53: Getting Started with Web

@akshaymathu 53

Conditional Blocks

• If… else if … elseIf (age > 18){ can_vote = true;} else { can_vote = false;}Orcan_vote = (age>18) ? true : false;

Page 54: Getting Started with Web

@akshaymathu 54

For Loop

• Forfor (i=0; i<array.length; i++){ console.log(array[i]);}• For/infor (item in array){ console.log(item);}

Page 55: Getting Started with Web

@akshaymathu 55

While Loop

• Whilewhile (is_extra_water){ drain();}• Do/whiledo { drain();} while (is_extra_water);

Page 56: Getting Started with Web

JS Functions

Page 57: Getting Started with Web

@akshaymathu 57

Function

• Code block that executes on ‘call’//define the functionfunction say_hello(name){ alert(‘Hello! ‘ + name);}

//call the functionsay_hello(‘Akshay’);

Page 58: Getting Started with Web

@akshaymathu 58

Function Arguments

• Any number of arguments can be passed without declaring

• Named arguments are not supported

say_hello(1); // Hello! 1say_hello(); // Hello! undefinedsay_hello(‘Akshay’, ‘Mathur’);

//Hello! Akshay

Page 59: Getting Started with Web

@akshaymathu 59

Naming a Function

function my_func(){}

• A function may not have a name

function(){};

my_func = function(){};

Page 60: Getting Started with Web

@akshaymathu 60

Variable Scope

• By default all variables are global• Variables defined with ‘var’ keyword are local to the

function• It is assumed that all variables are defined in the first

linefunction(){

var my_var = ‘Hello’;console.log(msg);var2 = 6;

}

Page 61: Getting Started with Web

@akshaymathu 61

Return Values

• Anything can be returned from a function using return statement

function sqr(x){var sq = x * x;

return sq;}

var four_sq = sqr(4);

Page 62: Getting Started with Web

@akshaymathu 62

Other Facts

• A function can be assigned to a variable• A function can be defined within another function• A function can return a functionfunction sqr(){ sq = function (x){

return x * x * x; }; return sq;}My_sqr = sqr(); // functionMy_sqr(3); // 27

Page 63: Getting Started with Web

63

Global Functions• encodeURI(),

encodeURIComponent() Encodes a URI

• decodeURI(), decodeURIComponent() Decodes a URI

• escape() Encodes a string • unescape() Decodes an encoded

string

• String() Converts an object's value to a string

• Number() Converts an object's

value to a number

• isFinite() Determines whether a value is a finite, legal number

• isNaN() Determines whether a value is an illegal number

• parseInt() Parses a string and returns an integer

• parseFloat() Parses a string and returns a floating point number

• eval() Evaluates a string and executes it as if it was script code

@akshaymathu

Page 64: Getting Started with Web

64@akshaymathu

Page 65: Getting Started with Web

JS Objects

Page 66: Getting Started with Web

@akshaymathu 66

Objects

• Everything in JS is an object (instance)“string”.length // 6“str”.length.toFixed(2) // “3.00”[‘hell’, ‘o!’].join(‘’) // ‘hello!’

• Custom objects can also be defined

Page 67: Getting Started with Web

@akshaymathu 67

JSON

• Javascript Object has a key and a value• Key is always string• Value can be of any type– Including another JSON object

A = {key1: value1, key2: value2};or

A = new Object();A[‘key1’] = value1;A.key2 = value2;

Page 68: Getting Started with Web

@akshaymathu 68

Object as Namespace

• It is a good practice to group variables and functions together in an object rather than keeping them global

var user = {};user.name = “Akshay”;user.greet = function(){ alert(‘Hello!‘.concat(user.name);};

Page 69: Getting Started with Web

@akshaymathu 69

Object as Named Argument• Objects can be passed to a function as an argument• They proxy for named arguments

Say_hello = function (options){ if (typeof options === ‘Object’){ options.msg = (options.msg)?options.msg : ’Hello!’; } alert(options.msg + ‘ ‘ + options.name);}

Say_hello({name: ‘Akshay’});

Page 70: Getting Started with Web

@akshaymathu 70

Page 71: Getting Started with Web

Dynamic Pages

Page 72: Getting Started with Web

@akshaymathu 72

Server Side Dynamism

• At web server• Ability to execute a program in context of a web

request– The program takes input from the request– The program creates a HTML page as output

• Web browser understands only HTML

• Embedded scripting technologies make it simpler– Allow the program to be inserted within an HTML

page• PHP, ASP, JSP etc.

Page 73: Getting Started with Web

@akshaymathu 73

Client Side Dynamism

• At web browser– Javascript

• Ability to change properties of elements on the web page on user’s action– Text color, image source etc.– On click, on hover etc.

• Ability to validate Form input without the round trip

Page 74: Getting Started with Web

@akshaymathu 74

Document Object Model

• Window Object– Represents the browser window– All Javascript functions and variable are attached

here by default• Document Object– Represents the page rendered inside the window– All HTML elements are available here• In the hierarchy they are attached

Page 75: Getting Started with Web

@akshaymathu 75

Manipulating the Web Page

• Get programmatic handle of an HTML element via Document Object Model (DOM)

var el = document.getElementByID(‘a_unique_id’);

• Change desired property of the elementel.src = “my_photo.png”

Page 76: Getting Started with Web

@akshaymathu 76

Changing Style

• Access to inline style properties is via style object

text_color = el.style.color

• Change desired style attributeel.style.fontSize = “16px”

Page 77: Getting Started with Web

@akshaymathu 77

Responding to User Actions

• Browser raises an event on user action– A few of them are onclick, onkeypress

• A JavaScript function can be called when the event happens

el.onclick = function(){alert(‘User clicked!’);

}

Page 78: Getting Started with Web

@akshaymathu 78

Page 79: Getting Started with Web

Creating Single Page Web App

Series of 3 workshopsFull Day

Hands-on

presents

Page 80: Getting Started with Web

@akshaymathu 80

1. Simple Web Pages

• Introduction to Web and its evolution• Web page basics and HTML tags• Styling elements• JavaScript basics• Introduction to DOM• Changing style using JavaScript• Simple DOM manipulation• Responding to user actions

Page 81: Getting Started with Web

@akshaymathu 81

2. Dynamic Web Pages

• Jquery JavaScript Framework• Handling DOM events• Getting data asynchronously via AJAX• Client side dynamism using JavaScript

templates• Simplify JS coding via CoffeeScript• Writing JS classes (prototypes)

Page 82: Getting Started with Web

@akshaymathu 82

3. Single Page App

• Understanding MVC concepts• Introduction BackboneJS and UnderscoreJS• Using Backbone models, views and router• Dealing with collections• Custom events and their handlers• Adjusting URLs for making browser buttons

work

Page 83: Getting Started with Web

@akshaymathu 83

Document Object Model

• Window Object– Represents the browser window– All Javascript functions and variable are attached

here by default• Document Object– Represents the page rendered inside the window– All HTML elements are available here• In the hierarchy they are attached

Page 84: Getting Started with Web

@akshaymathu 84

Manipulating the Web Page

• Get programmatic handle of an HTML element via Document Object Model (DOM)

var el = document.getElementByID(‘a_unique_id’);

• Change desired property of the elementel.src = “my_photo.png”

Page 85: Getting Started with Web

@akshaymathu 85

JS Framework

• Library for simplifying JS coding– Jquery is most popular

• Provides simple interface and syntactic sugar for common JS work– Selecting DOM element– DOM traversal and manipulation– Event handling

• Takes care of cross browser and cross version issues

Page 86: Getting Started with Web

@akshaymathu 86

Jquery

• Takes care of cross browser and cross version issues• Library for simplifying JS coding– Everything is via functions– Same function for get and set

• Provides simple interface and syntactic sugar for common JS work– Selecting DOM element– DOM traversal and manipulation– Event handling

Page 87: Getting Started with Web

@akshaymathu 87

Javascript Templates

• Dynamically creates HTML code in JS– Data driven HTML– Allows variable substitution, looping and

conditional statements• Generated HTML is inserted into the DOM for

changing part of the page on-the-fly

Page 88: Getting Started with Web

@akshaymathu 88

Using Template

<script type="text/x-jquery-tmpl” id=”photo">

<img src=“${photo_url}” title="${name}" />

</script>

<script type="text/javascript”>template = $(’#photo').template();t_html = $.tmpl(template, data);$(“#container”).html(t_html);

</script>

Page 89: Getting Started with Web

@akshaymathu 89

AJAX

• A way in web browser to communicate with server without reloading the page

• XmlHttpRequest (XHR) object can also create HTTP request and receive response– The request happens asynchronously• Other operations on page are allowed during the

request

– Received data does not render automatically• Data needs to be received in a callback function and

used programmatically

Page 90: Getting Started with Web

@akshaymathu 90

AJAX Call$.ajax({

url: ‘/my_ajax_target’,type: ‘POST’,DataType: ‘json’,data: {id: 2},success: function(response){

alert(‘Hello! ‘ + response.name);},

error: function(){alert(‘Please try later’);}

});

Page 91: Getting Started with Web

@akshaymathu 91

CoffeeScript

• A language with simple syntax– No semicolons and braces– Resembles to English– Indentation decides the code blocks

• Compiles into Javascript– Provides syntactic sugar for boilerplate code• Manage variable scope• Class instead of prototype

– Generates good quality, error free code

Page 92: Getting Started with Web

92

Cofeescript to Javascript

greet_me = (name) ->greeting_word = 'Hello!'alert "#{greeting_word} #{name}”

Compiles to

greet_me = function(name) { var greeting_word; greeting_word = 'Hello!'; return alert("" + greeting_word

+ " " + name); };

@akshaymathu

Page 93: Getting Started with Web

@akshaymathu 93

BackboneJS

• Provides MVC structure for Javascript– The model object holds data– The view object handles visual elements and

interactions– The controller object glues everything together and

provides communication amongst objects• Custom Events help writing good code and

eliminates use of global variables– The event object allows raising and handling custom

events

Page 94: Getting Started with Web

@akshaymathu 94

BackboneJS code in Coffeescriptclass LoginModel extends Backbone.Modelclass LoginView extends Backbone.View

initialize: =>@template = $(’#login_template').template()@render()

render: =>$(@el).html $.tmpl(@template, @model.toJSON())

events:'click #login_btn' : ’login_handler’

login_handler: (ev) =>window.mpq_track ’Login Click’

class LoginController extends Backbone.Routerinitialize: =>

@l_model = new LoginModel window.app_info@l_view = new LoginView model: model, el:

’#login_div’

Page 95: Getting Started with Web

@akshaymathu 95

Thanks

@akshaymathu

http://www.quora.com/Akshay-Mathur