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
Revision | Details of Modification(s) | Reason for modification | Date | By |
---|---|---|---|---|
0 | Draft release | 46376 - Web App Development | 2019/01/24 17:33 | Gerhard van der Linde |
HTML5 Browser compatibility testing - https://html5test.com
W3c validator Service: https://validator.w3.org/#validate_by_input
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
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
<!doctype html> <head> <title>My Web Page</title> </head> <body> <h1>The History of the World Wide Web</h1> <h3>Tim Berners Lee and the Development of HTML</h3> <p>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.</p> <h3>Precursors</h3> <p>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.</p> <h3>1980-1991: Invention and implementation of the Web</h3> <p>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.</p> </body> </html>
To open on in a new tab
target=“_blank”
<!DOCTYPE html> <html> <head> <title>My Table</title> </head> <body> <table border="3" cellpadding="5" cellspacing="0" align="center" bgcolor="yellow"> <tr> <th width="75">cell 1</th> <th width="75" bgcolor="grey">cell 2</th> <th width="75">cell 3</th> </tr> <tr align="center"> <td rowspan="2" bgcolor="red">cell 4</td> <td colspan="2"><a href="http:\\www.amazon.co.uk">cell 5</a></td> </tr> <tr align="center"> <td>cell 8</td> <td>cell 9</td> </tr> </table> </body> </html>
Related External Links
Information from W3C on URLs: https://www.w3.org/TR/WD-html40-970917/htmlweb.html
All files are in the same folder and referenced directly in links.
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.
# img is a void tag, no open and close, all inside tag <img src="images/pic1.jpg"> # alt tag <img src="images/pic1.jpg" alt="Picture Info"> #dimensions is pixels <img src="images/pic1.jpg" alt="Picture Info" width="100" height="100">
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 |
Related Resources Sample code for form controls provided underneath in related code
External Resources W3C resource on Form Controls
Related Resources
Related Resources
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; }
There can be multiple rules
font-family: Arial, Verdana, sans-serif;
<head> <title>Using Internal CSS</title> <style type=“text/css”> body{ font-family: arial; background-colour: yellow; } h1{ color:red; } </style> </head>
Universal | * {} |
---|---|
Type | h1, h2, h3 {} |
Class | .note {} p.note{} |
ID | #introduction{} |
h1{ color: cyan; } h2{ color: #00ffff; } h3{ color: rgb(0,255.255); } h4{ color: rgba(100, 100, 90, 0.5) }
Font size
Specify a font type not installed on a computer by specifying a url.
@font-face{ font-family: ‘ChunkyFiveRegular’; src: url(‘fonts/chuckfive.eot’); }
p{ text-align: center # left, right, justify }
margin: 0 auto
Set the position property first then left or right
.d1{ position: fixed; top: 20px; left: 50px; background-color: blue; }
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.
.d1{ position: relative; top: 30px; left: 10px; background-color: blue; }
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
.d2 { position: absolute; top: 20px; background-solor: blue; } .d3 { positioning: relative; background-color: orange; }
How to position block elements beside each other
div{ float:left; clear:left }
.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; }
<div class="d1"> This is DIV 1 </div> <div class="d2"> This is DIV 2 </div> <div class="d3"> This is DIV 3 </div>
JavaScript is not Java.
Place the script tag after the closing HTML body tag
<script> document.write(“Hello World!”); alert(“Hello again world”); </script>
<script> var myVar = “Hello from a variable”; document.write(myVar); </script>
Individual step in scripts are known as statements
Statements should end with a smile-colon ;
document.write(‘Welcome!’);
Comments explain the code
Help you remember it and others understand it
/* anything between these characters is a comment
and will not be processed */
// Anything after the two forward slashed // is also a comment and // will not be processed
Scripts often need to store bits of information temporarily in order to perform tasks.
These bits of information - or data - are stored in variables
var quantity; // keyword -> variable name quantity = 3
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. |
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;
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;
// writes to the page document.write(‘Welcome!’); // popup with the message displayed alert(“my output here “);
var num1 = 3; var num2 = 4; var result= num1 +num2; document.write(result);
var num1 = 3; var num2 = 4; document.write(num1 +num2);
// user input var myInput; myInput = prompt(“Please enter your name:”); // writes a string + input document.write(“Hello ” + myInput);
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);
A script can do different things depending on what values it has been passed.
using if statements
// if score is greater than 40 if(score > 40){ document.write(‘you passed!’); } else { document.write(’Try again...!’); }
== //is equal to != //is not equal to > //greater than < //Less than >= //greater than or equal to <= //Less than or equal to
// && logical and if ( score > 75) && (score <95){ document.write(‘very good!’); } //|| logical or if ( score > 75) || (score <95){ document.write(‘very good!’); } // ! logical not
for(var i=0; i<3;i++){ document.write(i); }
initialisation: var i=0 condition: i < 3 update: i++
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 + “<br>"); }
No numbers, no reserved words or variables for a function name
Also it is common to use camelCase
function sayHello(){ document.write(‘Hello’); }
sayHello();
function helloWorld(){ document.write("hello from a function!"); } helloWorld();
Calling a function when a button is clicked
<button type="button" name="button" onclick="helloWorld()">Click me!</button>
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
<button type="button" name="button" onclick="helloWorld()">Click me!</button>
function helloWorld(){ alert("hello from a function!"); }
//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);
function getArea(width, height){ alert(width * height); } var num1 = 10; var num2 =6; getArea(num1, num2);
function getArea(width, height){ return width * height; }
function getArea(width, height){ return width * height; } var x = getArea(3, 9); alert(x);
They are known as DOM queries.
How to specify a heading in JavaScript?
<h1>This is my heading</h1> <h1>This is another heading</h1> <h1>This is yet another heading</h1>
Easiest way is to do this is to assign each one an ID
HTML
<h1 id="one">This is my heading</h1> <h1 id="two">This is another heading</h1> <h1 id="three">This is yet another heading</h1>
JavaScript
// get the element with an id of two document.getElementById("two");
Demo
HTML
<h1>This is my first heading</h1> <h1 id="two">This is my second heading</h1> <h1>This is my third heading</h1>
JavaScript
// get the element with an id of two and the title var x = document.getElementById("two").innerHTML; alert(x);
Demo 2
HTML
<input id="in1"> <button onclick="myName()">Check name</button> <h1 id="result"></h1>
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; }
Style
HTML
<h1 id="two">My Article Heading</h1>
JavaScript
//targeting the color document.getElementById("two").style.color;
HTML
<h1 id="one">This is a Heading</h1> <button onclick="change()">Change to red</button>
JavaScript
// change color to red function change(){ document.getElementById("one").style.color ="red"; }
HTML
<body id="bdy"> <button onclick="changeBackground()">Change background</button> </body>
JavaScript
function changeBackground(){ document.getElementById("bdy").style.background ="yellow"; }
Demo
HTML
<p id="para"> 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. </p> <button onclick="change()">Change me</button>
JavaScript
function change(){ document.getElemntByID("para").style.background="green"; document.getElemntByID("para").style.border="3px dashed red"; document.getElemntByID("para").style.fontfamily="Arial"; }
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"; }
This feature provides some information on troubleshooting your code using Chrome and other browsers
External Resources: https://www.w3schools.com/js/js_debugging.asp
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
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)
>myVar="Hello" <"Hello" >typeof myVar <"string" >myVar=true <true >typeof myVar <"boolean" >num=0 <0 >num+=1 <1
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" <NaN
>50+true <51 >50-true <49 >50-false <50 >50+false <50 >"Hello"+true <"Hellotrue" >"Hello"+false <"Hellofalse"
External Resources
Comparison Operators in JavaScript: https://www.w3schools.com/js/js_comparisons.asp
>4==4 <true >4==41 <false >4=="4" <true >4===4 <true >4==="4" <false >"4"==="4" <true >1==true <true >0==false <true >1===true <false >0===false <false >4!=5 <true >5!="Hello" <true >4!="4" <false >4!=="4" <true
https://d3js.org/ 2) 3) Data-Driven Documents
D3(Standing for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers.
Capabilities
Technologies
Origins
Scalable Vector Graphics
D3.js - SVG
SVGs have the following structure:
</code>
Demo:
<svg width="1000" height="500"> <rect width="50" height="20" fill="red"/> </svg>
You can use classes
.myClass {border:2px solid black}
<svg class="myClass" width="1000" height="500"> <rect width="500" height="200" fill="red"/> </svg>
Use x to move from the left
<svg class="myClass" width="1000" height="500"> <rect x="100" width="500" height="200" fill="red"/> </svg>
Use y to move from the top
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Document</title> <style type="text/css"> .myClass {border:2px solid black} </style> </head> <body> <svg class="myClass" width="700" height="500"> <rect x="10" y="10" width="500" height="200" fill="red"/> <rect x="60" y="180" width="500" height="200" fill="blue"/> </svg </body> </html>
.myClass {border:2px solid black}
<svg width="1000" height="1000" class="myClass"> <circle r="50" cy="100" cx="200" fill="green" /> </svg>
Stroke
<svg width="1000" height="1000" class="myClass"> <circle r="50" stroke="blue" stroke-width="20" cy="100" cx="200" fill="green" /> </svg>
<script src="https//d3js.org/d3.v5.min.js"></script>
Using D3.js to create elements
<svg width="1000" height="1000" id="mySVG">
var svgConatiner = d3.select("#mySVG");
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" );
<!DOCTYPE html> <html> <head> <script src="https//d3js.org/d3.v5.min.js"></script> </head> <body> <svg width="1000" height="1000" id="mySvg"> </svg> </body> </html> <script> var svgContainer = d3.select("#mySvg"); var myRectangle = svgContainer.append("rect"); myRectangle.attr("x", 100); myRectangle.attr("y", 100); myRectangle.attr("height", 50); myRectangle.attr("width", 200); myRectangle.attr("fill", "orange"); </script>
<!DOCTYPE html> <html> <head> <script src="https//d3js.org/d3.v5.min.js"></script> </head> <body> <svg width="1000" height="1000" id="mySvg"> </svg> </body> </html> <script> var svgContainer = d3.select("#mySvg"); //method chaining var myRectangle = svgContainer.append("rect") .attr("x", 100) .attr("y", 300) .attr("height", 15) .attr("width", 200) .attr("fill", "green"); </script>
<!DOCTYPE html> <html> <head> <script src="https//d3js.org/d3.v5.min.js"></script> </head> <body> <svg width="1000" height="1000" id="mySvg"> </svg> </body> </html> <script> var svgContainer = d3.select("#mySvg"); //method chaining var myRectangle = svgContainer.append("rect") .attr("x", 100) .attr("y", 300) .attr("height", 15) .attr("width", 200) .attr("fill", "green"); var myCircle = svgContainer.append("circle") .attr("cx", 100) .attr("cy", 300) .attr("r", 250) .attr("fill", "Blue"); </script>
<!DOCTYPE html> <html> <head> <script src="https//d3js.org/d3.v5.min.js"></script> </head> <body> <svg width="1000" height="1000" id="mySvg"> </svg> </body> </html> <script> var svgContainer = d3.select("#mySvg"); //method chaining var myRectangle = svgContainer.append("rect") .attr("x", 100) .attr("y", 300) .attr("height", 15) .attr("width", 200) .attr("fill", "green"); var myCircle = svgContainer.append("circle") .attr("cx", 100) .attr("cy", 300) .attr("r", 250) .attr("fill", "Blue"); .attr("stroke", "yellow"); .attr("stroke-width", 20); </script>
<!DOCTYPE html> <html> <head> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <svg width="800" height="800" id="mySvg"> </svg> </body> </html> <script> var svgContainer = d3.select("#mySvg"); //method chaining var myRectangle = svgContainer.append("rect") .attr("x", 200) .attr("y", 450) .attr("height", 15) .attr("width", 200) .attr("fill", "green"); var myCircle = svgContainer.append("circle") .attr("cx", 180) .attr("cy", 300) .attr("r", 150) .attr("fill", "Blue") .attr("stroke", "yellow") .attr("stroke-width", 20); //myRectangle.attr("fill", "Black"); </script>
<!doctype html> <html lang="en"> <head> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <div id="svg_area"></div> </body> <script> var svgContainer = d3.select("#svg_area").append("svg") .attr("height", 800) .attr("width", 800); var myRectangle = svgContainer.append("rect") .attr("x",50) .attr("y",50) .attr("height",100) .attr("width",100) .attr("fill","blue"); </script> </html>
https://www.w3schools.com/js/js_arrays.asp
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
<script> var myVar = 10; var myArray = [1,2,3,4,5,6,7,8,9,10]; alert(myArray[10]); </script>
<!doctype html> <html> <title>Home</title> <script src="https://d3js.org/d3.v5.js"></script> </head> <body> <div id="svg_area"></div> </body> </html> <script type="text/javascript"> var myVar = 600; var svgContainer = d3.select("#svg_area").append("svg") .attr("height", 800) .attr("width", 800); var myRectangle = svgContainer.append("rect") .attr("x", 50) .attr("y", 50) .attr("height", 100) .attr("width", myVar) .attr("fill", "blue"); </script>
<!doctype html> <html> <head> <title>Home</title> <script src="https://d3js.org/d3.v5.js"></script> </head> <body> <div id="myDiv"></div> </body> </html> <script type="text/javascript"> var myArray = [10, 22, 14, 16, 19, 9]; let svgContainer = d3.select("#myDiv").append("svg") .attr("height", 1000) .attr("width", 1000); let circles = svgContainer.selectAll('circle') .data(myArray); // enter loops through circles.enter() .append("circle") // function will run and returns i (the index value of the array) .attr("cx", function(d, i){return 50 + (i*50);}) .attr("cy", 50) .attr("r", function(d){return d;}) .attr("fill", "blue"); </script>
<!doctype html> <html> <head> <title>Home</title> <script src="https://d3js.org/d3.v5.js"></script> </head> <body> <div id="myDiv"></div> </body> </html> <script type="text/javascript"> var myArray = [100, 220, 20, 160, 190, 90, 320]; let svgContainer = d3.select("#myDiv").append("svg") .attr("height", 1000) .attr("width", 1000); let myRectangle = svgContainer.selectAll('rect') .data(myArray); // enter loops through myRectangle.enter() .append("rect") // function will run and returns i (the index value of the array) // d = data, i = index .attr("x", function(d, i){return 50 + (i*110);}) .attr("y", 50) .attr("width", 100) .attr("height", function(d){return d;}) .attr("fill", "blue"); </script>
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
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <div id="myDiv"></div> </body> <script> d3.csv("temp_data.csv").then(function(data) { console.log(data); }); </script> </html>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <div id="myDiv"></div> <script type="text/javascript"> // import the data d3.csv("temp_data.csv").then(function(data) { console.log(data); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 800) .attr("height", 800); // create a variable and select all rectangles in svg containe as associate with data let myRectangle = svgContainer.selectAll("rect") .data(data); // using d3 enter method to add rectangles myRectangle.enter() .append("rect") .attr("x",function(d, i){ return 50 + (i*21); }) .attr("y", 50) .attr("width", 20) .attr("height",function(d){ return d.temp * 10; }) //.attr("fill", "red"); .attr("fill", function(d){ if(d.temp <=10) {return "blue";} else if (d.temp<=15){return "green";} else if (d.temp <=20){return "orange";} else {return "red";}}); }); </script> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <div id="myDiv"></div> <script type="text/javascript"> //d3.csv("temp_data.csv").then(function(data) // import the data d3.csv("temp_data.csv").then(function(data) { console.log(data); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 800) .attr("height", 800); // create a variable and select all rectangles in svg containe as associate with data let myRectangle = svgContainer.selectAll("rect") .data(data); // using d3 enter method to add rectangles myRectangle.enter() .append("rect") .attr("x",function(d, i){ return 50 + (i*21); }) .attr("y", function(d){ return 300 - (d.temp *10); }) .attr("width", 20) .attr("height",function(d){ return d.temp * 10; }) //.attr("fill", "red"); .attr("fill", function(d){ if(d.temp <=10) {return "blue";} else if (d.temp<=15){return "green";} else if (d.temp <=20){return "orange";} else {return "red";}}); }); </script> </body> </html>
<!doctype html> <html lang ="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://d3js.org/d3.v5.js"></script> </head> <body> <div id="myDiv"></div> </body> <script type="text/javascript"> //d3.csv("temp_data.csv").then(function(data) // import the data d3.csv("temp_data.csv").then(function(data) { console.log(data); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 800) .attr("height", 800); // create a variable and select all rectangles in svg containe as associate with data let myRectangle = svgContainer.selectAll("rect") .data(data); // using d3 enter method to add rectangles myRectangle.enter() .append("rect") .attr("x",function(d, i){ return 50 + (i*41); }) .attr("y", function(d){ return 300 - (d.temp *10); }) .attr("width", 40) .attr("height",function(d){ return d.temp * 10; }) //.attr("fill", "red"); .attr("fill", function(d){ if(d.temp <=10) {return "blue";} else if (d.temp<=15){return "green";} else if (d.temp <=20){return "orange";} else {return "red";} }); // Add label text for bar chart let mylabel = svgContainer.selectAll("text") .data(data); // using d3 enter method to add rectangles mylabel.enter() .append("text") .attr("x",function(d, i){ return 70 + (i*41); }) .attr("y", function(d){ return 320 - (d.temp *10); }) .attr("text-anchor", "middle") .attr("font-family", "sans-serif") .attr("font-size", "20px") .attr("fill", "white") .text(function(d){ return d.temp + " \u00B0"; }); }); </script> </html>
Using CSS to style SVG rectangles on hover
rect:hover{ fill:black;}
<!doctype html> <html lang ="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://d3js.org/d3.v5.js"></script> <style> rect:hover{ fill:black; } </style> </head> <body> <div id="myDiv"></div> </body> <script type="text/javascript"> //d3.csv("temp_data.csv").then(function(data) // import the data d3.csv("temp_data.csv").then(function(data) { console.log(data); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 800) .attr("height", 800); // create a variable and select all rectangles in svg containe as associate with data let myRectangle = svgContainer.selectAll("rect") .data(data); // using d3 enter method to add rectangles myRectangle.enter() .append("rect") .attr("x",function(d, i){ return 50 + (i*41); }) .attr("y", function(d){ return 300 - (d.temp *10); }) .attr("width", 40) .attr("height",function(d){ return d.temp * 10; }) //.attr("fill", "red"); .attr("fill", function(d){ if(d.temp <=10) {return "blue";} else if (d.temp<=15){return "green";} else if (d.temp <=20){return "orange";} else {return "red";} }); // Add label text for bar chart let mylabel = svgContainer.selectAll("text") .data(data); // using d3 enter method to add rectangles mylabel.enter() .append("text") .attr("x",function(d, i){ return 70 + (i*41); }) .attr("y", function(d){ return 320 - (d.temp *10); }) .attr("text-anchor", "middle") .attr("font-family", "sans-serif") .attr("font-size", "20px") .attr("fill", "white") .text(function(d){ return d.temp + " \u00B0"; }); }); </script> </html>
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)
<!doctype html> <html lang ="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://d3js.org/d3.v5.js"></script> <style> rect:hover{ fill:black; } </style> </head> <body> <div id="myDiv"></div> </body> <script type="text/javascript"> //d3.csv("temp_data.csv").then(function(data) // import the data d3.csv("temp_data.csv").then(function(data) { console.log(data); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 800) .attr("height", 800); // create a variable and select all rectangles in svg containe as associate with data let myRectangle = svgContainer.selectAll("rect") .data(data); // using d3 enter method to add rectangles myRectangle.enter() .append("rect") // start of transition .attr("fill", "black") .attr("x",function(d, i){ return 50 + (i*41); }) .attr("y", 300) .attr("width", 300) .transition() .duration(1000) // end of transition .attr("x",function(d, i){ return 50 + (i*41); }) .attr("y", function(d){ return 300 - (d.temp *10); }) .attr("width", 40) .attr("height",function(d){ return d.temp * 10; }) //.attr("fill", "red"); .attr("fill", function(d){ if(d.temp <=10) {return "blue";} else if (d.temp<=15){return "green";} else if (d.temp <=20){return "orange";} else {return "red";} }); // Add label text for bar chart let mylabel = svgContainer.selectAll("text") .data(data); // using d3 enter method to add rectangles mylabel.enter() .append("text") .attr("x",function(d, i){ return 70 + (i*41); }) .attr("y", 300) .transition() .duration(3000) .attr("x",function(d, i){ return 70 + (i*41); }) .attr("y", function(d){ return 320 - (d.temp *10); }) .attr("text-anchor", "middle") .attr("font-family", "sans-serif") .attr("font-size", "20px") .attr("fill", "white") .text(function(d){ return d.temp + " \u00B0"; }); }); </script> </html>
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);
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
No scaling so add the scaling code.
var yScale =d3.scaleLinear() .domain([0,480]) .range([0,300]);
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"); });
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"); });
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.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>D3 Scaling</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <div id="myDiv"></div> <script type="text/javascript"> // import the sales data d3.csv("sales.csv").then(function(data) { console.log(data); // create a scale for y var yScale =d3.scaleLinear() .domain([0,480]) .range([0,300]); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 1000) .attr("height", 1000); //ceate a rectangle var myRectangle = svgContainer.selectAll("rect") .data(data); //add attributes to rectangle 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"); }); </script> </body> </html>
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)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>D3 Scaling</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <div id="myDiv"></div> <script type="text/javascript"> // import the sales data d3.csv("sales.csv").then(function(data) { console.log(data); //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; })]) .range([300,0]); //create y Axis var yAxis = d3.axisLeft() .scale(yScale) // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 1000) .attr("height", 1000); //ceate a rectangle var myRectangle = svgContainer.selectAll("rect") .data(data); //add attributes to rectangle myRectangle.enter() .append("rect") .attr("x",function(d,i){ return (50+(i*21)); }) .attr("y",function(d){ return yScale(d.sales); }) .attr("width",20) .attr("height",function(d){ return 300-yScale(d.sales); }) .attr("fill","red"); //To ensure that the axis is shown on top we do it here after the bars are drawn //We will be appending "svgContainer" declared above on line 28 svgContainer.append("g") .attr("transform", "translate(45,0)") .call(yAxis); }); </script> </body> </html>
<!doctype html> <html lang ="en"> <head> <meta charset="UTF-8"> <title>D3 Scaling</title> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> Select chart height: <select name="" id="chartHeight"> <option value="300">300 pixels</option> <option value="600">600 pixels</option> <option value="900">900 pixels</option> </select> Select chart color: <input type="color" id="colorPicker"> <button onclick="drawChart()">Draw Chart</button> <div id="myDiv"></div> </body> <script type="text/javascript"> function drawChart(){ // import the sales data d3.csv("sales.csv").then(function(data) { console.log(data); // values for bar chart var height = document.getElementById('chartHeight').value; var width = 600; var dataCount = data.length; var gap = 2; var chartColor = document.getElementById('colorPicker').value; //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; })]) .range([height,0]); // create a scale for x var xScale = d3.scaleBand() .domain(data.map(function(d){ return d.month; })) .range([0, width]) //create y Axis var yAxis = d3.axisLeft() .scale(yScale) //create y Axis var xAxis = d3.axisBottom() .scale(xScale); //removes previous code d3.select("#myDiv").selectAll("*").remove(); // create the svg container using d3 select, append svg to div above let svgContainer = d3.select("#myDiv").append("svg") .attr("width", 1000) .attr("height", 1000); //ceate a rectangle var myRectangle = svgContainer.selectAll("rect") .data(data); //add attributes to rectangle myRectangle.enter() .append("rect") .attr("x",function(d,i){ return (50+(i*(width/dataCount))); }) .attr("y",function(d){ return yScale(d.sales); }) .attr("width",(width/dataCount -gap)) .attr("height",function(d){ return height-yScale(d.sales); }) .attr("fill",chartColor); //To ensure that the axis is shown on top we do it here after the bars are drawn //We will be appending "svgContainer" declared above on line 28 svgContainer.append("g") .attr("transform", "translate(45,0)") .call(yAxis); svgContainer.append("g") .attr("transform", "translate(50," +height+")") .call(xAxis) .selectAll("text") .attr("transform", "rotate(60)") .attr("text-anchor", "start") .attr("x", "9") .attr("y", "3"); }); } </script> </html>