Web Notes HTML, CSS, JS, jQuery and other notes about web development
Last Updated: December 31, 2018 by Pepe Sandoval
If you find the information in this page useful and want to show your support, you can make a donation
Use PayPal
This will help me create more stuff and fix the existent content...
<?XML version="1.0" encoding="UTF-8"?>
Constructs
Tag: A construct that begins with the <
character and ends with the >
character
<item>
</item>
<item />
Element: a construct that includes either an empty element tag or a set of opening & closing tags
<item>content</item>
<plucodes>
<plucode>4012</plucode>
<plucode>4381</plucode>
</plucodes>`
Attribute: A constructs that describe a key-value pair in an element and provides additional metadata about the element
<plucode description="Blood Orange">4381</plucode>
HyperText Markup Language that defines/describes the structure of a webpage
A web page constructed using HTML has basic and essential elements
HTML allows us to encode the structure of a page using tags <tagName></tagname>
<!DOCTYPE HTML>
<!-- HTML Element -->
<html lang="en-US">
<!-- HEAD Element -->
<head>
<title>Sample Web Page</title>
</head>
<!-- BODY Element -->
<body>
Welcome
</body>
</html>
Reference to all HTML elements
<p></p>
- Paragraph: Designates you want to create a text paragraph<hN></hN>
- Headers: Up to six levels of headersFormat | Markup | Result |
---|---|---|
Bold | <b> |
Bold Text |
Strong | <strong> |
Strong Text |
Italic | <i> |
Italic Text |
Emphasized | <em> |
Emphasized Text |
Small | <small> |
Small Text |
Marked | <mark> |
Marked Text |
Deleted | <del> |
Deleted Text |
Inserted | <ins> |
Inserted Text |
Subscript | <sub> |
Subscript Text |
<br>
, <body>
, <p>
, <hN>
<div>
element is a multi-purpose element that simply gives you a container for other content (generic block container).<span>
element (generic inline container).<img>
- Images: This tag provides metadata about the image file and preferred sizing to help the browser decide how to render the image.<a></a>
- Hyperlinks: Allow to reference external, remote documents (web pages) and also reference elements within the same page.action
attribute indicates the URL where the form will be submittedmethod
attribute indicates the HTTP method used when submitting the formsubmit
type is the one used to indicate that an input will be used to submit a form<fieldset>
and <legends>
are usually used to group split into different input sectionsTo build a form in HTML you can use a variety of input elements. Each input element offers options that allow you to control features such as validation or watermarks.
<textarea />
- Text Area: Renders a multi-line text input control.<select />
- Select: Renders a drop-down list with multiple options.<optgroup />
- Option Group: Group related option.<input />
- Input: Its the basic form element in HTML, used to capture text and numeric values<button />
- functions similarly to an input element of type button but it also allows you to render custom content within the button.novalidate
attributeAttribute | Description | Ex |
---|---|---|
required | Specifies that a text input must have valid data | required="required" |
pattern | Specifies a regular expression that the value of the input field must match | pattern="\d{5}(-\d{4})?" |
readonly | Specifies that a particular field is read-only and cannot be modified by the user | readonly="readonly" |
disabled | Specifies that a particular field is disabled and cannot be modified by the user | disabled="disabled" |
min/max | Used with the range input type to specify boundaries for the selected numeric value | type="range" min="1" max="15" |
autocomplete | Toggle the auto-complete feature found in most modern browsers | autocomplete="off" |
placeholder | Renders a "watermark" that is shown when the input is empty | placeholder="Watermark here |
<svg>
element is used to define an SVG element and the <rect>
, <circle>
, <text>
, etc. elements can be used to draw basic shapes.css
extension references by other(s) HTML doc(s)Declaration: Contains one or more property-value pairs
Selector: Defines the HTML element being manipulated
We can use commas on the selector section to target multiple elements. Ex. header, footer { color: black; }
We can use greater-than >
to target all Direct Descendants of the specified type within another element Ex. section > nav { color: black; }
We can use space
to target all elements inside of another element Ex. section nav { color: black; }
We can use space +
to target adjacent elements sibling elements Ex. h4 + ul { color: black; }
We can use space select all elements with a certain attribute Ex. a [href="http://www.google.com]" { color: black; }
We can create CSS classes and then specify the HTML elements that belong to that CSS class.
.
in the selector in the .css
fileA CSS ID is a unique identifier for an element which can only be declared once within the same HTML file and is normally very specific
#
in the selector in the .css
filebody {color: red !important;}
CSS Media Queries allow us to conditionally apply CSS in specific scenarios based on properties of our current browser and can contain simple logic using and
for logic AND and ,
for logic OR
@media screen
@media (min-width: 500px)
<=
): the browser is less or equal than this value>=
): the browser is greater or equal than this value<head>
<link rel="stylesheet" href="base.css" />
<link rel="stylesheet" href="mobile.css" media="screen and (max-width: 1000px)" />
<link rel="stylesheet" href="print.css" media="print" />
</head>
sans-serif
, serif
, monospace
. It is good practice to use the keyword for these basic fonts as a catch-all fallback@font-face {
font-family: "Demo Font";
src: url(/demofont.otf);
}
CSS font stack Google Fonts Google Fonts how-to
Color
color: red;
color: #FF0000;
color: rgb(255, 0, 0);
color: rgba(255, 0, 0, 0.5);
Background
background: red;
, background: #FF0000;
, background: rgb(255, 0, 0);
, rgba(255, 0, 0, 0.5);
background: url(http://3dprint.com);
Border
width
, color
, style
in order to show border: 5px solid purple
float: left
margin: auto auto auto auto;
is a value to center between elementstext-align
, width
and height
operate over the Content of an elementwidth
and height
represents the percent of the the parent element that a certain element will take
.css
file and a .js
file that we can include in our application to use the functionality provided by those files.css
is just a bunch of class definitions that we can use to style our html elementsmake sure to put your own CSS file after including bootstrap so overrides work
Scripts are added at the end of the html, make sure to get jQuery and add it before the bootstrap
.js
script
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">COL 1</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">COL 2</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">COL 3</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">COL 4</div>
</div>
</div>
<script>
to define the code which can be embedded in HTML to be interpreted and executed by the client’s browsertrue
or false
""
or ''
undefined
and null
The two possible states/values for a variable if it does not have a value assigned in JavaScript are:
undefined
myVariable = "Hell"
===
and !==
which also compare type unlike ==
and !=
.
operator or the with
keywordNumber
, Boolean
, String
, Array
, Date
, Math
, RegExp
[]
or with the Array
keyword and the values stored in them do not need to be the same type, you can have arrays within arraysfunction myFunc() {};
var cars = ["Saab", "Volvo", "BMW"];
var myArray = new Array(3);
myArray[0] = Date.now;
myArray[1] = myFunc;
myArray[2] = new Array("Demo", "Test");
localStorage
(non-volatile) and sessionStorage
(volatile) objects are used to data stored locally on the browser clientgetCurrentPosition()
and watchPosition()
methods are used to setup thisalert()
, prompt()
, console.log()
:onload
)onclick
)document
objectThe main JS methods to select DOM elements:
document.getElementById()
: use element ID and returns a single element
var elem = document.getElementById("myid")
elem.innerHtml = ""
document.getElementsByClassName()
: use class name and returns a list or nodelist
var elem = document.getElementsByClassName("myclass")
console.log(elem.length)
elem[0].innerHtml = ""
document.getElementsByTagName()
: takes as input element tags like h1
, li
, div
, etc. ands returns a list or nodelist
var elem = document.getElementsByTagName("tag")
console.log(elem.length)
elem[0].innerHtml = ""
document.querySelector()
: selects and returns only the first element that match the specified CSS style selector
var elem = document.querySelector("#myid")
elem.innerHtml = ""
var elem = document.querySelector(".myclass")
elem.innerHtml = ""
document.querySelectorAll()
: selects and returns a nodelist of all the elements that match the specified CSS style selector
var elem = document.querySelectorAll("#myid")
elem[0].innerHtml = ""
var elem = document.querySelectorAll(".myclass")
elem[0].innerHtml = ""
CSS style selector is any valid CSS selector so for example for ID we use
#
, for class we use.
, for html tags we use the direct HTML tag name likeh1
,li
etc.
We usually manipulate 3 main things in a element:
style
object to manipulate specific properties like background
, color
, etc.classList.add("classname")
, classList.remove("classname")
and classList.toggle("classname")
to add, remove and toggle a class we have defined in our .css
to add style to an elementtextContent
or innerHtml
propertiesgetAttribute("attr_name")
and setAttribute("attr_name", "value")
to change HTML attributes of an element like href
, src
, etc.addEventListener(type, callback)
methodthis
keyword inside a listener refers to the element that triggered the event$.ajax
object and it's methods to make queries to external sources (web services, files, APIs, etc).$
and takes as input any CSS selector and return a list. E.x. $(#myid)
The jQuery manipulation methods usually accept either a key-value pair or JS object (dict)
The jQuery selector methods methods usually return a list of jQuery objects so when using a get method this usually operates only on the first element of that list and a set method usually operates on all the matched/selected elements
style -> .css
method:
.css(property, value)
method e.x. $(#myid).css("color", "yellow")
.css({...})
It's also common to pass a JS object with the key-value pairs of the styles to be changed. CamelCase is needed for the name of the properties.css
returns a list so the styles can be applied to multiple elements at the same timecontent -> .html
and .text
methods:
.text()
to get the text contents of the selected element and all of its descendants and .text("new text")
to update all the selected elements.html()
to get the html contents of the first matched element and .html("new html")
to set contents of every matched elementattributes -> .attr()
:
.attr("attr_name")
and attr("attr_name", "value")
to get the attribute for the first matched element or to set attributes to every matched elementsinput -> .val()
method
classes -> .addClass("className")
, .removeClass("className")
and .toggleClass("className")
methods:
$(this)
returns the jQuery object referenced by this
event
object parameter to the callback in the events makes all the information of the event available in the callback .click(functio(event){...})
click(callback)
: used to add click listeners to one or more elementskeypress(callback)
, keyup(callback)
and keydown(callback)
: used to add key press listeners to one or more elements.keypress()
gets you the end character result that is entered when pressing keyson(type, callback)
is the general jQuery method to add an event listener and it lets us specify the event type.fadeOut(duration, callback)
, .fadeIn(duration, callback)
and .fadeToggle(duration, callback)
on the selected element it animates a fade out/in, this means it makes it go from certain level of opacity to the other extreme of opacity.slideDown(duration, callback)
, .slideUp(duration, callback)
and .slideToggle(duration, callback)
it animates the hide of the selected element, this means it makes it go from certain level of opacity to the other extreme of opacityThe protocol used for Web communication is called HTTP (HyperText Transfer Protocol) which
defines a set of rules for how clients and servers communicate and transfer resources (HTML pages, CSS style sheets or data).
HTTP uses a set of methods (GET
, POST
, PUT
, DELETE
) that clients and servers use to communicate,
this is how a client specifies if its asking for data, providing data or deleting data then Servers send an HTTP responses
to clients after handling the requests appropriately. The response include a status and can include data or resources that were requested.
A web server handles requests for web content and serves the content to clients
An API is an interface that allows one software component to use or interact with another, a Web API is no different it's just accessed over the web they are also sometimes referred as REST APIs or REST Services
JSON is a text-based data-interchange format used on the Web
The Presentation Layer refers to user interface of an application which includes all the HTML, CSS and JS code needed to display and interact with the web application, basically it refers to the front-end
The Application layer refers to all the logic carried out in the background in order to handle the features of the application. Generally handled in the back-end
The Data Layer is the one that stores, organizes and manages access to an application's data using a database, also handled in the back-end
With client-side rendering the JavaScript code running in the user's web browser is responsible for requesting data from the server and manipulating the webpage as needed, with this approach the server server-side code will be primarily responsible with providing access to data, not with rendering user-interface code
With server-side rendering the client requests a new webpage from the server for every update, and displays the page in the way it's received.
It is possible to use a combination of these approaches, using server-side code to render the initial page, and then updating it as needed with client-side code.
<script>
tags so we need NPM to install/include JS libraries (or packages)npm install <package_name>
to install a packagerequire()
to add modules to our project, in other word to include a package in a JS filenpm
package or project has a .json
(package.json
) file that contains all the metadata about a package (dependencies, name, author, license info, url, etc.)npm init
is used to setup a Node.js project and uses the information from your package.json
file to do so or creates a new package.json
file if it doesn't exist--save
flag is used to creates a dependency in the package.json
app.use(express.static('public'));
. This means we'll keep our static HTML, CSS and JavaScript files for our front-end in a public folder on our server, and Express will simply return those files as-is when the browser requests them..ejs
(Embedded JavaScript) files to render html, which are templates to create parametrized html files.ejs
files must be in the views
folder, express will look in this folder by defaultapp.use(express.static("path_to_folder"))
methodejs
package for this. Install: npm install ejs --save
ejs
brackets <%= %>
/<% %>
and everything inside these special brackets is treated as JavaScript<%= %>
whatever the code inside returns will be rendered and added to the html file<% %>
code inside will just be evaluated as JS but NOT added to the html file<% %>
node -v
to check it was installed correctlynpm init
you will be guided through a series of prompts to enter values for your project, you can press enter to use the default valuesapp.js
or server.js
package.json
file was created, and save it as server.js
or whatever name you have as entry point.server.js
file. For example:var http = require('http');
var port = 3000; // process.env.PORT;
var requestHandler = function(request, response){
console.log('New request to: ' + request.url);
response.end('Hello, World!');
};
var server = http.createServer(requestHandler);
server.listen(port, process.env.IP, function() {
//server.listen(port, function() {
console.log('Listening on port ' + port);
});
node server.js
and open a browser in localhost:3000
or 127.0.0.1:3000
to test access to the serverThe
http
module is a module that is built into Node.js. It allows HTTP communication with your Node.js server. We need it to create o create a server that listens to http requests and provides http responses, to create the server we use thecreateServer
method from this module
npm install express --save
var express = require('express');
) and create an express app object var app = express();
and use this instead of the server objectvar express = require('express');
var app = express();
var port = 3000; // process.env.PORT;
app.get('/', function(request, response){
response.send('Hello, World!');
});
app.listen(port, process.env.IP, function() {
//app.listen(port, function() { // if you dont need to define a specific IP use this
console.log('Listening on port ' + port);
});
A collection of information/data that has an specific interface to interact (add, remove, update, etc.) with the information
A database is an organized and structured collection of data that stores data as records, each record would have attributes that describe the item being stored and each attribute has a specific data type.
A query language is used to define instructions for creating, accessing and modifying data in a database, for example SQL (Structured Query Language).
A DBMS (DataBase Management System) is an application that allows you to interact with databases, for example SQL Server, SQLite and MySQL. You can interact with these DBMSs directly which is the common use case when debugging or manually checking the database or you can write code in a server-side programming language to do this interaction, which is the comon use case
Associations: Refers to the idea to have associated data. Types: one:one, one:many and many:many
CRUD (Create, Read, Update, Destroy) basic expected functionality from a database interface. CRUD app is a term used to refer to web application that support CRUD operations, this means it provides a way to perform some set of CRUD operations on its data/resources (the resources of a webpage can be its users, posts, comments, etc.)
SQL (Structured Query Language) is a language used to interact with relational databases. It supports the following command types:
CREATE
: Create a new database or tablesALTER
: Change the structure of a tablesDROP
: Delete a table, database or columnRENAME
: Rename a tableTRUNCATE
: Delete all of the data from a tableINSERT
: Save a new record into a databaseUPDATE
: Update a record in a database with new fieldsDELETE
: Delete a record from a databaseSELECT
: Retrieve records from the databaseSQL Data types:
p
integer digits and s
decimal digitssudo apt-get install sqlite3
sqlite3 NewDatabase.db
.table
, .mode column .width 10
# create table
CREATE TABLE Contacts(
id INTEGER PRIMARY KEY,
FirstName VARCHAR(255),
LastName VARCHAR(255),
Age INTEGER,
EmailAddress VARCHAR(255),
PhoneNumber VARCHAR(255),
ZipCode VARCHAR(255)
);
# insert record
INSERT INTO Contacts
VALUES (12, 'John', 'Doe', 'JohnDoe@email.com`, '999-999-9999', '29384');
# omitting id
INSERT INTO Contacts (FirstName, LastName, EmailAddress, PhoneNumber, ZipCode) VALUES ('Thomas', 'Axen', 'taxen@email.com', '111-111-1111', '90110');
# select all data from table
SELECT * FROM Contacts;
# select specific columns
SELECT FirstName FROM Contacts;
SELECT FirstName, LastName FROM Contacts;
# select conditionally
SELECT * FROM Contacts WHERE FirstName = 'Roya';
SELECT FirstName FROM Contacts WHERE id <= 4
SELECT * FROM Contacts WHERE id <= 4 AND ZipCode = '90210';
# ordering
SELECT * FROM Contacts ORDER BY id DESC
SELECT FirstName FROM Contacts ORDER BY id DESC;
# update single record
UPDATE Contacts SET ZipCode = '33333' WHERE ID = 3;
UPDATE Contacts SET LastName = 'Smith', ZipCode = '44444' WHERE ID = 4;
# update multiple records
UPDATE Contacts SET ZipCode = '22222' WHERE ZipCode = '90210';
# update all records
UPDATE Contacts SET ZipCode = '00000';
# delete single record
DELETE FROM Contacts WHERE ID = 5;
DELETE FROM Contacts WHERE FirstName = 'Kim'
# delete multiple records
DELETE FROM Contacts WHERE ZipCode = '90210';
# delete table
DELETE TABLE Contacts;
DROP TABLE Contacts
SQLite will automatically provide an auto-incrementing, primary key attribute named rowid when you create a new table
npm install sqlite3 --save
var sqlite3 = require('sqlite3');
and create a database object to connect and access the database var db = new sqlite3.Database('myDatabase.db');
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database('myDatabase.db'); // you can also use ':memory:' as parameter to use an in-memory temporary database
db.serialize(function(){
// To run the appropriate INSERT, UPDATE or DELETE SQL statement use run()
//create table
db.run('CREATE TABLE Contacts (first_name TEXT, last_name TEXT, age INTEGER)');
//insert values
db.run('INSERT INTO Contacts VALUES ("John", "Doe", 25)');
// For SQL SELECT queries use all(), each(), or get()
// The all() method allows you to run a SQL query and provide a callback function that processes the resulting set of rows.
db.all('SELECT * FROM Contacts', processRows);
// The each() method allows you to run a SQL query and provide a callback function that processes one row at a time
db.each('SELECT * FROM Contacts', processRow);
// The get() method allows you to run a SQL query and provide a callback function that processes the first resulting row
var firstName = 'John';
db.get('SELECT * FROM Contacts WHERE first_name = ?', [firstName], processRow);
});
function processRows(err, rows){
if(err) {
console.log("ERROR: " + err.message);
}
else {
for(var i = 0; i < rows.length; i++){
console.log(rows[i].name);
}
}
}
function processRow(err, row){
if(err) {
console.log("ERROR: " + err.message);
}
else {
console.log(row.name);
}
}
db.close();
/etc/init.d/mongod
cd ~
mkdir data
echo "mongod --dbpath=data --nojournal" > mongod
chmod a+x mongod
cd ~ ./mongod
mongo
commanduse <database_name_here>
db.<name_new_collection_here>.insert(<json_object_here>)
show collections
: shows collectionsdb.<collection_name_here>.find()
return all data in collectiondb.<collection_name_here>.find({<key>:"<value>"})
return entries that match key-value pair(s)db.<collection_name_here>.update({<select_key>:"<select_value>"}, <json_object_here>)
: update entry that matches select key-value pair overriding entry with new objectdb.<collection_name_here>.update({<select_key>:"<select_value>"}, {$set:{<json_object_here>}})
: update entry that matches select key-value pair without overriding original object just updates fields appropriatelydb.<collection_name_here>.remove({<select_key>:"<select_value>"})
remove entries that matches select key-value pairdb.<collection_name_here>.drop()
delete all entries in a collectionREST Services are a category of APIs that are available on the Web, and are accessed using HTTP requests (GET
, POST
, PUT
, DELETE
)
In a RESTful system, all data is represented in terms of resources. REST revolves around the idea of resources and performing actions on those resources.
Paradigm to structure a web page
A pattern/convention to define web page routes
It's a SW architecture to map or establish a relationship between HTTP routes and CRUD operations
Mongoose | CRUD Op | REST Op | URL | Method | Description/Purpose |
---|---|---|---|---|---|
.find() | READ | INDEX | /url | GET | display in general all resources |
- | CREATE | NEW | /url/new | GET | display a form to create a resource |
.create() | CREATE | CREATE | /url | POST | creates a resource then redirect |
.findById() | READ | SHOW | /url/:id | GET | shows info about a resource with identifier :id |
.findById() | UPDATE | EDIT | /url/:id/edit | GET | display a form to edit resource with identifier :id |
.findByIdAndUpdate() | UPDATE | UPDATE | /url/:id | PUT | update resource with identifier :id then redirect |
.findByIdAndRemove() | DESTROY | DESTROY | /url/:id | DELETE | delete resource with identifier :id then redirect |
http is a stateless protocol, request do not contain information about your history (if you had previously accessed the page) or the previous request that you have made requests don't have states
Sessions: are the way we make HTTP not-stateless, they are the way we provide state to HTTP requests, provide a secret key/hash information that identifies the user
Headers are also involved in male HTTP not-stateless, a header is essentially the same as form data or just in data as just some more data included but instead of being in the form section or the JSON payload section and it goes in the headers section
npm install passport passport-local passport-local-mongoose express-session
this
this
is NOT inside of a declared object it refers to the global object, in the browser is the windowthis
IS inside of a declared object it refers to the closest parent objectcall
, apply
and bind
to choose what we want the context of this
to be, these methods are applied to functionsthis
refers to the new object creatednew
keyword is used to create a new object from a functionnew
keyword is used and implicit return this
is added to the function used to construct an objectJS does not have built-in support for OOP or classes so JS mimics this through constructors (functions) and the use of new
new
keyword
this
to be that empty objectreturn this
to the end of the function (constructor) used with new
__proto__
property, which is the link between the created object and the prototype
property which is stored in the constructor function is an object that is shared among instances/objects of this 'class')
Inheritance can be implemented using call
or apply
, we use these functions to simulate the call to the base/parent constructor
function Vehicle(make, model, year, wheels) {
this.make = make;
this.model = model;
this.year = year;
this.wheels = wheels
this.isOn = false;
// this is an object method, every instances has his own copy
this.move = function () {
console.log(this.make + " " + this.model + " has moved");
}
}
// these are class methods which are stored in the property object
Vehicle.prototype.turnOn = function() {
this.isOn = true;
}
Vehicle.prototype.turnOff = function() {
this.isOn = false;
}
Vehicle.prototype.turnOff = function() {
if (this.isOn) {
console.log("Beep");
}
}
function Car(make, model, year) {
// equivalents
//Vehicle.call(this, make, model, year, 4);
//Vehicle.apply(this, [make, model, year, 4]);
Vehicle.apply(this, arguments); this.wheels = 4;
}
var myCar = new Car("My Car", "Aveo", "2014")
If you find the information in this page useful and want to show your support, you can make a donation
Use PayPal
This will help me create more stuff and fix the existent content...