Programming in HTML5 with Javascript and CSS3 Flashcards
- npm install
- npm install -g
- installs locally
- installs globally
Class : blueprint of an object
Object: instance of a class
jQuery promises
- always( )
- done( )
- fail( )
- progress( )
REST
Representational state transfer
- Post (create)
- Get
- Put (update)
- Delete
AJAX
Asynchronous Javascript and XML
- XSS
- CORS
- Cross-site scripting
- Cross origin resource sharing
- rel
- lang
- relation
- language
- tr
- td
- th
- row
- detail
- header
- var jsonObject = JSON.parse(xmlhttp.response);
- result.innerHTML = jsonObject.result;
- The response string needs to be converted to an object and the JSON.parse method can accomplish the task
- In addition, the URL must be pieced together by taking the values from text boxes to build this QueryString
- var xmlhttp=new XMLHttpRequest();
- xmlhttp.open(“GET”,”/addition?x=5&y=10”,false);
- xmlhttp.send();
- var xmlDoc=xmlhttp.responseXML;
- The first line creates a new XMLHttpRequest object and assigns it to the xmlhttp variable.
- The next line sets up the request to use the GET method with a relative URL of /addition and QueryString of x=5&y=10.
- The last parameter (false) indicates whether the operation is to be performed asynchronously when false means that operation is synchronous.
padding: 5px 15px;
- 5px for the top and the bottom
- 15 px for the right and the left
AJAX codes
- 0 Uninitialized The open method has not been called yet.
- 1 Loading The send method has not been called yet.
- 2 Loaded The send method has been called; headers and status are available.
- 3 Interactive Downloading; the response properties hold the partial data.
- 4 Completed All operations are finished.
Handling errors
- xmlhttp.addEventListener(“error”, failed, false);
- xmlhttp.addEventListener(“abort”, canceled, false);
- function transferFailed(evt) {
- alert(“An error occurred”);
- }
- function canceled(evt) {
- alert(“canceled by the user”);
- }
Progress event
- xmlhttp.addEventListener(“progress”, updateProgress, false);
- function updateProgress(evt) {
- if (evt.lengthComputable) {
- var percentComplete = evt.loaded / evt.total;
- //display percenComplete
- } else {
- // Need total size to compute progress
- }
- }
Promise object
The promise object has the done, fail, always, and progress methods that accept
a function parameter, which enables you to subscribe to state change. The then()
method on the promise object enables you to subscribe to done, fail, and progress
Deferred object
The deferred object is a wrapper for the promise object. The deferred object provides control of the promise object, which is read-only
$.when() method
Use the $.when() method to monitor the completion of many parallel asynchronous
calls. Use the $.when() method with no parameters to create a resolved promise object
A web worker
A web worker provides asynchronous code execution
TCP
Transmission Control Protocol
URL
Uniform Resource Locator
URI
Uniform resource identifier
- ws://
- wss://
- Websocket
- Secure websocket
- http://
- https://
- Hypertext Transfer Protocol
- Secure Hypertext Transfer Protocol
The readyState property contains one of the following values
- CONNECTING = 0 Connection is not yet open
- OPEN = 1 Connection is open and ready to communicate
- CLOSING = 2 Connection is in the process of closing
- CLOSED = 3 Connection is closed or couldn’t be opened
WebSocket protocol
The WebSocket protocol provides a standardized way for the server to send content to the browser without being solicited by the client, and it allows messages to be passed back and forth while keeping the connection open
MIME types
- Multipurpose Internet Mail Extensions
- Content-types
Codec
A codec is a device or computer program capable of encoding or decoding a digital data stream or signal
The four parameters of the rect method
The first and second parameters are the x and y coordinates of the upper-left
corner of the rectangle. The third parameter is the width, and the fourth parameter is the height
SVG
Scalable Vector Graphics
JSON
Javascript Object Notation
API
Application Program Interface
UI
User Interface
- article
- aside
- figcaption
- figure
- footer
- header
- hgroup
- mark (highlighted text)
- nav
- progress
- section
body > article
article > section
- figure
- figcaption
- for images
- for captions
- getElementById
- getElementsByClassName
- getElementsByTagName
- querySelector
- querySelectorAll
- Gets an individual element on the page by its unique id attribute value
- Gets all the elements that have the specified CSS class applied to them
- Gets all the elements of the page that have the specified tag name or element name
- Gets the first child element found that matches the provided CSS selector criteria
- Gets all the child elements that match the provided CSS selector criteria
window.onload = function ()
Tells the runtime to run your code after the window finishes loading
querySelector
The querySelector method returns the first element it finds that matches the selector criteria passed to it
querySelectorAll
The querySelectorAll method returns all elements that match the selector criteria passed in
appendChild
Use this method to add a new HTML element to the collection of child elements belonging to the calling container
- childNodes
- first child
- lastChild
- hasChildNodes
- A collection of all child nodes of the parent element
- A reference to the very first child node in the list of child nodes of the parent node
- A reference to the very last child node in the list of the child nodes of the parent node
- A useful property that returns true if the parent element has any child nodes at all. A good practice is to check this property before accessing other properties, such as firstChild or lastChild
- beginPath
- moveTo
- lineTo
- stroke
- lineWidth
- strokeStyle
- Resets/begins a new drawing path
- Moves the context to the point set in the beginPath method
- Sets the destination end point for the line
- Strokes the line, which makes the line visible
- Accepts a value that determines the line width
- Lets you change the line color
- arc
- quadradicCurveTo
- bezierCurveTo
- A standard arc based on a starting and ending angle and a defined radius
- A more complex arc that allows you to control the steepness of the curve
- Another complex arc that you can skew
- X, Y
- radius
- startAngle, endAngle
- counterclockwise
- The first two parameters are the X and Y coordinates for the center of the circle
- The third parameter is the radius. This is the length of the distance from the
center point of the circle to the curve - The fourth and fifth parameters specify the starting and ending angles of the arc to be drawn. This is measured in radians, not in degrees
- The final parameter specifies the drawing direction of the arc
context.transform(a,b,c,d,e,f);
- a Scales the drawing horizontally
- b Skew the the drawing horizontally
- c Skew the the drawing vertically
- d Scales the drawing vertically
- e Moves the the drawing horizontally
- f Moves the the drawing vertically
style
style=”property:value”
ex.: style=”font-style:italic”
Geolocation API functions
- watchPosition
- getCurrentPosition
Hide an element
style=”display:none”
Mutiple columns
- columns: column-count column-width
- ex.: columns: 2 auto;
Drop shadow
- box-shadow: vertical offset horizontal offset blur distance color value;
- ex.: box-shadow: 10px 10px 20px black;
- text-shadow: h-shadow v-shadow blur-radius color | none | initial | inherit;
CSS style set
The element that occurs last will be applied
Variables declared in the global namespace will be parsed before functions
Variables declared in functions need to be declared before they are invoqued
Focus on an element
element.focus();
Rectangle method
- .rect(x, y, width, height);
- .fillRect(x, y, width, height);
- Rotate
- Translate
- Skew
- Scale
- transform: rotate(90deg);
- transform: translate(50px,0px);
- transform: skew(10deg, 10deg);
- transform: scale(1.5);
Display or hide
- style.display = ‘none’;
- style.display == ‘inline’
- visible
- hidden
- collapse
- inherit
- Sets the property to visible to show the element
- Hides the element
- Collapses the element where applicable, such as in a table row
- Inherits the value of the visibility property from the parent
Web Storage API
- Local storage is persistent
- Session storage is available only for the duration of
- the current session
- setItem
- getItem
- clear
- key
- removeItem
- Adds a key/value pair into storage. If no item with the specified key exists, the item is added; if that key does exist, its value is updated
- Retrieves data from storage based on a specified key value or index
- Clears all storage that has been saved. Use this method to clear out the storage as needed
- Retrieves the key at a specified index. You can use the resultant key to pass as a parameter to one of the other methods that accepts a key
- Removes the specified key/value pair from storage
Add to storage as a string
JSON.stringify();
- AppCache API
- AppCache manifest
- Use to make offline application
- html manifest=”webApp.appcache”
- Geolocation
- Three methods
- window.navigator.geolocation;
- getCurrentPosition, watchPosition, and clearWatch
Program flow
- Conditional program flow is based on evaluating state to make a decision as to which code should run
- Iterative flow is the ability to process lists or collections of information systematically and consistently
- Behavioral flow can be defined as an event or callback in which specific logic should be applied based on user engagement with the web application or the completion of another task
Ternary operation
expression ? true part: false part
indexOf default value
- 1
Array methods
- concat
- indexOf
- join
- reverse
- slice
- splice
- pop
- push
- shift
- unshift
readyState
- OPEN
- CONNECTING
- CLOSING
- CLOSED
- The connection is open
- The connection is in the process of connecting and not ready for use yet. This is the default value
- The connection is in the process of being closed
- The connection is closed
- $.ajax({
- url: searchPath,
- cache: false,
- dataType: “xml”,
- success: function (data) {
- $(data).find(“fruit”).each(
- function () {
- $(‘#searchResults’).append($(this).text());
- $(‘#searchResults’).append(“
“);
- })
- $(data).find(“fruit”).each(
- }
- });
- error: function (xhr, textStatus, errorThrown) {
- $(‘#searchResults’).append(errorThrown);
- }
type: “POST”
- $.ajax({
- url: searchPath,
- cache: false,
- dataType: “xml”,
- type: “POST”,
- success: function (data) {
- …
- },
- });
Syntax for an anonymous function
function (n,n,…,n) { body };
- When ready
- When clicked
- $(“document”).ready( function () {…
- $(“#Button1”).click( function () {…
WebSockets provide bidirectional communication with a server
WebSockets support both non-secure (ws) and secure (wss) connections to the server
- window.onload = function () {
- //do event setup in here.
- }
Anonymous function that executes after the page is loaded
- Bubbling: false
- Bubbling: true (cascading)
- To prevent
- The event travels outwards
- The event travels inwards
- window.event.cancelBubble = true;
- focus
- blur
- focusin
- focusout
- Raised when the element receives the focus
- Raised when the element loses the focus
- Raised just before an element receives the focus
- Raised just before an element loses the focus
Creating custom events
- myEvent = new CustomEvent(
- “anAction”,
- {
- detail: { description: “a description of the event”,
- timeofevent: new Date(),
- eventcode: 2 },
- bubbles: true,
- cancelable: true
- detail: { description: “a description of the event”,
- }
- );
Create a new web worker
var webWorker = new Worker(“workercode.js”);
placeholder
input type=”” placeholder=””
- ^ The caret character denotes the beginning of a string
- $ The dollar sign denotes the end of a string
- . The period indicates to match on any character
- [A-Z] Alphabet letters indicate to match any alphabetic character. This is case-sensitive. To match lowercase letters, use [a-z]
- \d This combination indicates to match any numeric character
- The plus sign denotes that the preceding character or character set must match at least once
- * The asterisk denotes that the preceding character or character set might or might not match
- [^] When included in a character set, the caret denotes a negation. [^a] would match a string that doesn’t have an ‘a’ in it
- ? The question mark denotes that the preceding character is optional
- \w This combination indicates to match a word character consisting of any alphanumeric character, including an underscore
- \ The backslash is an escape character. If any special character should be included in the character set to match on literally, it needs to be escaped with a . For example, to find a backslash in a string, the pattern would include \.
- \s This combination indicates to match on a space. When it’s combined with + or *, it can match on one or more spaces
Expression
To be place inside forward slashes / /
JSON:
{firstName: “Rick”, lastName: “Delorme”, hairColor: “brown”, eyeColor: “brown” }
- XML (Elements):
- Person
- firstName Rick firstName
- lastName Delorme lastName
- hairColor Brown hairColor
- eyeColor Brown eyeColor
- Person
XMLHttpRequest
- script
- $(“document”).ready(function () {
- $(“#btnGetXMLData”).click(function () {
- var xReq = new XMLHttpRequest();
- xReq.open(“GET”, “myXMLData.xml”, false);
- xReq.send(null);
- $(“#results”).text(xReq.response);
- });
- $(“#btnGetXMLData”).click(function () {
- });
- $(“document”).ready(function () {
- script
xReq.open(“GET”, “myXMLData.xml”, false);
- Open method
- Request type
- URI
- Asynchronous
- Hexadecimal RGB
- RGB function
- # 00FF00
- rgb(0,255,0)
- font-weight
- lighter, normal, bold, and bolder
- font-family
- This CSS code renders the fonts in order from left to right until it finds one that is available
- font-size
- xx-small, x-small, small, smaller, medium, larger, large,
x-large, xx-large.
- font-weight: bold;
- font-style:italic;
- font-family:Arial,’Times New Roman’,Webdings;
- text-align: right, left, center, justify
- hyphens: none, auto, manual
- text-align: center;
- text-indent: 50px;
- letter-spacing: 8px;
- word-spacing: 8px;
- hyphens: none;
- border-style: solid border, dashed border, dotted line border, grooved line border, and so on
- border-style: solid;
- border-color: black;
- border-spacing: 250px;
- border-width: 5px;
Padding
- padding: 25px 25px 25px 25px;
- or
- padding-top: 25px;
- padding-bottom: 25px;
- padding-left: 25px;
- padding-right: 25px;
- opacity: from 0 to 1.0
- backround-image: size, repeat, clip, position-x/position-y
- linear-gradient: direction, color stop…n
- box-shadow
- text-shadow
- clipping: The parameters run in clockwise order as top, right, bottom, and left sides of the rectangle
- opacity: 0.4;
- background-image: url(‘orange.jpg’);
- background-size: 20px;
background-repeat: repeat; - background:linear-gradient(black,gray);
- clip: rect(25px, 50px, 50px, 25px);
.clipper
- .clipper{
- position: fixed;
- left: 325px;
- clip: rect(25px, 100px, 100px, 25px);
- }
float
Used to wrap text around an image
element positioning
fixed, absolute, relative
- transition-property
- transition-duration
- transition-delay
- Specifies the property to which a transition will be applied
- Specifies how much time the transition should take from start to finish
- Specifies how long
- translate
- scale
- rotate
- matrix
- Moves the object from its current location to a new location
- Changes the size of the object
- Spins the object along the x-axis, y-axis, and/or the z-axis
- Allows you to combine all the transformations into one command
display:none; will hide an element but keep its space in the overall flow
visibility: hidden; will hide an element and won’t keep its space in the overall flow
- =
- ~=
- ^=
- $=
- *=
- Specifies that an attribute equals a specific value. For example, the URL of an anchor is a specify URL
- Specifies a space-separated list of words as the values for an attribute
- Specifies that the attribute has a value starting with the text specified
- Specifies that the attribute has a value ending with the specified text
- Specifies that the attribute has a value containing the specified text
anchor element
- a:link
- hyperlinks
onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState
Holds the status of the XMLHttpRequest
- 0: request not initialized
- 1: server connection established
- 2: request received
- 3: processing request
- 4: request finished and response is ready
ready state status
- 200: “OK”
- 404: Page not found
shadows
- box-shadow
- text-shadow
border-radius
If only two value are specified:
- Upper-left and bottom-right
- Upper-right and bottom-left
css selector
- .class.child
- .class: element
hovering
.onmouseover
Video format compatible with most browswer
- ogg
- mp4
- webm
Successful completion of an asynchronous operation
done ();
Promise object methods
- always()
- done()
- fail()
- progress()
A Promise is in one of three states
- pending: initial state, not fulfilled or rejected
- fulfilled: successful operation
- rejected: failed operation
stringify(fields, separator, assignment)
parse(querystring, separator, assignment)
- fields : object The data to convert to a query string.
- separator : string The string to use as a separator between each name:value pair. By default this is “&”.
- assignment : string The string to use between each name and its corresponding value. By default this is “=”.
querySelectorAll : static NodeList
getElementByTagName: live NodeList
svg content
XML-based
Elements that trigger continuously during a drag and drop operation
- drag
- dragover
HTMLMediaElement
- Audio
- Video
- …
Data that can be passed to the drop event using the DataTransfer object
Any object that can be represented as a string or URL
- Using static, the element is displayed where it would normally appear in the HTML flow. This is the default
- Using relative, the element is displayed relative to where it would normally appear in the HTML flow
- Using absolute, the element is removed from the HTML flow and positioned within the first non-static element. Although this could mean that the element is positioned within the browser window, it’s not guaranteed
- Using fixed, the element is removed from the HTML flow and positioned within the browser window
decodeURIComponent
The decodeURIComponent function can deserialize the QueryString
localStorage.clear();
The clear() method removes all existing key/value pairs existing for the origin
Change in progress for deferred object
The notify method indicates a change in progress
Audio formats that are compatible with most browsers
- .mp3
- .mp4
- .wav
- .oga
Web SQL
- Safari
- iOS platform
hsl ()
By using the hsl function, you can set the hue value and then adjust the saturation and lightening values to derive other matching colors
text-transform
- Lowercase
- Uppercase
instanceof
object instanceof constructor
JSON
.data
XMPP
Extensible Messaging and Presence Protocol
- xmlhttp.onreadystatechange = function () {
- if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
- var jsonObject = JSON.parse(xmlhttp.response);
- result.innerHTML = jsonObject.result;
- }
- }
- To handle the asynchronous call, you must subscribe to the onreadystateschange event, which is triggered whenever the state of XMLHttpRequest changes.
- You must also test the HTTP status code
to ensure that no error has occurred by verifying that the return code is 200.
Setting the cookie value
- function setCookie(cookieName, cookieValue, expirationDays) {
- var expirationDate = new Date(); expirationDate.setDate(expirationDate.getDate() +
- expirationDays); cookieValue = cookieValue + “; expires=” + expirationDate.toUTCString();
- document.cookie = cookieName + “=” + cookieValue;
- }
Retrieving the cookie value
- var cookies = document.cookie.split(“;”);
- for (var i = 0; i
- var cookie = cookies[i];
- var index = cookie.indexOf(“=”); var key = cookie.substr(0, index); var val = cookie.substr(index + 1);
- if (key == cookieName)
- return val;
- }
transform: rotate(xdeg);
default: clockwise
Selector examples
dataTable tbody tr.selected:not(tr:last-child)
$(“div#container > ul”) .css(“border”, “1px solid black”)
Error prototype
All Error instances and instances of non-generic errors inherit from Error.prototype
.val() works on input elements (or any element with a value attribute) and gets the value of the input element - regardless of type
.text() will not work on input elements - gets the innerText (not HTML) of all the matched elements
Verify if e is an instance of a fonction
if (e instanceof function name)
Drag and drop
- dragstart
- dragenter
- dragover
- dragleave
- drag
- drop
- dragend
Data Transfer
- void addElement(in Element element)
- void clearData([in String type])
- String getData(in String type)
- void setData(in String type, in String data)
- void setDragImage(in nsIDOMElement image, in long x, in long y)
- void mozClearDataAt([in String type, in unsigned long index])
- nsIVariant mozGetDataAt(in String type, in unsigned long index)
- void mozSetDataAt(in String type, in nsIVariant data, in unsigned long index)
- StringList mozTypesAt([in unsigned long index])
- -ms-grid-columns
- -ms-grid-rows
- Specifies the width of each grid column within the Grid. Each column is delimited using a space
- Specifies the height of each grid row within the Grid. Each row is delimited using a space
flex-flow
flex-flow: flex-direction || flex-wrap
flex-grow
This defines the ability for a flex item to grow if necessary
flex-direction
flex-direction: row | row-reverse | column | column-reverse;
flex-wrap
By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap as needed with this property
align-items
- flex-start: cross-start margin edge of the items is placed on the cross-start line
- flex-end: cross-end margin edge of the items is placed on the cross-end line
- center: items are centered in the cross-axis
- baseline: items are aligned such as their baselines align
- stretch (default): stretch to fill the container (still respect min-width/max-width)
Simple object access protocol (SOAP)
- contentType: “application/soap+xml”
- type: “Post”
- dataTyp:”xml”
hyphens
- hyphens: none;
- hyphens: manual;
- hyphens: auto;
- Global values
- hyphens: inherit;
- hyphens: initial;
- hyphens: unset;
ActiveXObject Object
- Enables and returns a reference to an Automation object.
- var = new ActiveXObject(servername.typename[, location])