70
PFNP - SESSION 2: THE FRONT END WILL MYERS Freelance Front-end Developer WORKING FILES FOR THIS WEEK http://bit.ly/1lJc7AM SLIDES http://www.slideshare.net/wilkom/pfnp-slides

Pfnp slides

Embed Size (px)

Citation preview

PFNP - SESSION 2: THE FRONT ENDWILL MYERS

Freelance Front-end Developer

WORKING FILES FOR THIS WEEKhttp://bit.ly/1lJc7AM

SLIDEShttp://www.slideshare.net/wilkom/pfnp-slides

ATOM PLUGINSopen Atomgo to Preferences (Atom > Preferences), this will launch aSettings tab.select Install from the Settings left-hand navsearch for 'atom-beautify' and install thisdo the same for 'open-in-browser', 'white-cursor' and'highlight-line'restart Atom

SUBLIME PACKAGE CONTROLhttps://packagecontrol.io/installation

AGENDASummary from last weekHTML Tags & CSS Selectors ReviewThe Box Model, Positioning, FlexBoxJavaScript and JQuery ReviewAdding a simple Express Server to your webpageInternet protocols - IP, TCP, HTTPOnline Global Community for Web Development

SUMMARY FROM LAST WEEK introduction to the command line.

workshop to learn the basics ofJavaScript.Install Node, NPMInstall http-server module globallyCreate simple webpage with CSS styling and someJavaScript functionality( )Run the http-server command to serve the currentworking directory's files and sub-folders to the browser.

GA FundamentalsNodeschool javascripting

http://codepen.io/cbas/pen/QjRWZm

HTML TAGS REVIEW

HTML SYNTAX

creates structured documents from page 'parts'(headings, paragraphs, lists, links, footer etc)is written in the form of HTML elements consisting of tagselements either have opening and closing tags: <p></p>or are 'empty', they have no closing tag: <img>

HTML SYNTAX

HTML tags can also have attributes which are propertieswritten inside the first (opening) tag:

<img src="smiley.gif" height="42"width="42">

MAIN TAGS<html></html> the root container tag for the whole

document (web page)

<head></head> the container tag for metadata and linksto external files (e.g .css files)

<body></body> contains all the visible structure andcontent of the web page, nested inside

CONTENT TAGSHeading Elements

<h1>Largest Heading</h1>

<h2> . . . </h2>

<h3> . . . </h3>

<h4> . . .</h4>

<h5> . . . </h5>

<h6>Smallest Heading</h6>

CONTENT TAGSText Elements

<p>This is a paragraph</p>

<code>This is some computer code</code>

<span>For styling words inside a container tag</span>

CONTENT TAGSUnordered list <ul></ul>

CONTENT TAGSUnordered list item

<li>First item</li>

<li>Next item</li>

CONTENT TAGSlinks

<a href="Link">First item</a>

CONTENT TAGS<div></div>

This is a very widely used generic container tag. It is arectangular element which can be styled with margins,

padding, borders, background-colors, width, height etc. Likemany other elements it has block-level display which means

it starts on a new line of the page.

<div>s can be nested in other <div>s

IMAGES<img src="smiley.gif" height="42"

width="42">

The img tag requires a src attribute, which tells thebrowser where to find the image.

IMAGESHow would you write the src?

There are different approaches to specifying an imagelocation

IMAGESInside webroot, a relative path could be used:<IMG SRC="IMAGES/LOGO.PNG">

IMAGESRelative Path

Given this folder structure the same image would be<img src="../images/logo.png">../ means to go up a directory, and can be usedrepeatedly: ../../ would go up two directories.

IMAGESAbsolute Path

<img src="/images/logo.png">

Absolute URLs start with a /, which implies the rootdirectory of your web site.

IMAGESFull URL

<img src="https://ga-core.s3.amazonaws.com/production/uploads/program/default_image/397/thumb_User-Experience-Sketching.jpg"

IMAGESalt attribute

<img src="puppy.jpg" alt="My cute puppy">

HTML VS HTML5HTML5 is HTML with a few additions The Doctype tells you if

the page is HTML5 ready.

<!DOCTYPE html>

HTML HISTORY

HTML5brings many improvements and new features to webpagesmany features of HTML5 have been built to run on low-powered devices such as smartphones and tabletsintroduces the new <video>, <audio> and <canvas>tagsintroduces many new structural document tags, e.g.<main>, <section>, <article>, <header>,<footer>, <aside>, <nav> and <figure> - theseare like <div> but with a semantic styleable name.

CSS REVIEW

CSSis a styling (stylesheet) language used for describing thepresentation of an HTML documentit separates document content from documentpresentation, including control of layout, colors, andfontsit makes the page much easier to edit and update, andimproves accessibilitymultiple HTML pages can share the same formatting bywriting the CSS in a separate .css file and linking to it fromyour HTML page

CSS SYNTAX

CSSWhere does CSS go?

Inline with the style attribute<h1 style="color: red;">Hello World</h1>

In the head<head> <style> </style></head>

h1 {color: red;}

In a separate file (best option)<head> <link rel="stylesheet" type="text/css" href="path/to/some.css"></head>

CSSUsing a separate CSS file

It is best practice to put CSS in its own file and link to it fromthe <head>.

<link rel="stylesheet" href="style.css">

CSS BREAK DOWNp { color: red; font-weight: bold;}

CSS BREAK DOWNThis whole thing is called a rule.

The p is called a selector, and it's followed by a set ofdeclarations in a declaration block.

CSS BREAK DOWNThe selector, p in this case, specifies what parts of the HTMLdocument should be styled by the declaration. This selector

will style all p elements on the page.

CSS BREAK DOWNThe declaration block here is:

{ color: red; font-weight: bold;}

Declarations go inside curly braces.

Every declaration is a property followed by a value,separated by a colon, ending in a semicolon.

CASCADING STYLE SHEETS (CSS)COLORS

Colors can be specified in CSS in a variety of ways:

keyword (e.g. red or blanchedalmond)hex codes (e.g. #FF0000)rgb(0,0,0)rgba(255, 255, 255, 0.8)hsl(0, 100%, 50%)hsla(0, 100%, 50%, 0.8)

Today we'll use keywords :http://www.w3schools.com/html/html_colornames.asp

CSS SELECTORSif you want to directly style all elements of a certain type (e.g

all <p> tags) they you style pp {color: red;}

if you want to apply styles to individual elements then use'#' (hash/id) selectors. This selects one element on your

page with an unique id attribute#my-id {color: green }

if you want to apply styles to groups of elements then use '.'(dot/class) selectors. These select elements which have a

corresponding class attribute..my-class {color: blue }

CSS SELECTORSThere are many other selectors and each has a different

level of importance. This means it can either be overwrittenby, or can overwrite another style.

See: http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

CSS SELECTORS EXERCISEIn the blank folder of the downloaded working files, do the

following:

Copy this code into lesson.css#my-id { color: green; background-color: white; }.my-class { color: blue; background-color: yellow; }

Copy this code into lesson.html<p id="my-id">There should only be one of me.</p><p class="my-class">There can be many of me.</p><p class="my-class">There can be many of me.</p><p>This text has <span class="my-class">a styled bit</span> inside</p>

CSS STYLE PROPERTIESThere are many CSS styling properties. Some can be applied

to all types of tags, others only work on certain tags.

color: sets the color of textbackground-color: sets the color of the backgroundrectangular area, including the paddingwidth: sets the width of the element in different unitsheight: sets the height of the element in different unitsfont-family: sets the text fontfont-weight: sets the text font weight - e.g. bold orcan be a numeric value

CSS STYLE PROPERTIESThese properties relate the to the box model and

positioning

margin: sets the outer transparent rectangular border ofan element as part of the box modelborder: sets the visible rectangular border style of theelement as part of the box modelpadding: sets the inner transparent rectangular borderof an element as part of the box modeldisplay: sets the layout of the element in the 'flow ofthe page'

CSS BOX MODELThe CSS box model is essentially a box that wraps around

every HTML element. It consists of: margins, borders,padding, and the actual content.

In terms of visibility, margin area is transparent, paddingarea inherits background-color, border has its own style

and color properties.

You can see a representation of the box model for anelement in Chrome dev tools (Cmd + Alt + I), in the

'Elements' tab.

CSS STYLE PROPERTIESmargin, border and padding have individual properties

for each side of the rectangle.

margin-top, margin-left, margin-bottom, margin-rightborder-top, border-left, border-bottom, border-rightpadding-top, padding-left, padding-bottom, padding-right

These values can also be set with shorthand:

margin: top right bottom left; (clockwise)margin: top-and-bottom left-and-right;

CSS STYLE PROPERTIES - BORDERSBorder has its own style and color properties:

border-width (number px)border-style (string)border-color (string or hex value)

It is commonly set as border: width style color;

border: 4px dashed red;

CSS STYLE PROPERTIES - BORDERSBorder style properties: none (low priority), hidden (high

priority), dotted, dashed, solid, double, groove,ridge, inset, outset

Don't forget border-radius

border-radius:50%; makes a square into a circle

CSS AND <DIV> EXERCISERemembering that a <div> can be styled and nested inside

another <div>, try and do the following:

create a circle inside a squarecreate the Singaporean flag (without the stars)

Your code should look something like:<div class="parent-class"> <div class="child-class"></div></div>

The demo is here, but have a go without looking firsthttp://codepen.io/wilkom/pen/OyrPzV

Work in the blank folder of the downloaded working files

CSS POSITIONINGYou can also position <div>s (or other HTML tags) with

exact values using the position property and top, left,bottom, right properties.

position has the following values:

static: default positioning in the document flowabsolute: positioned relative to its first non-staticancestor elementfixed: positioned relative to the browser windowrelative: positioned relative to it's normal defaultposition

CSS POSITIONING EXERCISEGo to this link: http://codepen.io/wilkom/pen/xwmPeL

You can see the top and left properties set on the differentclasses that are applied to the <div>s.

CSS OVERFLOW OF AN ELEMENTWhat happens when we put some content into a container

and the content is bigger than the container? This canhappen particularly when you want to put some text insidea container of a fixed size, but the text requires more space

than the container has available.

Open up the folder named overflow-text and open thelesson.html file in your browser

CSS OVERFLOW OF AN ELEMENTFor this we used the overflow property in the container. It

has the following values:

visible: (default) the content will âbreak outâ and bevisiblehidden: any overflowing content will be hiddenscroll: the content is clipped and scroll bars will alwaysbe availableauto: the content is clipped and scroll bars should beavailableinitial: default valueinherit: inherits from parent container

CSS OVERFLOWING NESTED IMAGESOpen up the folder named nested-image and open the

lesson.html file in your browser

See if you can get the image to scale down be 'sitting inside'the parent circle. Hint there is a class you can use in the

lesson.css.

CSS FLOW OF AN ELEMENT IN THEPAGE LAYOUT

The display property affects how an element is positioned inthe 'flow' of the page.

display has the following values:

block: means the element 'moves down' the pageinline: means the element 'moves across' the pageinline-block: means the element is inline and theinside of this element is blockflex: this is a big new thing that makes layouts easier

CSS FLEXBOXFlexbox is a new way of laying out the flow of elements in a

web page.

It is a definite improvement in layout techniques for webpages. A good link explaining Flexbox is here:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

It is now fairly well supported in browsers (going back to IE9using prefixing), and so should be used in front-end web

development going forward.

CSS PAGE LAYOUT PRE-FLEXBOXOpen up the folder named web-page-float-layout

and open the lesson.html file in your browser

Before Flexbox the most common way of doing a pagelayout involved floats. The float property in CSS was

originally intended for making content 'float alongside'other content. It ended up also being used to float

containers alongside each other (e.g. sidebars in a webpage).

CSS FLOATSYou can 'float' elements to the left or right of a parentcontainer.Floats are often used for page layouts - for example tohave a sidebarYou need to use the clear property in the style of theelement that comes after the container of the floatedelements. This stops the float continuing in the rest of thepage. By convention a style for clearing a float iscommonly called a clearfix.

CSS FLOAT LAYOUT STYLES.sidebar{ float:left;}

.clearfix{ clear:left;}

CSS CLEARING FLOATSYou need to clear floats for different reasons - whether

you are still inside the container of your floated elements orback up on the same level as the container.

In both cases a clear will fix things, but because things aredifferent inside and outside the container there are also

other approaches to clear-fixing. Basically floated items in acontainer will cause the container to collapse so this will

affect subsequent elements at the container level, as well aselements in the container.

See http://www.sitepoint.com/clearing-floats-overview-different-clearfix-methods/

CSS HTML5 TAGS LAYOUTOpen up the folder named web-page-h5 and open the

lesson.html file in your browser.

This page layout does not use floats but doesn't useFlexbox either. It is a single column layout with a 'sticky

footer'.

It uses HTML5 semantic tags which can be styled directly.

CSS FLEXBOX LAYOUTFlexbox's algorithm works on the basic principles of

elements flowing (vertically or horizontally), wrapping, andexpanding or shrinking according to different page sizes (e.g

for a laptop screen vs a tablet screen vs a mobile phonescreen).

Open up the following working files in the browser and playaround with resizing the window:

flexbox/holy-grail-layout/index.htmlflexbox/flexible-column-layout-with-rows/index.html

CSS FLEXBOX VERTICAL CENTERINGAnother old problem that Flexbox solves easily is vertically

centering text. Previous ways of doing this involved hackeryor limitations (e.g. content could only be on one line).

Go to this link to see examples of vertically centered text:

http://codepen.io/wilkom/pen/NGeyNg

CSS FONTSIn our web pages we can use the system fonts that come

with most operating systems, like Times, Arial and Helvetica.

But what if we want to use a really cool font, and embed itso that anyone who visited our web page would see that

font. Enter the CSS3 font embedding syntax.@font-face { font-family: MyFont; src: url('path/to/MyFont.ttf'); }

Now go and download some cool free fonts and put them inyour project folder: http://www.dafont.com/

Use the font-family: MyFont; property to apply thatfont to a given tag

CSS3 TRANSITIONSCSS3 which is the latest well supported version of CSS gives

you the ability to add transition animations to your HTMLelements. We use the transition property.

We can add some transitions to specific properties so thatthey change smoothly over time. One place we can do this is

when an a:hover style is applied to an <a> anchor tag.-webkit-transition: background-color 2s;transition: background-color 2s;

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions

JAVASCRIPT AND THE DOMJavaScript in the browser has an API (application program

interface) for accessing and editing the DOM (the documentobject model) of an HTML document. The DOM is a

hierarchical tree representation of the structure of the HTMLin a web page.

JavaScript can target specific elements on an HTML pageand show, hide, style, edit and animate them. It can also

listen for events emitted by an HTML page (e.g mouse-clicks)and invoke functions when an event occurs.

JAVASCRIPT AND THE DOMJavaScript gets a reference to elements with (for example)document.getElementById()

The JQuery library provides easier ways to do this, but is notactually necessary.

JAVASCRIPT AND CSSYou can dynamically set CSS classes on elements with

JavaScript.

Open up the 'jsfb-styling-css-with-js' in the 'js-for-beginners'folder and open lesson.html in your browser

JAVASCRIPT AND CSSThe same thing can be achieved with jQuery using less code,

but you have to import the jQuery library too!

Open up the 'jsfb-styling-css-with-jquery' in the 'js-for-beginners' folder and open lesson.html in your browser

JQUERYJQuery is a JavaScript library that does the following:

Access parts of the HTML pageModify the appearance of the pageEdit the pageRespond to user interactionAdd animationRetrieve data from a server using AJAX (AsynchronousJavaScript and XML)Simplify common JavaScript tasks

JQUERYJQuery also provides the following useful features:

uses CSS selector syntaxsupports extensionsabstracts away browser quirksallows multiple actions to be defined in one line withchaining

JQUERY SCROLLINGFirstly lets create some <a> anchor tags that link to otherparts of your same page. If you are linking to a spot on the

same page, the format of the link will be similar to:<a href="#my-anchor">Jump to contact details</a> //note the # (hash)!

Now set the anchor where the first <a> will link to. Theanchor should be placed at the beginning of the line where

you want to start reading after you jump:<p><a name="my-anchor"></a>Hey you can contact me at [email protected]</p>

or you can target the id of a <div><div id="my-anchor">

JQUERY SCROLLINGNow make sure jQuery is linked in the <head> of your

page:<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

Create a file called scrollLinks.js and put it in the rootof your current folder. Then create another <script> link

in your <head>:<script defer src="scrollLinks.js"></script>

JQUERY SCROLLINGNow copy and paste the following code into

scrollLinks.js

$(document).ready(function(){ $('a[href̂="#"]').on('click',function (e) { e.preventDefault(); var target = this.hash; var $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); });});

When you click on an <a> that links to another part of yourpage, the page should scroll to that position.

NODEJS EXPRESS SERVER EXAMPLEcd to the 'hello-express-programmers' folder in your

Terminal. We now need to install dependencies via thecommand line

npm i express --save

npm install

Now run the server withnpm start