~~CLOSETOC~~ ~~TOC 0-3~~ |<100% 25% - >| ^ \\ DATA ANALYTICS REFERENCE DOCUMENT\\ \\ ^^ ^ Document Title:|46376 - Web App Development| ^ Document No.:|1548351190| ^ Author(s):|Rita Raher, Gerhard van der Linde| ^ Contributor(s):| | **REVISION HISTORY** |< 100% 10% - - 10% 17% 10% >| ^ \\ Revision\\ \\ ^\\ Details of Modification(s)^\\ Reason for modification^ \\ Date ^ \\ By ^ | [[:doku.php?id=modules:46376&do=revisions|0]] |Draft release|46376 - Web App Development| 2019/01/24 17:33 | Gerhard van der Linde | ---- ====== 46376 - Web App Development ====== [[https://www.tutorialspoint.com/html/html_tutorial.pdf|A free PDF Book on HTML and is good reference resource]] ===== Learning Outcomes ===== * The design, development and deployment of web applications using HTML, CSS and JavaScript * The architecture of the World Wide Web * Creating a web application with Data Driven Document Framework (D3) ===== Course Structure ===== * 13 Weeks * Lectures and reading material ===== Assessment and Marking ===== * Week 4 - MCQ Assesment (10%) * Week 8 - MCQ Assesment (20%) * Week 12 - MCQ Assesment (20%) * Final Project (50%) ===== Course Outline ===== * HTML - Beginning Week 1 * CSS - Beginning Week 3 * JavaScript - Beginning Week 5 ===== Resources ===== * W3Schools: http://www.w3schools.com/ * HTML Dog: http://htmldog.com/ * W3C Markup Validation Service: https://validator.w3.org/#validate_by_input * HTML-Validator: https://www.freeformatter.com/html-validator.html ====== Week 1 - Introduction ====== * Welcome to Web Application Development * The Evolution of the World Wide Web * Hello World Wide Web! ===== The Evolution of the World Wide Web ===== * The internet - A global network of computers using various protocols * The world Wide Web - A way of accessing information over the medium of the internet * ARPANET - 1969 - 1990 * Tim Berners-Lee * Cern * March 1989 * Included HTML - Hypertext Markup Language ===== Early Web Pages ===== * Basic Functionality lacking fonts, colour of advanced presentation * CSS - Cascaded Style Sheets - Created for presentation * 1990 - HTML * 1994 - CSS version 1 * 1995 - HTML v2 * 1995 - //JavaScript// * 1998 - CSS v2 * 1999 - CSS v3 - numerous updates since * 2014 - HTML v5 ===== Current Web Versions ===== * HTML v5 * CSS v3 * JavaScript v1.8.5 * Versions are browser dependent * W3C publishes standards * Not all browsers support HTML5 ===== Most Popular Browsers ===== * Google Chrome - 73% * Firefox - 15.5% * IE(Edge) - 4.8% * Safari - 3.5% * Opera - 1.1% HTML5 Browser compatibility testing - https://html5test.com ===== Purpose ===== * HTML - Structure * CSS - Presentation * JavaScript - Behaviour ===== Hello World Wide Web! ===== [[https://www.w3schools.com/html/tryit.asp?filename=tryhtml_basic|W3schools Try it]]

Hello World!

This is some sample paragraph test text

====== Week 2 - HTML Coding ====== ===== References ===== ==== Related External Links ==== W3c validator Service: https://validator.w3.org/#validate_by_input ==== W3C Recommendations on HTML code structure and doctype declaration ==== https://www.w3.org/QA/2002/04/valid-dtd-list.html\\ Note Indentation example on this basic page\\ http://w3c.github.io/html/syntax.html#the-doctype ==== Lists ==== w3Schools resource on lists; note other attributes that can be used in lists\\ http://www.w3schools.com/html/html_lists.asp\\ W3.ORG on Lists: https://www.w3.org/TR/html40/struct/lists.html\\ ==== Semantic Markup ==== http://www.w3schools.com/html/html5_semantic_elements.asp ===== Part 1: Installing a Development Environment & HTML document structure ===== * Find and install notepad++((https://notepad-plus-plus.org/)) * Create a html body framework * Create a sample html document My Web Page My Web Page

The History of the World Wide Web

Tim Berners Lee and the Development of HTML

The World Wide Web ("WWW" or simply the "Web") is a global information medium which users can read and write via computers connected to the Internet. The term is often mistakenly used as a synonym for the Internet itself, but the Web is a service that operates over the Internet, just as e-mail also does. The history of the Internet dates back significantly further than that of the World Wide Web.

Precursors

The hypertext portion of the Web in particular has an intricate intellectual history; notable influences and precursors include Vannevar Bush's Memex, IBM's Generalized Markup Language, and Ted Nelson's Project Xanadu. Paul Otlet's Mundaneum project has also been named as an early 20th century precursor of the Web. The concept of a global information system connecting homes is prefigured in "A Logic Named Joe", a 1946 short story by Murray Leinster, in which computer terminals, called "logics," are present in every home. Although the computer system in the story is centralized, the story anticipates a ubiquitous information environment similar to the Web.

1980-1991: Invention and implementation of the Web

In 1980, Tim Berners-Lee, an English independent contractor at the European Organization for Nuclear Research (CERN) in Switzerland, built ENQUIRE, as a personal database of people and software models, but also as a way to play with hypertext; each new page of information in ENQUIRE had to be linked to an existing page. Berners-Lee's contract in 1980 was from June to December, but in 1984 he returned to CERN in a permanent role, and considered its problems of information management: physicists from around the world needed to share data, yet they lacked common machines and any shared presentation software.

===== Part 2: Lists, Semantic Markup, Comments, Indentation and Validation ===== ==== Ordered HTML List - The Type Attribute ==== * type="1" The list items will be numbered with numbers (default) * type="A" The list items will be numbered with uppercase letters * type="a" The list items will be numbered with lowercase letters * type="I" The list items will be numbered with uppercase roman numbers ==== Improve readability of your code ==== - use comments - indent your code
  1. item 1
  2. item 2
  3. item 3
  4. item 4
==== Validating your code ==== https://validator.w3.org/#validate_by_upload ==== Add links to your code ==== Link To open on in a new tab target="_blank" Link My Table
cell 1 cell 2 cell 3
cell 4 cell 5
cell 8 cell 9
===== Lab exercise week 2 ===== {{ :modules:46376:pdf:excercise_-_introduction_-_week_2.pdf |Lab Exercise Week 2 - Introduction to HTML}} ====== Week 3 - Linking, Images and Forms ====== ===== Part 1: Linking to internal webpages ===== Related External Links Information from W3C on URLs: https://www.w3.org/TR/WD-html40-970917/htmlweb.html {{ :modules:46376:html_links.png?nolink |}} All files are in the same folder and referenced directly in links. ==== Directory Structure ==== {{:modules:46376:directory_structure.png?nolink&200 |}} Folder and directories are used interchangeably. Folders are refered to as Chold, Parent, Garndchild and Grandparent similar to family trees. Understanding //relative URL's// is important when referencing files in folders and subfolder or parent folders. ===== Part 2: Images in HTML ===== # img is a void tag, no open and close, all inside tag # alt tag Picture Info #dimensions is pixels Picture Info ==== Supported file formats ==== ^ext^description^comments^ |.jpeg|joint photographic experts group|technically not a file format but a method to compress images| |.jpg| ::: | ::: | |.gif| |8 buts per pixel, not good for photos. Supports animated and transparent images. | |.png|portable network graphics |losless compression, supports tranparency | ===== Part 3: Troubleshooting Images and links ===== ===== Part 4: Forms and Form Controls in HTML ===== Related Resources Sample code for form controls provided underneath in related code External Resources W3C resource on Form Controls https://www.w3.org/TR/2002/WD-xforms-20020118/slice8.html ===== Part 5: Validation and Input in HTML5 ===== Related Resources * [[https://www.w3schools.com/tags/att_input_required.asp|Forcing a user to input using the REQUIRED attribute]] * [[https://www.w3schools.com/html/html_forms.asp|Forms]] * [[https://www.w3schools.com/html/html_form_elements.asp|Form Elements]] * [[https://www.w3schools.com/html/html_form_input_types.asp|Form Input Types]] * [[https://www.w3schools.com/html/html_form_attributes.asp|Form Attributes]] ===== Part 6: Additional HTML ===== Related Resources * [[https://www.w3.org/International/questions/qa-escapes|Escape Characters in HTML]] * [[https://www.w3schools.com/html/html_entities.asp|HTML Entities]] * [[https://www.w3schools.com/html/html_blocks.asp|Inline and Block elements]] ===== Lab Exercise ===== {{:modules:46376:pdf:week_3_-_lab_exercise_-_images_links_forms.pdf|}} Related Resources * {{:modules:46376:pdf:week_3_-_text_files_for_exercise-20190209.zip|Text sources for excercise}} * {{:modules:46376:pdf:week_3_-_images-20190209.zip|Image sources for excercise}} ====== Week 4 - Cascading Style Sheets ====== ===== CSS- The Box Model ===== CSS work by associates styles with HTML elements Selector decoration -> properties value This rule applies to all paragraphs, denoted by the //**p** tag//. p { font-family: Arial; } {{:modules:46376:css.png?nolink&450|}} There can be multiple rules font-family: Arial, Verdana, sans-serif; ===== CSS - Internal CSS ===== Using Internal CSS ===== CSS SELECTORS ===== ^ Universal| * {} | ^ Type| h1, h2, h3 {} | ^ Class| **.**note {} p**.**note{} | ^ ID| #introduction{} | ===== CSS - Foreground Color ===== h1{ color: cyan; } h2{ color: #00ffff; } h3{ color: rgb(0,255.255); } h4{ color: rgba(100, 100, 90, 0.5) } https://www.w3schools.com/colors/colors_names.asp ===== Typeface ===== * SERIF * SANS-SERIF * monospace **Font size** * font-size: 200%; * font-size: 2em; * Font-size: 12px; Specify a font type not installed on a computer by specifying a url. @font-face{ font-family: ‘ChunkyFiveRegular’; src: url(‘fonts/chuckfive.eot’); } * text-transform:uppercase; # or lowercase or capatilize * text-decoration: underline; * text-decoration: none; * text-indent: 20px * text-shadow:1px 2px 0px #000000; # right, down, blur, colour ==== Styling of links ==== {{:modules:46376:styling_of_links.png?nolink&300|}} ===== CSS Box Model ===== ==== CSS- Width and Height ==== {{:modules:46376:divs.png?nolink&300|}} * min-width:450px; * max-width:650px; * min-height:250px; * max-height:900px {{:modules:46376:min_max.png?nolink&300|}} ==== Overflow ==== * overflow:hidden; * overflow:scroll; {{:modules:46376:overflow.png?nolink&300|}} ==== border, margin, padding ==== {{:modules:46376:border_margin_padding.png?nolink&300|}} * border-width:2px * border-width:thick # thin and medium * border-width:1px 4px 4px 4px; # size for each side, clockwise starting top * border-style: double; # solid, dotted, dashed, groove, ridge, inset and outset * border-color: red; * border-color: red pink cyan black; # for each side * border:3px solid red; # border shorthand, must be in this order, size, style and colour * padding: 10px {{:modules:46376:borders.png?nolink&400|}} ==== Use inspector ==== {{ :modules:46376:inspactor.png?nolink |}} p{ text-align: center # left, right, justify } ==== Centering content ==== margin: 0 auto ====== Week 5 - Positioning with CSS and Introduction to JavaScript ====== ===== External refernces ===== * https://www.w3schools.com/cssref/pr_class_position.asp * https://www.w3schools.com/css/css_positioning.asp ===== CSS: Layout ===== * Block level elements begin on a new line * inline elements: exist between surrounding text ===== Css - positioning elements ===== * static (Normal Flow) * div {position: fixed;} * div{ position: relative;} * div{position: absolute;} Set the position property first then left or right ==== Fixed Positioning ==== * An element with position: fixed is positioned relative to the viewport or window * This means that it will stay in the same place even if the page is scrolled. * The top, right, bottom, and left properties are used to position the elements. * A fixed element does not leave a gap in the page where it would normally have been located. === CSS Code === .d1{ position: fixed; top: 20px; left: 50px; background-color: blue; } === HTML Code ===
This is DIV 1
==== Relative positioning ==== An element with position: relative is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element. === CSS Code === .d1{ position: relative; top: 30px; left: 10px; background-color: blue; } ==== Absolute Positioning ==== An element with position: absolute is positioned relative to the nearest positioned ancestor. If an absolute positioned ancestors, it uses the document body, and moves along with page scrolling. Parent container must have a position other than static === CSS Code === .d2 { position: absolute; top: 20px; background-solor: blue; } .d3 { positioning: relative; background-color: orange; } === HTML Code ===
This is DIV 3
This is DIV 2
===== Part 2- Float and Clear in CSS ===== * https://www.w3schools.com/cssref/pr_class_position.asp How to position block elements beside each other div{ float:left; clear:left } ==== CSS Code ==== .d1 { float: left; width 50px; height: 50px; background-color: red; } .d2 { float: left; width 50px; height: 50px; background-color: blue; } .d3 { clear: left; float: left; width 100px; background-color: orange; } ==== HTML Code ====
This is DIV 1
This is DIV 2
This is DIV 3
{{ :modules:46376:div_preview.png?nolink |}} ===== Part 3: Introduction to JavaScript ===== JavaScript is not Java. :-D Place the script tag after the closing HTML body tag ===== Part 4: The Basics of JavaScript ===== ==== Statements ==== Individual step in scripts are known as statements Statements should end with a smile-colon ; document.write(‘Welcome!’); ==== Comments ==== Comments explain the code Help you remember it and others understand it === multi-line comment === /* anything between these characters is a comment and will not be processed */ === single-line comments === // Anything after the two forward slashed // is also a comment and // will not be processed ==== Variables ==== Scripts often need to store bits of information temporarily in order to perform tasks. These bits of information - or data - are stored in **variables** ==== Declaring a variable ==== var quantity; // keyword -> variable name quantity = 3 ==== Data types ==== * Numbers * Strings * Booleans Javascript distinguishes between **number, string and true or false** values known as booleans. ^Numbers |no integers, logs, shorts or floats, just numbers stored as 64 bit double precisonion float.| ^Strings |enclosed in quotes or double quotes but they must match.| ^Boolean |true or false.| ==== Operators ==== ^Arithmetic|| ^Operator^Description^ |+ |Addition | |- |Subtraction | |* |Multiplication | |%%**%% |Exponentiation (ES2016) | |/ |Division | |% |Modulus (Division Remainder) | |++ |Increment | |-- |Decrement | ^Assignment||| ^Operator^Example^Same As^ |=| x = y | x = y | |+=| x += y |x = x + y | |-=| x -= y |x = x - y | |*=| x *= y |x = x * y | |/=| x /= y |x = x / y | |%=| x %= y |x = x % y | ^Comparison|| ^Operator^Description^ |== |equal to | |=== |equal value and equal type | |!= |not equal | |!== |not equal value or not equal type | |> |greater than | |< |less than | |>= |greater than or equal to | |%%<=%% |less than or equal to | |? |ternary operator | ^Logical|| ^Operator^Description^ |&& |logical and | |%%||%% |logical or | |! |logical not | Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number. ^Bitwise^^^^^^ ^Operator^Description^Example^Same as^Result^Decimal^ |& |AND |5 & 1 |0101 & 0001 |0001 | 1 | |%%|%%| OR |5 %%|%% 1 |0101 %%|%% 0001 |0101 | 5 | |~ |NOT |~ 5 |~0101 |1010 |10 | |%%^%% |XOR |5 %%^%% 1 |0101 %%^%% 0001 |0100 | 4 | |%%<<%% |Zero fill left shift |5 %%<<%% 1 |0101 %%<<%% 1 |1010 | 10 | |%%>>%% |Signed right shift |5 %%>>%% 1 |0101 %%>>%% 1 |0010| 2 | |%%>>>%% |Zero fill right shift |5 %%>>>%% 1 |0101 %%>>>%% 1 |0010 | 2 | Javascript uses mathematics to perform tasks var width = 3; var height = 2; area = width * height; ==== Concatenating strings ==== There is just one string operator: the + symbol. It is used to join strings on either side of it var greeting = “Hello”; var who = “world”; var message = greeting + who; ==== Basic input and output ==== // writes to the page document.write(‘Welcome!’); // popup with the message displayed alert(“my output here “); ==== Adding two numbers using a variable for result ==== var num1 = 3; var num2 = 4; var result= num1 +num2; document.write(result); var num1 = 3; var num2 = 4; document.write(num1 +num2); ==== Prompting the user for an input ==== // user input var myInput; myInput = prompt(“Please enter your name:”); // writes a string + input document.write(“Hello ” + myInput); ==== Asking for two numbers and then adding together ==== var num1; var num2; num1 = prompt(“Please enter first number”); num2 = prompt(“Please enter second number”); // convert to a number num1 = Number(num1); num2 = Number(num2); document.write(num1 +num2); var num1; var num2; num1 = Number(prompt(“Please enter first number”)); num2 = Number(prompt(“Please enter second number”)); document.write(num1 +num2); ====== Week 6 - Decisions and loops in Javascript ====== A script can do different things depending on what values it has been passed. ===== Making Decisions ===== **using if statements** // if score is greater than 40 if(score > 40){ document.write(‘you passed!’); } else { document.write(’Try again...!’); } ===== Comparison operators ===== == //is equal to != //is not equal to > //greater than < //Less than >= //greater than or equal to <= //Less than or equal to ==== Logical Operators ==== // && logical and if ( score > 75) && (score <95){ document.write(‘very good!’); } //|| logical or if ( score > 75) || (score <95){ document.write(‘very good!’); } // ! logical not ==== Loops ==== for(var i=0; i<3;i++){ document.write(i); } initialisation: var i=0 condition: i < 3 update: i++ ===== Decisions and Loops (Code example) ===== var myInput = Number(prompt(“please enter a score:”)); if (myInput > 40 ){ document.write(“You passed!”); } else { document.write(“Try again!”); } var numIn = Number(prompt(“Please enter a number:”)); for (var i = 1; i <= numIn; i++){ document.write(i + “
"); }
===== Functions ===== No numbers, no reserved words or variables for a function name Also it is common to use camelCase function sayHello(){ document.write(‘Hello’); } ===== Calling a function ===== sayHello(); function helloWorld(){ document.write("hello from a function!"); } helloWorld(); **Calling a function when a button is clicked** The function being called function helloWorld(){ document.write("hello from a function!"); } **A function being called when you click a button and an alert box appears ** function helloWorld(){ alert("hello from a function!"); } ===== Declaring a function that needs information ===== //parameters when defining the function: width, height function getArea(width, height){ document.write(width*height); } // arguments when calling the function (3, 5) getArea(3, 5); function getArea(width, height){ alert(width * height); } getArea(3, 5); ==== Using Variables ==== function getArea(width, height){ alert(width * height); } var num1 = 10; var num2 =6; getArea(num1, num2); ===== Returning from a function ===== function getArea(width, height){ return width * height; } function getArea(width, height){ return width * height; } var x = getArea(3, 9); alert(x); ====== Week 7 - The Document Object Model ====== {{:modules:screenshot_2019-03-07_at_07.51.16.png?600|}} To access and update the HTML, first you select the element(s), you want to work with. ===== Here are some of the ways to select elements ===== They are known as** DOM queries.** How to specify a heading in JavaScript?

This is my heading

This is another heading

This is yet another heading

Easiest way is to do this is to assign each one an ID **HTML**

This is my heading

This is another heading

This is yet another heading

**JavaScript** // get the element with an id of two document.getElementById("two"); ===== To access and update content you can use: ===== InnerHTML for text and markup value for input boxes {{:modules:screenshot_2019-03-07_at_07.58.34.png?600|}} ===== For an Input box ===== **HTML** **JavaScript** document.getElementById('inBox').value; {{:modules:screenshot_2019-03-07_at_08.00.23.png?600|}} ===== Part 1 : Intro to the DOM ===== Demo **HTML**

This is my first heading

This is my second heading

This is my third heading

**JavaScript** // get the element with an id of two and the title var x = document.getElementById("two").innerHTML; alert(x); ===== Part 2 : DOM query examples ===== Demo 2 **HTML**

**JavaScript** // gets input text when the button is clicked and updates the h1 function myName(){ var x = document.getElementById("in1").value; document.getElementById("result").innerHTML = "Hello" + x; } ===== Part 3: Styling with the DOM (A) ===== **Style** ==== DOM Query Selectors ==== **HTML**

My Article Heading

**JavaScript** document.getElementById("two").innerHTML; ==== changing Style ==== **HTML**

My Article Heading

**JavaScript** //targeting the color document.getElementById("two").style.color; ==== Changing the heading color ==== **HTML**

This is a Heading

**JavaScript** // change color to red function change(){ document.getElementById("one").style.color ="red"; } ===== Part 4: Styling with the DOM (B) ===== ==== Changing the background color ==== **HTML** **JavaScript** function changeBackground(){ document.getElementById("bdy").style.background ="yellow"; } ===== Part 5: Styling with the DOM (C) ===== **Demo** HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

JavaScript function change(){ document.getElemntByID("para").style.background="green"; document.getElemntByID("para").style.border="3px dashed red"; document.getElemntByID("para").style.fontfamily="Arial"; } ==== using a variable for document.getElemntByID ==== function change(){ var par = document.getElemntByID("para") para.style.background="green"; para.style.border="3px dashed red"; para.style.fontfamily="Arial"; para.style.boxShadow="10px 20px 30px grey"; } {{:modules:46376:pdf:week_8_excercise.pdf|}} ====== Week 8 - Working With JavaScript ====== ===== Part 1: Troubleshooting with the browser ===== This feature provides some information on troubleshooting your code using Chrome and other browsers External Resources: https://www.w3schools.com/js/js_debugging.asp ===== Part 2: Dynamic Typing in JavaScript ===== External Resources: https://www.w3schools.com/js/js_datatypes.asp \\ Strings in JavaScript: https://www.w3schools.com/js/js_strings.asp \\ Numbers in JavaScript: https://www.w3schools.com/js/js_numbers.asp \\ Booleans in JavaScript: https://www.w3schools.com/js/js_booleans.asp \\ ==== JavaScript Types ==== * Number * String * Boolean * Null * Undefined Java script used dynamically typed variables. __//Dynamically typed languages assigns variables a type at runtime based on the variables value at the time.//__ \\ __//Statically type languages specify what type a variable will use.//__ \\ Using the built in development console in web browsers to test JavaScript code. Right click and select developer console, (F12) {{ :modules:46376:chrome_console.jpg?nolink |}} {{ :modules:46376:edge_console.jpg?nolink |}} >myVar="Hello" <"Hello" >typeof myVar <"string" >myVar=true typeof myVar <"boolean" >num=0 <0 >num+=1 <1 ===== Part 3: Type Coercion In JavaScript ===== External Resources Coercion in JavaScript: https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839 \\ See chapter 1 of book Eloquent JavaScript for information on coercion in JavaScript: https://eloquentjavascript.net/01_values.html \\ >5+10 <15 >"Hello" + " World" <"Hello World" >5+"hello" <"5hello" >5+"10" <"510" >5*"10" <50 >5/"10" <0.5 >5-"10" <-5 >5-"Hello" >50+true <51 >50-true <49 >50-false <50 >50+false <50 >"Hello"+true <"Hellotrue" >"Hello"+false <"Hellofalse" ===== Part 4: Comparison Operators In JavaScript ===== External Resources Comparison Operators in JavaScript: https://www.w3schools.com/js/js_comparisons.asp \\ >4==4 4==41 4=="4" 4===4 4==="4" "4"==="4" 1==true 0==false 1===true 0===false 4!=5 5!="Hello" 4!="4" 4!=="4" {{:modules:46376:pdf:converting_to_numbers_in_javascript.pdf|}} ====== Week 9 - Introduction to D3 ====== ===== Part 1 - Introduction to D3.js ===== https://d3js.org/ ((https://gist.github.com/tomerd/1499279)) ((https://gist.github.com/paulinm/10556397)) Data-Driven Documents ==== D3.js - Overview ==== === Purpose === D3(Standing for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. **Capabilities** * Principal functions allow for selections, transitions an data-binding. * D3 can select elements in the DOM programmatically(can use instead of the verbose DOM API) * By declaring a transition, styles can be smoothly interpolated/animated over a certain time. * Large datasets(e.g JSON/XML format) can be easily bound to svg objects using simple D3.js functions to generate rich text/graphic charts and diagrams. **Technologies** * Built on top of common web standards liek HTML, CSS, JavaScript the DOM and SVG * Exportable nature of SVG enables graphics created by D3 to be used in print publications. **Origins** * Initially released in 2011(successor to the earlier Protovis framework) - Now used widely (e.g by the New York Times, OpenStreetMap etc.) * Recent version -v4 has big breaks in the API from previous versions ===== Part 2 - Introduction to SVGs and XML ===== Scalable Vector Graphics **D3.js - SVG** * SVG(Scalable Vector Graohics) is an XML format used for drawing * SVG also has a DOM - there are elements with parents and children and attributes, and you can respond to the same mouse/touch events * CSS styles and selectors can apply to SVG elements SVGs have the following structure: * The tag (with a closing tag) which will contain the graphics * Graphics are placed inside the tag. Standard shaped include: * Rectangle * Circle * Ellipse * Polygon * Path Demo: **You can use classes** .myClass {border:2px solid black} {{:modules:screenshot_2019-03-22_at_19.12.52.png?400|}} Use x to move from the left {{:modules:screenshot_2019-03-22_at_19.15.10.png?400|}} Use y to move from the top Document {{:modules:screenshot_2019-03-22_at_19.17.50.png?400|}} ===== Part 3 - Circles in SVGs ===== .myClass {border:2px solid black} {{:modules:screenshot_2019-03-22_at_19.20.57.png?400|}} **Stroke** {{:modules:screenshot_2019-03-22_at_19.22.26.png?400|}} ===== Part 4 - Using D3 to create SVGs ===== ==== Using D3 to create SVGs ==== * Include link reference to D3: Using D3.js to create elements * Create an SVG container in the HTML page * Access the SVG elements using an associated ID * The SVG can be targeted using a D3 selector in JavaScript: var svgConatiner = d3.select("#mySVG"); * Elements (such as a rectangle) can then be appended to the svg container: var myRectangle = svgContainer.append("rect"); The appended element can then have attributes set: myRectangle.attr("x",100 ); myRectangle.attr("y", 100); myRectangle.attr("height", 50 ); myRectangle.attr("width", 600 ); myRectangle.attr("fill", "orange" ); ===== Part 5 - D3: Select, Append, and Attr with method chaining ===== {{:modules:screenshot_2019-03-22_at_19.53.07.png?400|}} ==== Method chaining ==== {{:modules:screenshot_2019-03-22_at_19.52.03.png?400|}} {{:modules:screenshot_2019-03-22_at_19.56.59.png?400|}} {{:modules:screenshot_2019-03-22_at_19.58.44.png?400|}} {{:modules:screenshot_2019-03-22_at_20.00.23.png?400|}} ====== Week 10 - Arrays and External Data in D3 ====== ===== Appending an SVG to HTML elements =====
===== Introduction to Arrays ===== [[https://www.w3schools.com/js/js_arrays.asp]] * Store one or multiple element in one variable. * Each element is referred to by it's index. var colours = ['Pink','Yellow','Green'] 0: 'Pink' 1: 'Yellow' 2: 'Green' //refer to yellow like this: colours[1]; //some usefull method is arrays colours.length 3 ==== Samples of arrays is JavaScript ==== ===== Using Arrays to Generate SVG using D3 ===== ==== Using var for width ==== Home
{{:modules:screenshot_2019-03-29_at_08.19.47.png?200|}} ==== Looping through an array with .enter() ==== Home
{{:modules:screenshot_2019-03-29_at_08.34.02.png?400|}} ==== myRectangle.enter() ==== Home
{{:modules:screenshot_2019-03-29_at_08.41.11.png?400|}} ==== Importing a File Using D3 ==== * Create a CSV File * Create a Python web server * Import File ((http://learnjsdata.com/read_data.html)) * Output Result to SVG month,temp January,4 February,5 March,8 April,12 May,18 June,20 July,21 August,23 September,18 October,12 November,7 December,5 Document
==== csv ==== - Create a csv in excel - Create a folder "mypythonwebserver" - In terminal, type python -m http.server ((https://docs.python.org/3/library/http.server.html)) - start coding. save file to "mypythonwebserver" - To view file, open in localhost. e.g http://localhost:8000/d3.html Document
{{:modules:46376:upside_down_bargraph.jpg?nolink|}} ====== Week 11 - Charts and Labels in D3 ====== ===== Part 1- Baseline correction in D3 ===== Document
{{:modules:screenshot_2019-04-04_at_20.01.42.png?400|}} ===== Part 2 - Adding labels in D3 ===== Document
{{:modules:screenshot_2019-04-04_at_20.13.56.png?400|}} ===== Part 3 - Transitions and Styles in D3 ===== ==== Using CSS to add Style ==== Using CSS to style SVG rectangles on hover rect:hover{ fill:black;} Document
{{:modules:screenshot_2019-04-04_at_20.22.07.png?400|}} ==== Transitions in D3.js ==== D3's .transition() method allows for easy transitions from one state to another. Instead of applying changes instantaneously, transitions smoothly change from one state to a desired target state, over a given duration. Transitions are created using the following code: .transition() Using the .transition() in conjunction with the .duration() method allows us to specify the time taken to change from the starting state to the finishing state. The default value in 250 milliseconds. To change the default, a value is specified in the parentheses in the method, specifying the transition duration in milliseconds. Transitions durations are created using the following code: .transition(500) Document
====== Week 12 - Adding Scales and Axis in D3 ====== ===== Part 1 - Introduction to Scales in D3 ===== In D3, scales are functions that **map** from an //input domain// to an //output range//. var myScale = d3.scaleLinear(); //define the scale var myScale = d3.scaleLinear() .domain([0,600]) .range([0,600]); //using the scale myscale(400); ===== Part 2 - Creating Scales in D3 ===== {{:modules:46376:sales.csv|}} month,sales January,40 February,50 March,130 April,120 May,180 June,200 July,210 August,480 September,180 October,200 November,68 December,210 {{:modules:46376:svg_scaled1.jpg?nolink&200|}} No scaling so add the scaling code. var yScale =d3.scaleLinear() .domain([0,480]) .range([0,300]); {{:modules:46376:svg_scaled2.jpg?nolink&200|}} Then apply the scaling in one spot only myRectangle.enter() .append("rect") .attr("x",function(d,i){ return (50+(i*21)); }) .attr("y",function(d){ return 300-(d.sales); }) .attr("width",20) .attr("height",function(d){ return yScale(d.sales); }) .attr("fill","red"); }); {{:modules:46376:svg_scaled3.jpg?nolink&200|}} Then in both spots... myRectangle.enter() .append("rect") .attr("x",function(d,i){ return (50+(i*21)); }) .attr("y",function(d){ return 300-yScale(d.sales); }) .attr("width",20) .attr("height",function(d){ return yScale(d.sales); }) .attr("fill","red"); }); ==== Automatic Scaling ==== //Use the d3.max feature to find the biggest number in the list to use in automatic scaling.// //convert to numbers for d3.max to work properly in scaling data.forEach(function(d){ d.sales = Number(d.sales); }) // create a scale for y var yScale =d3.scaleLinear() .domain([0,d3.max(data, function(d){ return d.sales; })]) In order for this to work however, all the strings need to be converted to numbers first. See the code lines two and three to tae care of this. Then on line 7 use **d3.max()** and //function(d)// to set the max value for scaling taken automatically from the dataset. ==== Final Full Code ==== D3 Scaling
===== Part 3 - Creating Axes in D3 ===== This section covers the code to generate the axis on the graph. The code that is used to do this is as follow: var xAxis = d3.axixTop(); var xAxis = d3.axixBottom(); var yAxis = d3.axixLeft(); var yAxis = d3.axixRight(); Code to define the axis. var xAxis = d3.axisBotom() .scale(myScale); Now the axix needs to be positioned on the screen. Todo this we need to append the axis to the svg container. //append the axix to the svg container referincing the svg group **"g"** svg.append("g") .call(xAxis) now that the axix exist we need to add and start drawing it to the screen with **call(xAxis)** Position the axix using transformations. The translate values determines how many pixels to move the axis horizontally and vertically, so in example ten pixels from the left and 45 down. //append the axix to the svg container referincing the svg group **"g"** svg.append("g") .attr("transform", "translate(10, 45)") .call(xAxis) ==== Full Axis Code implemented ==== D3 Scaling
{{:modules:46376:svg_scaled4.jpg?nolink|}} ====== Week 13 - Allowing the user to specify chart settings ====== D3 Scaling Select chart height: Select chart color:
{{:modules:screenshot_2019-04-19_at_12.37.12.png?400|}}