CS202 Final Term Handouts.....
CS202 Final Term Handouts.....
Associative arrays
Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays
with named indexes.
pop() method
The pop() method removes the last element from an array. The pop() method returns the value that was
"popped out".
push() method
The push() method adds a new element to an array (at the end).
shift() method
The shift() method removes the first element of an array, and "shifts" all other elements one place up.
The shift() method returns the value that was "shifted out".
Delete elements
Elements can be deleted by using the JavaScript operator delete.
splice() method
The splice() method can be used to add new items to an array.
sort() method
The sort() method sorts an array alphabetically.
reverse() method
The reverse() method reverses the elements in an array.
concat() method
The concat() method creates a new array by concatenating two arrays.
slice() method
The slice() method slices out a piece of an array into a new array
JavaScript Comparisons
Comparison and Logical operators are used to test for true or false. Comparison operators are
used in logical statements to determine equality or difference between variables or values.
Logical operators are used to determine the logic between variables or values. JavaScript also
contains a conditional operator that assigns a value to a variable based on some condition.
JavaScript also has Bitwise Operators. Bit operators work on 32-bit numbers. Any numeric
operand in the operation is converted into a 32-bit binary number. The result is converted back
to a JavaScript number.
Comparison Operators
Operator Description
== equal to
Logical Operators
Operator Description
&& and
|| or
! not
Syntax
Example
If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise
the value of voteable will be "Old enough".
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
Example
Code Out Put
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p id="demo"></p>
<script>
if (a > b) {
} else if (a < b) {
} else {
document.getElementById("demo").innerHTML =
result;
</script>
</body>
</html>
Switch Statement
You can use multiple if...else…if statements, to perform a multi way branch. However, this is
not always the best solution, especially when all of the branches depend on the value of a
single variable.
Instead you can use a switch statement which handles exactly this situation, and it does so
more efficiently than repeated if...else if statements.
Flow Chart
Syntax
switch (expression) {
break;
break;
...
break;
default: statement(s)
<html>
<body>
<h2>JavaScript Switch</h2>
<p id="demo"></p>
<script>
switch (flower){
case "rose":
break;
case "violet":
break;
case "sunflower":
break;
default:
document.getElementById("demo").innerHTML =
result;
</script>
</body>
</html>
The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is true, then
the code given inside the loop will be executed, otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
Syntax
<body>
<p id="demo"></p>
var count;
document.getElementById("demo").innerHTML+="Starting
Loop" + "<br />";
document.getElementById("demo").innerHTML+="Current Count :
" + count+"<br>";
document.write("<br />");
document.getElementById("demo").innerHTML+="Loop
stopped!";
</script>
</body>
</html>
Loop statements
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce
the number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
Flow Chart
Syntax
while (expression) {
Statement(s) to be executed if expression is true
}
<body>
<p id="demo"></p>
<script>
var myBankBalance = 0;
myBankBalance ++;
document.getElementById("demo").innerHTML=msg;
</script>
</body>
</html>
<html>
<body>
<h3>JavaScript do-while Loop Example</h3>
<p id="demo"></p>
<script type="text/javascript">
var num = 3;
document.getElementById("demo").innerHTML+=
var i = 1;
do
document.getElementById("demo").innerHTML+=
num*i + "<br/>";
i++;
} while(i<=10);
document.getElementById("demo").innerHTML+="Done!";
</script>
</body>
</html>
To handle all such situations, JavaScript provides break and continue statements. These
statements are used to immediately come out of any loop or to start the next iteration of any
loop respectively.
Flow Chart
<body>
<p id="demo"></p>
<!--
var x = 1;
document.getElementById("demo").innerHTML+="Entering the
loop<br /> ";
if (x == 5) {
x = x + 1;
document.getElementById("demo").innerHTML+= x +
"<br />";
document.getElementById("demo").innerHTML+="Exiting
the loop!<br /> ";
//-->
</script>
</body>
</html>
<body>
<p id="demo"></p>
<!--
var x = 1;
var msg="";
x = x + 1;
if (x == 5) {
document.getElementById("demo").innerHTML=msg;
//-->
</script>
</body>
</html>
In JavaScript there are 5 different data types that can contain values:
String
Number
Boolean
Object
Function
Object
Date
Array
null
undefined
typeof operator
You can use the typeof operator to find the data type of a JavaScript variable.
Constructor
A constructor is a function that creates an instance of a class which is typically called an “object”. In
JavaScript, a constructor gets called when you declare an object using the new keyword. The purpose of
a constructor is to create an object and set values if there are any object properties present.
Constructor Property
The constructor property returns the constructor function for all JavaScript variables.
can be used for text search and texts replace operations. When you search for data in a text, you
can use this search pattern to describe what you are searching for.
expressions can be used to perform all types of text search and texts replace operations.
Syntax
/pattern/modifiers;
Example:
Example
<html>
<body>
<p id="demo"></p>
<script>
var text = "Virtual University!";
var n = text.search(/university/i);
document.getElementById("demo").innerHTML = n;
</script>
</body>
</html>
The replace() method replaces a specified value with another value in a string.
Example
<body>
<script>
function myFunction() {
var text =
document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML
=
text.replace(/canada/i, "Pakistan");
}
</script>
Example
<html>
<body>
<p id="demo"></p>
<script>
var text =
document.getElementById("p01").innerHTML;
document.getElementById("demo").innerHTML
= pattern.test(text);
</script>
</body>
</html>
The exec() method is a RegExp expression method. It searches a string for a specified pattern, and
returns the found text as an object. If no match is found, it returns an empty (null) object.
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
</script>
</body>
</html>
Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the
top of their scope before code execution. This means that no matter where functions and
variables are declared, they are moved to the top of their scope regardless of whether their
scope is global or local. however, is the fact that the hoisting mechanism only moves the
declaration. The assignments are left in place.
Types of Errors
There are three types of errors in programming:
a. Syntax Errors
b. Runtime Errors
c. Logical Errors
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis.
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as
the syntax error is affected and the rest of the code in other threads gets executed assuming
nothing in them depends on the code containing the error.
Runtime Errors
For example, the following line causes a runtime error because here the syntax is correct, but at
runtime, it is trying to call a method that does not exist.
<!--
window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.
Example
<body>
<p id="p01"></p>
<script>
function myFunction() {
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
x = Number(x);
catch(err) {
finally {
Code Debugging
Programming code might contain syntax errors, or logical errors. Many of these errors are difficult
to diagnose.
Often, when programming code contains errors, nothing will happen. There are no error messages,
and you will get no indications where to search for errors.
Searching for (and fixing) errors in programming code is called code debugging.
JavaScript Debuggers
Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.
Built-in debuggers can be turned on and off, forcing errors to be reported to the user.
With a debugger, you can also set breakpoints (places where code execution can be stopped), and
examine variables while the code is executing.
<html>
<body>
<script>
a = 15;
b = 6;
c = a * b;
</script>
</body>
</html>
Out Put in Google Chrome
JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment
operator (=), instead of a comparison operator (==) in an if statement.
Addition is about adding numbers. Concatenation is about adding strings. In JavaScript both operations
use the same + operator. Because of this, adding a number as a number will produce a different result
from adding a number as a string.
Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). All programming
languages, including JavaScript, have difficulties with precise floating point values.
Example
var x = 0.1;
var y = 0.2;
var z = x + y // the result in z will not be 0.3
JavaScript will allow you to break a statement into two lines. But, breaking a statement in the middle of
a string will not work. You must use a "backslash" if you must break a statement in a string.
Misplacing Semicolon
Because of a misplaced semicolon, this code block will execute regardless of the value of x:
<html>
<body>
<p id="demo"></p>
<script>
var x = 5;
if (x == 19);
document.getElementById("demo").innerHTML =
"Hello";
</script>
</body>
</html>
Example
function myFunction(a) {
var power = 10;
return
a * power;
}
If you use a named index, when accessing an array, JavaScript will redefine the array to a standard
object. After the automatic redefinition, array methods and properties will produce undefined or
incorrect results.
What is JSON?
JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting
data. JSON is often used when data is sent from a server to a web page.
Incorrect:
Incorrect:
With JavaScript, null is for objects, undefined is for variables, properties, and methods. To be null, an
object has to be defined, otherwise it will be undefined.
JavaScript does not create a new scope for each code block. It is true in many programming languages,
but not true in JavaScript.
Each statement in a loop, including the for statement, is executed for each iteration of the loop. Search
for statements or assignments that can be placed outside the loop.
Reduce DOM Access
Accessing the HTML DOM is very slow, compared to other JavaScript statements. If you expect to access
a DOM element several times, access it once, and use it as a local variable.
Keep the number of elements in the HTML DOM small. This will always improve page loading, and speed
up rendering (page display), especially on smaller devices.
Putting your scripts at the bottom of the page body, lets the browser load the page first.
Avoid using the with keyword. It has a negative effect on speed. It also clutters up JavaScript scopes.
You should also avoid using the name of HTML and Window objects and properties:
Examples:
Multiple iframes (<iframe>) can be defined in a window object. However, one window object is created
for the HTML document while each of the iframes have their own window object.
As described in the video, setTimeout function sets a timer on a function, so that the function executes
when the time limit set by a timer is reached. See below the pictorial description.
The setInterval function is the same as the setTimeout function except that it calls the function after
every time interval specified in millseconds as shown in the figure below.
Lesson# 97 - JavaScript and Forms
Learning objectives
HTML forms used in a webpage can be accessed through JavaScript. One way is to use the method
getElementById. You just need to specify the id of the form in this method.
Another way is to use the document object. By using the document.forms collection, you can retrieve
the collection of all forms in a document. Each <form> element is indexed with its name attribute.
Validation of forms
As you can see forms in an HTML document can be accessed in more than one way, we can utilize these
ways to validate forms. It is up to the developer how he tends to validate components of a form. A form
field can be validated whether it is filled or empty, an email address can be validated for certain
symbols. Similarly, a certain length of a password can be imposed on a user.
Client-side validation
Server-side validation
Client-side validation is performed using JavaScript. The following lesson video demonstrates examples
of client-side form validations.
An example has been set out for you in lesson video. A brief description of the code is given below. You
can understand the working of example code in the video.
A form is created in an HTML document with four fields namely, name, email, city and country.
In order to access the form you need to specify the name attribute of <form> element.
A callback function is set on “submit” button. On submission of form the function
“validateForm” is invoked.
validateForm() is a function defined in <script> tag to check whether each one of the fields in the
form are correctly filled or not. If any of given fields fail to validate, a notice is displayed to user.
showNotice() function embeds a message in the div with the id “notice”. Whereas, clearNotice()
hides any previous displayed notices to user.
Lastly, there is the function validateEmail(), which validates an email address according to the
specifications of an actual email address.
Understanding of AJAX
Recognize the purpose of using AJAX
Identify components of AJAX
Introduction to AJAX
Asynchronous JavaScript And XML, also commonly known as AJAX, is a technique used in front-end
development to create dynamic webpages. However, AJAX has its unique features such as:
Above features make it as a key tool for creating fast dynamic webpages. Google Suggest is one of the
major examples, which utilize AJAX.
AJAX is not a programming language. In fact, it is a technique based on existing standards used in JS and
XML. AJAX makes use of two key components, which are
XMLHttpRequest object
JavaScript DOM
You have familiarized yourself with JavaScript DOM in preceding topics. However, XML HttpRequest
object is a new thing, which will be discussed in upcoming lectures.
You may have across these applications of AJAX not knowing how it was being done. In next few
lectures, you will be learning more about AJAX.
XMLHttpRequest
XMLHttpRequest object is used for communicating with server and updating webpages without
reloading the complete page. All browsers including Chrome, Edge, Firefox and later version of Internet
Explorer have a built-in XMLHttpRequest object. However, older versions of Internet Explorer use
ActiveXObject for creating a XMLHttp request.
XMLHttpRequest object has a number of methods. Some prominent methods we will be studying are:
new XMLHttpRequest()
open()
send()
setRequestHeader()
GET vs POST
Now that you have learnt the syntax and use of a few XMLHttpRequest object methods. We shall
proceed further with the methods by which a request is sent that are Get and Post.
The difference between Get and Post can be realized with points given in the following table.
open()
First of all, a connection with the server is opened with open(). There are three parameters passed into
this method, which are: the method with which a request is sent, the target file on the server, the
nature of request. The syntax of open() looks something like the one given below:
The value true here represents that the request will be sent asynchronously that is, the webpage will not
be loaded as a whole and a dynamic view of the webpage will be created.
Another method send() is used after a connection is opened with the server. This method is used to
send the request to server. There are two variations to this method, send() and send(string). Send() is
used to place a request with method GET or POST and send(string) on the other hand is for sending a
request with POST.
There is a property of XMLHttpRequest namely, onreadystatechange. This can help the browsers to
know that some change has occurred in the webpage and a response has been received. When this
change is acknowledged, a function associated with this event is invoked. You can perform necessary
actions required after the response in that function.
Lesson# 102 – AJAX Receiving Response
Learning objectives
For differentiation, you can say that if the fetched response is in XML format then responseXML is used.
However, if a response is in either text or XML format, responseText is a feasible option.
onreadystatechange
onreadystatechange is an event with which the state of XMLHttpRequest can be identified. Typically, a
pointer to a function is stored, which is invoked when the readystatechange event occurs.
There are two properties usually associated with this event, to know the status of request and expected
response. These are:
readystate
status
readystate
This is the property that indicates change in state and resultantly, the function associated with
onreadystatechange event invokes. This property can hold values ranging from 0 to 4. You will study
them further in the video lesson.
status
The status of XMLHttpRequest object is held by status property. The acquired response may or may not
be available when returned to the requesting browser. To check this condition, you can use status
property.
Callback functions
A callback function is a function passed as an argument to another function. This callback function is
sent as a parameter, which is in fact a pointer to the function. Only the name of the function is specified
in function arguments.
A very simple and basic example of a callback function is illustrated in the below figure.
A show() function is invoked as a result of onclick event on either of the buttons. This show() function
gets a reference to another function. To display an introduction to AJAX, the respective button is clicked.
This onclick event invokes the show() function and passes introAJAX() as a reference to this function. In
the show function, the received callback reference is invoked and then you will see relevant text
inserted into the empty <div> element created in the webpage. You can further understand the use of a
callback function in the example below:
You can avoid code from cluttering by using callback functions. Instead of creating XMLHttpRequest
object in each separate function and making an AJAX request, you can create a single function with
request and response logic. You can pass any function you desire as a callback, where each function may
contain distinct logic.
Look at a code snippet also described in the video lesson for better understanding of the concept.
Receiving response with responseText and
responseXML
You may recall ResponseText and ResponseXML from previous lesson. In this topic you will see an
example in which the use of both properties is illustrated.
responseText
When the response received through AJAX is in textual format or XML, you can use responseText to read
the response. The text may contain a string with formatted HTML like the one given below.
responseXML
The responseXML property is used when the received response is in XML. Here, you will need to parse
each element one by one depending upon what information you require from the response.
AJAX example
You have become familiarized with important methods and properties relevant to AJAX. You have been
given code snippets to understand each one of them.
Now, you will be given an overview of working with AJAX using an example. This example shows an
implementation of an autocomplete feature. A user types something in an input field and at that time
an event is fired in the backend using AJAX. A list is displayed to the user based on what the user has
typed so far, which contains words that can possibly be the ones the user wants to type.
You can understand the complete example in the video lesson. Some of the important components in
the example code are given below:
There is an HTML code with an <input> field and an empty <div> to display autocomplete
suggestions.
loadDoc() is a function, which is invoked as result of oninput() event in the input field. An
XMLHttpRequest object is created in this function and a request is sent with POST method. You
will note that the keyword the user has typed in the input field is passed in send() to be sent to
the server.
When a response is received the loadCountries() function is called, which populates response
text in the empty <div>.
A php file with the server-side logic shows how the data is retrieved from a database and a
response is readied as a formatted unordered list <ul>.
Each list <li> element in the response has an onclick() event associated with it, so that when the
user selects any of the options, it displays the search box.
Introduction to jQuery
jQuery is a JavaScript library. It works on the principle of “Write less, do more”. This library is cross
browser compatible, which enables it to run the same in all major web browsers. jQuery is easier to use
as manipulation and traversal of an HTML document, event handling and AJAX are simpler. This library
comes with a number of features such as:
HTML/DOM manipulation
CSS manipulation
Event handlers and utilities
AJAX
Animations
You will witness in upcoming lessons that how jQuery has reduced the code you initially had to write
with JavaScript.
To utilize this jQuery library, you need to have it downloaded on your system or add it to your HTML
document. Former way can result in increased load time, however, the later way of adding jQuery to
your document is fast as the copy is cached.
For including jQuery library to your HTML document, you need to add its source in <script> element. You
can know further about the versions of jQuery and the syntax to add this library in the video lesson.
jQuery Content Delivery Network (CDN)
jQuery can be included using jQuery Content Delivery Networks. jQuery is hosted by Microsoft and
Google. You can see sample code for including both libraries in the code snippets below. This again has
faster load time.
jQuery selectors
jQuery events
jQuery effects and jQuery animate
jQuery HTML , CSS
jQuery DOM traversal and AJAX
$(selector).action()
$ denotes jQuery.
Selector can be id, class, element etc.
Action indicates what to do with the fetched element
Other selectors can be class, element and this pointer. See the examples below.
Class
$(".test").hide()
Element
$("p").hide()
this pointer
$(this).hide()
jQuery selectors
You may recall the syntax used for jQuery selectors that is $(selector).action(). To select any HTML
elements using jQuery, multiple selectors exist. Most common of them are given below:
Element selector
To select an HTML element using its tag, you can substitute $(selector) with $(“tag”). For instance, if you
want to access an image <img> element, you can simply write $(“img”).hide().
#id selector
As discussed earlier, you can write $(“#id”) to fetch an element using its unique id. For instance, if you
want to fetch a <div> element using its id=“demo”, you can write $(“#demo”).
.class selector
Similarly, for a class selector, you can specify the class as $(“.class”).
Modularity of code
You can take a note in this lesson that a good practice is to separate your jQuery functions and other
jQuery logic in another file with the extension .js. You can include this file in the <script> element as
the src attribute. In this way, you can easily navigate through your code and modifications will be easier
in the future.
In Figure 1, the selector is $(“div”), which selects all the <div> elements in the HTML document. Then,
there is the traversing method first() that filters the selection made with $(“div”) and picks only the first
element from the selection. Lastly, the background-color is set to lightgreen for the selected <div>.
Traversing methods
A variety of methods are available in jQuery for DOM traversal. You can look at a few of them in the
following examples.
first()
last()
eq()
filter()
Reduces the set of matched elements to those that match the selector.
not()
The change that occurs after executing the script given in Figure 2, is shown in Figure 4.
jQuery Events
When a user interacts with a webpage, he performs actions like clicking a button, scrolling the webpage,
pressing keys on keyboard, resizing browser window etc. All such actions are responded in one or the
other way. A clicking action on a button with mouse can change its appearance, open a new window or
maybe submit a form.
jQuery provides you with event methods with which you can write responses to actions of a user who
interacts with a webpage.
DOM events
Commonly used DOM events are listed in Table 1. You will learn examples of a few of them in
succeeding lessons.
A variety of DOM events can be handled with methods in jQuery. You have seen the list of such methods
in Table 1. You can define a handler for these events that is nothing more than a function, which is
defined to specify the action to be performed when an event fires.
To define an action associated with this click event, you can write a function in click().
DOM Events
You have been introduced with various jQuery events in the previous lesson. You have also learnt how
to add a function to an event. In this lesson, you will look further into these events and learn their use.
Following are some of the DOM events you will be learning in the video lesson.
ready()
click()
dblclick()
Indicates a click event when a user clicks twice (double-clicks) on an HTML element.
mouseenter()
mouseleave()
mousedown()
Executes when a mouse button is pressed down, while the mouse is over an HTML element.
mouseup()
Executes when a mouse button is released, while the mouse is over an HTML element.
hover()
A combination of mouseenter() and mouseleave(). You will learn its syntax in the video.
focus()
on()
Reference HTML code is given in Figure 3 for you to understand events occurring in Figure 2.
jQuery Effects
Now that you have learnt jQuery events, you may want to add effects to contents on a webpage. jQuery
facilitates you with methods for adding effects and animations on your webpage. You can hide and show
HTML elements or fade elements. Similarly, sliding effects can be added. All such effects give a visual
appeal to a website.
Some of the commonly used effects are listed below, which will be covered in the video lesson later.
fadeIn
Gradually changes the opacity for selected elements from hidden to visible.
fadeout
Gradually changes the opacity for selected elements from visible to hidden.
fadeToggle
hide
show
slideUp
slideDown
slideToggle
You will notice later in their syntax that in fading and sliding effects, you will be able to specify speed
and desired effect.
jQuery Effects Example
In this section, you will be able to understand the working of jQuery effects. Given below is a simulation
that will help you in realizing the different effects that can be incorporated in a webpage.
Reference HTML code for above example is provided below. You can try similar examples yourself, to
learn more.
jQuery Effects
An example has been illustrated in previous lesson, showing use of jQuery effects. In this lesson, you will
learn further, how these methods can be used and what are the parameters of each method.
fadeIn() and fadeOut() take three arguments namely, speed. easing and a callback function. You have
studied both methods in preceding lesson. Hide, show(), toggle() and sliding effects will be discussed in
current lesson.
The hide() method is used to hide an HTML element. An element once hidden do not take any space in
the document and clears out its occupied space. The show() method is used to set hidden elements to
visible. Any hidden elements take the place and space according to their positioning and hierarchy in the
document. Third method is toggle(), which toggles the current element that is, if it is visible then toggle()
hides it and vice versa.
The slideUp() method is used to slide an element in the upward direction. The element is hidden with
this effect, while, the slideDown() method is used to slide an element in the downward direction. A
hidden element is shown with this effect. On the other hand, slideToggle() toggles an element between
slideUp and slideDown.
speed
easing
callback
Specifies the function to be executed after the effect method completes its operation.
On the other hand, fadeTo() method has a somewhat different set of arguments. There is one additional
argument namely, opacity. The value of this argument specifies the value to fade an element to. Its
syntax is as follows:
The floor() method rounds down a given number to its nearest integer. However, ceil() method rounds
up a given number to its nearest integer.
This method returns a random number between the specified range of 0 and 1. However, 0 is inclusive
within the range while 1 is not.
If you want a random integer within a specified range other than 0 to 1, you can take product of the
number returned by random() with the end range. Use floor() to round down that number. See the
example.
If you want to specify a range starting from 1 but not 0 then you can write it as:
jQuery Animations
You can add custom animations using jQuery. jQuery provides a method for creating custom animations
and that is animate().
animate() method
Multiple properties can be animated at the same time, which involves almost all properties except color
animation. Color animation is not a part of jQuery library.
Queue functionality
There is an another functionality that comes with animate() that is, queueing of various animate()
methods. If several calls to animate() are written one after the other then they execute one by one in a
sequence as if they are in a queue. Look at the example given below:
stop() method
You may sometimes require to stop an animation while it is halfway through. The stop() method is used
when you want to stop an animation or an effect before its completion.
This method has two optional parameters, the first one specifies whether all animations in the queue
shall be cleared or only the active one. You can set the value to False if you intend to stop active
animation only. Second parameter specifies whether the active animation shall be completed quickly or
not. You can set this value to False if you intend to stop the active animation instantly.
Understand XML
Recognize uses of XML
XML
XML stands for eXtensible Markup Language used in applications and devices to use, store, transport,
and display data. It is both human and machine-readable. What is XML and its application.
A significant feature of XML is that it is self-descriptive. Look at the following XML, which simply shows a
note and it is easily understandable. You can identify the sender and receiver of message as well as the
heading and body of the message.
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML Vs HTML
You have been learning HTML from the beginning of the course. You recognized that it is used to display
data on a webpage and determine how the data will look like.
XML on the other hand is used to transmit data over the Internet and describes the data itself. The tags
used in HTML were predefined with the language however, you can add custom tags to your XML.
Advantage of XML
At this point you shall be able to point out a few the advantages of XML. It has not only simplified data
transferring but also ensured platform independence. You can share data over computer systems
independent of the format they are using, as XML stores data as plain text.
jQuery Chaining
You have been writing single jQuery statements in a sequence, each new statement following the
previous one. You will be introduced to a new technique of writing multiple jQuery commands
functioning with the same element(s).
When you write a selector with every new jQuery command, the browser takes some time to find those
elements, which meet the criteria. With the technique of chaining you can write multiple commands at a
time for the same selected element(s). Each new action is appended to the preceding one.
There are a number of methods, which make access and manipulation of the DOM easier. These
methods are:
text() – This method returns or sets the text in the selected element(s).
html() – This method returns or sets the content of the selected element(s), which includes the
HTML markup as well.
val() – This method returns or sets the value of fields in a form.
Similarly, there is a method used to get attribute values and that is attr().
Callback function
To clarify things further, look at the following example. It describes the use of callback function in attr()
method.
You know that the callback function has two parameters. The first parameter shows the index of the
current element in the list of selected elements and the second parameter is the old value of the
attribute.
In the example ahead, an onclick function is defined. When a click event occurs, the attr() method is
used to change the src attribute of <img> element. You will see that the image that is displayed on the
webpage changes when the button is clicked.
The methods after() and before() can be used to add new elements.
remove() – This method removes the element entirely along with its child elements.
empty() – This method removes the child elements of a selected element.
You can see that the remove() method removes the element entirely with its child elements while
empty() clears the contents within the element that clears only the child elements.
See the following code. You can notice that there are three buttons having multiple classes. The first
button Button 1 has classes ‘round’ and ‘purple’. Similarly, Button 2 has classes ‘square’ and purple’.
Lastly, you have Button 3 with classes ‘round’ and ‘purple’.
When Button 1 is clicked, a new class ‘green’ is added to it while on clicking Button 2, its class ‘round’ is
removed and Button 3 toggles between ‘square’ and its default class ‘round’.
Get a property
Set a property
The example illustrates getting and setting of style properties using css().
Lesson# 122 – jQuery Dimensions
Learning objectives
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
See the following code, it uses the width() method to find width of the browser window and adjusts the
width of the div according to the change in window’s size. Whatever the size of the window, div adjusts
itself to 50 percent of the window size.
Most of the tasks performed with jQuery requires traversing of the DOM. You find an element or a set of
elements by providing a selector.
Lesson# 124 – jQuery Traversing
Learning objectives
You can find the ancestors of selected element, which can be a parent, grand-parent, great-grandparent
and so on.
Three useful jQuery methods for traversing up the DOM tree are:
You can find the descendants of selected element, which can be a child, grand-child or great-grandchild
and so on.
Several useful jQuery methods for traversing sideways in the DOM tree are:
jQuery Filtering
jQuery has facilitated in selecting a specific element based on its position in a group of elements.
You can now simply filter elements from a set of elements using the following jQuery methods:
jQuery AJAX
As previously discussed in lesson 99, Asynchronous JavaScript And XML, also commonly known as AJAX,
is a technique used in front-end development to create dynamic webpages. However, AJAX has its
unique features such as:
In this lesson, you will be learning the same concept but with the taste of jQuery methods. With the
jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP
Get and HTTP Post. You can load the external data directly into the selected HTML elements of your web
page.
When you place a request and receive its response using jQuery load(), it loads the data from server and
adds that returned data to your selected element.
jQuery load() used for AJAX and load() event are different. jQuery do not mix these two methods as their
parameters are different.
There are additional parameters to this function that are part of the callback function. These parameters
are:
Understand HTTP Request and Response using jQuery Get and Post
jQuery noConflict()
There exists multiple frameworks of JavaScript like Angular JS, Backbone, Ember etc. So, if you intend to
use jQuery along with other frameworks on your webpages, you may face a conflict on the $ sign. In
order to avoid any conflicts with other frameworks while using the $ sign, you can use the noConflict()
method.
Examples
You have learnt different ways of handling the naming conflicts. You can look at the output of the
examples discussed in the video lesson in the following figure.
You can see that jQuery does not throw any error by noConflict() method.
Examle :
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
It has a heading
But still, the XML above does not DO anything. XML is just information wrapped in tags.
For example, Microsoft Office versions 2007 and later use XML for its document structure. So, when you
save a document in Word, Excel or PowerPoint, you will get the document title with an "X" at the end.
The "X" stands for XML. For a Word document, the title would be presented with ".DOCX" at the end.
XML is a markup language, which means it is a computer language that uses tags to describe
components in a file. This XML markup language contains actual words instead of programming syntax.
The most popular markup languages are HTML and XML. You may already be familiar with HTML, but
XML has a few key differences such as:
Purpose: With HTML, or hypertext markup language, information is displayed, but with XML that
information is transferred. Typically, HTML is used for encoding web pages. On the other hand,
XML is a language for data-description and is used to store data.
Ability to customize: HTML uses a pre-selected range of markup symbols or short codes, which
describe the presentation of a web page's content. Conversely, XML is extensible and allows
users to customize and create their own markup symbols. In this way, with XML, users have
complete control and can create an unlimited symbol set to describe their content.
Uses of XML
ML has a variety of uses for Web, e-business, and portable applications.
The following are some of the many applications for which XML is useful:
Web publishing: XML allows you to create interactive pages, allows the customer to customize those
pages, and makes creating e-commerce applications more intuitive. With XML, you store the data once
and then render that content for different viewers or devices based on style sheet processing using an
Extensible Style Language (XSL)/XSL Transformation (XSLT) processor.
Web searching and automating Web tasks: XML defines the type of information contained in a
document, making it easier to return useful results when searching the Web:
For example, using HTML to search for books authored by Tom Brown is likely to return instances of the
term 'brown' outside of the context of author. Using XML restricts the search to the correct context (for
example, the information contained in the <author> tag) and returns only the information that you
want. By using XML, Web agents and robots (programs that automate Web searches or other tasks) are
more efficient and produce more useful results.
General applications: XML provides a standard method to access information, making it easier for
applications and devices of all kinds to use, store, transmit, and display data.
e-business applications: XML implementations make electronic data interchange (EDI) more accessible
for information interchange, business-to-business transactions, and business-to-consumer transactions.
Metadata applications: XML makes it easier to express metadata in a portable, reusable format.
Pervasive computing: XML provides portable and structured information types for display on pervasive
(wireless) computing devices such as personal digital assistants (PDAs), cellular phones, and others. For
example, WML (Wireless Markup Language) and VoiceXML are currently evolving standards for
describing visual and speech-driven wireless device interfaces.
What is a Tree?
Tree is a discrete structure that represents hierarchical relationships between individual elements or
nodes.
In mathematics, a tree is a graph in which any two vertices are connected by exactly one simple path.
Any connected graph is a tree. A tree is a hierarchical data structure defined as a collection of nodes. A
hierarchy consists of an order defined on a set. The term hierarchy is used to stress a hierarchical
relation among the elements.
The XML specification defines an XML document as a well-formed text if it satisfies a list of syntax rules
defined in the specification. This specification is long, however 2 key points relating to the tree structure
of an XML document are:
The begin, end, and empty-element tags that delimit the elements are correctly nested, with
none missing and none overlapping
A single "root" element contains all the other elements
XML Tree
An XML document is always descriptive. The tree structure is often referred to as XML Tree and plays an
important role to describe any XML document easily.
The tree structure contains root (parent) elements, child elements and so on. By using tree structure,
you can get to know all succeeding branches and sub-branches starting from the root. The parsing starts
at the root, then moves down the first branch to an element, take the first branch from there, and so on
to the leaf nodes.
Example
<?xml version = "1.0"?>
<Company>
<Employee>
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>[email protected]</Email>
<Address>
<City>Bangalore</City>
<State>Karnataka</State>
<Zip>560212</Zip>
</Address>
</Employee>
</Company>
XML Introduction
XML (Extensible Markup Language) is a markup language similar to HTML, but without predefined tags
to use. Instead, you define your own tags designed specifically for your needs. This is a powerful way to
store data in a format that can be stored, searched, and shared. Most importantly, since the
fundamental format of XML is standardized, if you share or transmit XML across systems or platforms,
either locally or over the internet, the recipient can still parse the data due to the standardized XML
syntax.
There are many languages based on XML, including XHTML, MathML, SVG, XUL, XBL, RSS, and RDF.
The syntax of a language defines its surface form.[1] Text-based computer languages are based on
sequences of characters, while visual programming languages are based on the spatial layout and
connections between symbols (which may be textual or graphical). Documents that are syntactically
invalid are said to have a syntax error.
Example
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
Diagram Example
You can notice there are two kinds of information in the above example.
The following diagram depicts the syntax rules to write different types of markup and text in an XML
document.
Learning objectives
Canvas Introduction
Example
<html>
<head>
<style>
#test {
width:100px;
height:100px;
margin:0px auto;
</style>
function drawShape() {
if (canvas.getContext) {
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(0.5, '#fff');
lingrad.addColorStop(0.5, '#66CC00');
lingrad.addColorStop(1, '#fff');
lingrad2.addColorStop(0.5, '#000');
lingrad2.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = lingrad;
ctx.strokeStyle = lingrad2;
// draw shapes
ctx.fillRect(10,10,130,130);
ctx.strokeRect(50,50,50,50);
} else {
</script>
</head>
<canvas id = "mycanvas"></canvas>
</body>
</html>
XML Introduction
XML (Extensible Markup Language) is a markup language similar to HTML, but without predefined tags
to use. Instead, you define your own tags designed specifically for your needs. This is a powerful way to
store data in a format that can be stored, searched, and shared. Most importantly, since the
fundamental format of XML is standardized, if you share or transmit XML across systems or platforms,
either locally or over the internet, the recipient can still parse the data due to the standardized XML
syntax.
There are many languages based on XML, including XHTML, MathML, SVG, XUL, XBL, RSS, and RDF.
XML Attributes
The XML attribute is a part of an XML element. The addition of attribute in XML element gives more
precise properties of the element i.e., it enhances the properties of the XML element.
Syntax:
In the above syntax element_name is the name of an element which can be any name.
The attribute1, attribute2, … is XML attribute having unique attribute name. Then in the
content section, any message can be written and at the end, the element name is
ended.
Attribute Types:
There are three types of attributes described below:
String types Attribute: This type of attribute takes any string literal as a value.
Enumerated Type Attribute: This attribute is further distributed in two types-
1. Notation Type: This attribute is used to declares that an element will be referenced to a notation
which is declared somewhere else in the XML document.
2. Enumeration: This attribute is used to specify a particular list of values which match with
attribute values.
Namespaces are commonly structured as hierarchies to allow the reuse of names in different contexts.
As an analogy, consider a system of the naming of people where each person has a given name, as well
as a family name shared with their relatives. If the first names of family members are unique only within
each family, then each person can be uniquely identified by the combination of first name and family
name; there is only one Jane Doe, though there may be many Janes. Within the namespace of the Doe
family, just "Jane" suffices to unambiguously designate this person, while within the "global" namespace
of all people, the full name must be used.
What is W3C
The World Wide Web Consortium (W3C) is the main international standards organization for the World
Wide Web. Founded in 1994 and currently led by Tim Berners-Lee, the consortium is made up of
member organizations that maintain full-time staff working together in the development of standards
for the World Wide Web. As of 21 October 2019, W3C had 443 members.[3][2] W3C also engages in
education and outreach, develops software and serves as an open forum for discussion about the Web.
Namespace Declaration
Namespace is declared using reserved attributes. Such an attribute name must either be xmlns or begin
with xmlns: shown as below −
Syntax:
Example
Namespace affects only a limited area in the document. An element containing the declaration and all of
its descendants are in the scope of the Namespace. Following is a simple example of XML Namespace −
<cont:name>Tanmay Patil</cont:name>
<cont:company>TutorialsPoint</cont:company>
<cont:phone>(011) 123-4567</cont:phone>
</cont:contact>
Here, the Namespace prefix is cont, and the Namespace identifier (URI) as
www.tutorialspoint.com/profile. This means, the element names and attribute names with the cont
prefix (including the contact element), all belong to the www.tutorialspoint.com/profile namespace.
What is DTD
A document type definition (DTD) is a set of markup declarations that define a document type for an
SGML-family markup language (GML, SGML, XML, HTML).
A DTD defines the valid building blocks of an XML document. It defines the document structure with a
list of validated elements and attributes. A DTD can be declared inline inside an XML document, or as an
external reference.[1]
As of 2009, newer XML namespace-aware schema languages (such as W3C XML Schema and ISO RELAX
NG) have largely superseded DTDs. A namespace-aware version of DTDs is being developed as Part 9 of
ISO DSDL. DTDs persist in applications that need special publishing characters, such as the XML and
HTML Character Entity References, which derive from larger sets defined as part of the ISO SGML
standard effort.
A well-formed and valid XML document is one which have been validated against DTD.
In above link, you can copy your XML code and it will check validation for you.
An ampersand (&)
An entity name
A semicolon (;)
author.xml
<!DOCTYPE author [
]>
<author>&sj;</author>
In the above example, sj is an entity that is used inside the author element. In such case, it will print the
value of sj entity that is "Sonoo Jaiswal".
What is Schema
In computer programming, a schema (pronounced SKEE-mah) is the organization or structure for a
database, while in artificial intelligence (AI) a schema is a formal expression of an inference rule.
For the former, the activity of data modeling leads to a schema. In the latter, a schema is derived from
mathematics and is -- essentially -- a generalized axiom or expression where specific values or cases are
substituted for symbols in a hypothesis to derive a particular inference.
The word schema originates in the Greek word for form or figure. However, how you specifically define
schema depends on context. There are different types of schemas, and their meanings are closely
related to fields like data science, education, marketing and SEO (search engine optimization) and
psychology.
An XML Schema is a language for expressing constraints about XML documents. There are several
different schema languages in widespread use, but the main ones are Document Type Definitions
(DTDs), Relax-NG, Schematron and W3C XSD (XML Schema Definitions).
to associate types, such as integer, string, etc., or more specifically such as hatsize, sock_colour,
etc., with values found in documents;
to constrain where elements and attributes can appear, and what can appear inside those
elements, such as saying that a chapter title occurs inside a chapter, and that a chapter must
consist of a chapter title followed by one or more paragraphs of text;
Information in schema documents is often used by XML-aware editing systems so that they can offer
users the most likely elements to occur at any given location in a document.
Checking a document against a Schema is known as validating against that schema; for a DTD, this is just
validating, but for any other type of schema the type is mentioned, such as XSD Validation or Relax-NG
validation.
The Service Modeling Language (SML) provides a framework for relating multiple XSD documents to one
or more documents in a single validation episode.
Since XSD supports associating data types with element and attribute content, it is also used for data
binding, that is, for software components that read and write XML representations of computer
programming-language objects.
XSLT 1.0: XSLT was part of the World Wide Web Consortium (W3C)'s eXtensible Stylesheet Language
(XSL) development effort of 1998–1999, a project that also produced XSL-FO and XPath. Some members
of the standards committee that developed XSLT, including James Clark, the editor, had previously
worked on DSSSL. XSLT 1.0 was published as a W3C recommendation in November 1999. Despite its age,
XSLT 1.0 is still widely used (as of 2018), since later versions are not supported natively in web browsers
or for environments like LAMP.
XSLT 2.0: after an abortive attempt to create a version 1.1 in 2001, the XSL working group joined forces
with the XQuery working group to create XPath 2.0, with a richer data model and type system based on
XML Schema. Building on this is XSLT 2.0, developed under the editorship of Michael Kay, which reached
recommendation status in January 2007. The most important innovations in XSLT 2.0 include:
What is Multimedia?
Multimedia comes in many different formats. It can be almost anything you can hear or see, like images,
music, sound, videos, records, films, animations, and more.
Web pages often contain multimedia elements of different types and formats.
Multimedia Formats
Multimedia elements (like audio or video) are stored in media files.
The most common way to discover the type of a file, is to look at the file extension.
Multimedia files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv, and .avi.
XSLT Introduction
EXtensible Stylesheet Language Transformation commonly known as XSLT is a way to transform the XML
document into other formats such as XHTML.
An XSLT stylesheet is used to define the transformation rules to be applied on the target XML document.
XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT stylesheet and applies the
transformation rules on the target XML document and then it generates a formatted document in the
form of XML, HTML, or text format.
What is XML?
xx. XML stands for eXtensible Markup Language
Simple links
A simple link creates a unidirectional hyperlink from one element to another via a URI.
Example:
<?xml version="1.0"?>
<document xmlns="http://example.org/xmlns/2002/document"
xmlns:xlink="http://www.w3.org/1999/xlink">
<para>It is an anchor that points to the element with the id "someHeading" on the current
page.</para>
</document>
Extended links
Extended links allow multiple resources, either remote or local, to be connected by multiple arcs. An arc
is information about the origin, destination and behavior of a link between two resources. The origin
and destination resources are defined by labels. By using one or more arcs, an extended link can achieve
specific sets of connections between multiple resources.
For example, if all resources in an extended link were given the label A, then an arc within that link
declaring from="A", to="A" would form connections between all resources.
Extended links do not need to be contained in the same document as the elements they link to. This
makes it possible to associate metadata or other supplementary information with resources without
editing those resources.
XLink also supports richer information about link types and the roles of each resource in an arc.
<foobar id="foo">
<bar/>
<baz>
<bom a="1"/>
</baz>
<bom a="2"/>
</foobar>
element(/1/2/1) => bom (a=1) (/1 descend into first element (foobar),
History of JSON
JSON grew out of a need for stateless, real-time server-to-browser communication protocol without
using browser plugins such as Flash or Java applets, the dominant methods used in the early 2000s.
A precursor to the JSON libraries was used in a children's digital asset trading game project named
Cartoon Orbit at Communities.com (at which State Software's co-founders had all worked previously) for
Cartoon Network, which used a browser side plug-in with a proprietary messaging format to manipulate
Dynamic HTML elements (this system is also owned by 3DO). Upon discovery of early Ajax capabilities,
digiGroups, Noosh, and others used frames to pass information into the user browsers' visual field
without refreshing a Web application's visual context, realizing real-time rich Web applications using
only the standard HTTP, HTML and JavaScript capabilities of Netscape 4.0.5+ and IE 5+.
Crockford first specified and popularized the JSON format. The State Software co-founders agreed to
build a system that used standard browser capabilities and provided an abstraction layer for Web
developers to create stateful Web applications that had a persistent duplex connection to a Web server
by holding two Hypertext Transfer Protocol (HTTP) connections open and recycling them before
standard browser time-outs if no further data were exchanged. The co-founders had a round-table
discussion and voted whether to call the data format JSML (JavaScript Markup Language) or JSON
(JavaScript Object Notation), as well as under what license type to make it available. Chip Morningstar
developed the idea for the State Application Framework at State Software.
The system was sold to Sun Microsystems, Amazon.com and EDS. The JSON.org website was launched in
2002. In December 2005, Yahoo! began offering some of its Web services in JSON.
JSON was based on a subset of the JavaScript scripting language (specifically, Standard ECMA-262 3rd
Edition—December 1999[15]) and is commonly used with JavaScript, but it is a language-independent
data format. Code for parsing and generating JSON data is readily available in many programming
languages. JSON's website lists JSON libraries by language.
In October 2013, Ecma International published the first edition of its JSON standard ECMA-404. That
same year, RFC 7158 used ECMA-404 as a reference. In 2014, RFC 7159 became the main reference for
JSON's Internet uses, superseding RFC 4627 and RFC 7158 (but preserving ECMA-262 and ECMA-404 as
main references). In November 2017, ISO/IEC JTC 1/SC 22 published ISO/IEC 21778:2017 as an
international standard. On 13 December 2017, the Internet Engineering Task Force obsoleted RFC 7159
when it published RFC 8259, which is the current version of the Internet Standard STD 90.
YAML
YAML version 1.2 is a superset of JSON; prior versions were not strictly compatible. For example,
escaping a slash / with a backslash \ is valid in JSON, but was not valid in YAML. YAML supports
comments, while JSON does not.
XML
XML has been used to describe structured data and to serialize objects. Various XML-based protocols
exist to represent the same kind of data structures as JSON for the same kind of data interchange
purposes. Data can be encoded in XML in several ways. The most expansive form using tag pairs results
in a much larger representation than JSON, but if data is stored in attributes and 'short tag' form where
the closing tag is replaced with />, the representation is often about the same size as JSON or just a little
larger. However, an XML attribute can only have a single value and each attribute can appear at most
once on each element.
XML separates "data" from "metadata" (via the use of elements and attributes), while JSON does not
have such a concept.
Another key difference is the addressing of values. JSON has objects with a simple "key" to "value"
mapping, whereas in XML addressing happens on "nodes", which all receive a unique ID via the XML
processor. Additionally, the XML standard defines a common attribute xml:id, that can be used by the
user, to set an ID explicitly.
XML tag names cannot contain any of the characters !"#$%&'()*+,/;<=>?@[\]^`{|}~, nor a space
character, and cannot begin with -, ., or a numeric digit, whereas JSON keys can (even if quotation mark
and backslash must be escaped).
XML values are strings of characters, with no built-in type safety. XML has the concept of schema, that
permits strong typing, user-defined types, predefined tags, and formal structure, allowing for formal
validation of an XML stream. JSON has strong typing built-in, and has a similar schema concept in JSON
Schema.
JSON file can be converted to XML (and back) using online file converters.
For example, a series of English words, such as — subject a need and does sentence a verb — has little
meaning without syntax.
Applying basic syntax results in the sentence — Does a sentence need a subject and verb?
If the syntax of a language is not followed, the code will not be understood by a compiler or interpreter.
The object model creates a tree that represents the JSON data in memory. The tree can then be
navigated, analyzed, or modified. This approach is the most flexible and allows for processing that
requires access to the complete contents of the tree. However, it is often slower than the streaming
model and requires more memory. The object model generates JSON output by navigating the entire
tree at once.
The streaming model uses an event-based parser that reads JSON data one element at a time. The
parser generates events and stops for processing when an object or an array begins or ends, when it
finds a key, or when it finds a value. Each element can be processed or discarded by the application
code, and then the parser proceeds to the next event. This approach is adequate for local processing, in
which the processing of an element does not require information from the rest of the data. The
streaming model generates JSON output to a given stream by making a function call with one element at
a time.
There are many JSON generators and parsers available for different programming languages and
environments.
The basic version of HTML has support for basic elements like text controls and images. This was the
very basic version of HTML with less support for a wide range of HTML elements. It does not have rich
features like styling and other things that were related to how content will be rendered in a browser.
The initial version of HTML does not provide support for tables, font support, etc., as it provides us in
the latest version.
We would also like to discuss that W3C did not exist before HTML 2.0; hence it does not show details
about HTML 1.
2. HTML 2
HTML version 2.0 was developed in 1995 with basic intention of improving HTML version 1.0
Now a standard got started to develop so as to maintain common rules and regulations across different
browsers. HTML 2.0 has improved a lot in terms of the markup tags. In HTML 2.0 version concept of
form came into force. Forms were developed, but still, they had basic tags like text boxes, buttons, etc.
Also, the table came as an HTML tag. Now, in HTML tag 2.0, browsers also came with the concept of
creating their own layers of tags that were specific to the browser itself. W3C was also formed. The main
intention of W3C is to maintain standard across different web browsers so that these browsers
understand and render HTML tags in a similar manner.
3. HTML 3.2
It was developed in 1997. After HTML 2.0 was developed, the next version of HTML was 3.2
With version 3.2 of HTML, HTML tags were further improved. It is worth noting that because of W3C
standard maintenance, the newer version of HTML was 3.2 instead of 3.
Now, HTML 3.2 has better support for new form elements. Another important feature what HTML 3.2
implemented was support for CSS. CSS stands for Cascading Style Sheet. It is CSS that provides features
to make HTML tags look better on rendering it on browsers. CSS helps to style HTML elements.
With the upgradation of browsers to HTML 3.2, the browser also supported for frame tags, although
HTML specifications still do not support frame markup tags.
4. HTML 4.01
It was developed in 1999. It extended the support of cascading styling sheets. In version 3.2, CSS were
embedded in HTML page itself. Therefore, if the website has various web pages to apply to the style of
each page, we must place CSS on each web page. Hence there was a repetition of the same block of CSS.
To overcome this thing, in version 4.01 concept of an external styling sheet emerged. Under this
concept, an external CSS file could be developed, and this external styling file could be included in HTML
itself. HTML 4.01 provided support for further new tags of HTML.
5. HTML5
This is the latest version of HTML. For a developer, it could be used in 2014. It came up with lots of
HTML tags support. HTML5 provided support for new form elements like input element s of different
types; geolocations support tags, etc.
Email – New HTML5 tag, which was added, is the input element of type email. This is a form tag,
although it could be used outside of a form tag also. This tag checks the validation of the input value. It
checks whether the value inserted is a valid email.
Password – This is another form tag that was added to receive a password from the user. Being the
password type field, the user types in the field are not visible directly to the user but are represented by
special symbols. These symbols save the password from getting revealed on the browser.
Audio tag – This is a new audio tag that was implemented in HTML5. This tag helps to add audio to our
web page. We can use this tag to embed an audio clip into a web page. This audio tag could be played
on a webpage.
Semantic tags – Semantic tags are also known as structural tags. Structural tags are the tags that provide
structure to the HTML page. It helps it divide the HTML page into different structures. These structures
get combined into an HTML page itself to form an HTML web page. Few of the important HTML
semantic tags are figcaption, <header>, <footer>
Section tag – This tag is used to semantic a section in an HTML page. A section tag represents a section
on a web page.
An HTML validator is a web-based tool that is used to maintain or check whether a piece of HTML tag or
HTML is valid. An HTML validator follows the standard of W3C to validate an HTML page. It follows the
W3C standard.
Metadata content
Flow content
Sectioning content
Heading content
Phrasing content
Embedded content
Interactive content
Palpable content
Content models can overlap, and it means that elements are belonging to several categories in the
meantime. For example, sectioning, heading, phrasing, embedded, interactive, and a part of metadata
content refer to flow content. Metadata and interactive content in certain cases may refer to phrasing
content.
What is an Element
An HTML element is an individual component of an HTML document. It represents semantics, or
meaning. For example, the title element represents the title of the document.
Most HTML elements are written with a start tag (or opening tag) and an end tag (or closing tag), with
content in between. Elements can also contain attributes that defines its additional properties. For
example, a paragraph, which is represented by the p element, would be written as:
However, in common usage the terms HTML element and HTML tag are interchangeable i.e. a tag is an
element is a tag. For simplicity's sake of this website, the terms "tag" and "element" are used to mean
the same thing — as it will define something on your web page.
Tag Description
<a> Defines a hyperlink.
<abbr> Defines an abbreviated form of a longer word or phrase.
<acronym> Obsolete Defines an acronym. Use <abbr> instead.
<address> Specifies the author's contact information.
<applet> Obsolete Embeds a Java applet (mini Java applications) on the page. Use <object> instead.
<area> Defines a specific area within an image map.
<article> Defines an article.
<aside> Defines some content loosely related to the page content.
<audio> Embeds a sound, or an audio stream in an HTML document.
<b> Displays text in a bold style.
<base> Defines the base URL for all relative URLs in a document.
<basefont> Obsolete Specifies the base font for a page. Use CSS instead.
<bdi> Represents text that is isolated from its surrounding for the purposes of bidirectional text formattin
<bdo> Overrides the current text direction.
<big> Obsolete Displays text in a large size. Use CSS instead.
<blockquote> Represents a section that is quoted from another source.
<body> Defines the document's body.
<br> Produces a single line break.
<button> Creates a clickable button.
<canvas> Defines a region in the document, which can be used to draw graphics on the fly via scripting (usual
JavaScript).
<caption> Defines the caption or title of the table.
<center> Obsolete Align contents in the center. Use CSS instead.
<cite> Indicates a citation or reference to another source.
<code> Specifies text as computer code.
<col> Defines attribute values for one or more columns in a table.
<colgroup> Specifies attributes for multiple columns in a table.
<data> Links a piece of content with a machine-readable translation.
Tag Description
<datalist> Represents a set of pre-defined options for an <input> element.
<dd> Specifies a description, or value for the term (<dt>) in a description list (<dl>).
<del> Represents text that has been deleted from the document.
<details> Represents a widget from which the user can obtain additional information or controls on-demand.
<dfn> Specifies a definition.
<dialog> Defines a dialog box or subwindow.
<dir> Obsolete Defines a directory list. Use <ul> instead.
<div> Specifies a division or a section in a document.
<dl> Defines a description list.
<dt> Defines a term (an item) in a description list.
<em> Defines emphasized text.
<embed> Embeds external application, typically multimedia content like audio or video into an HTML docume
<fieldset> Specifies a set of related form fields.
<figcaption> Defines a caption or legend for a figure.
<figure> Represents a figure illustrated as part of the document.
<font> Obsolete Defines font, color, and size for text. Use CSS instead.
<footer> Represents the footer of a document or a section.
<form> Defines an HTML form for user input.
<frame> Obsolete Defines a single frame within a frameset.
<frameset> Obsolete Defines a collection of frames or other frameset.
<head> Defines the head portion of the document that contains information about the document such as ti
<header> Represents the header of a document or a section.
<hgroup> Defines a group of headings.
<h1> to <h6> Defines HTML headings.
<hr> Produce a horizontal line.
<html> Defines the root of an HTML document.
<i> Displays text in an italic style.
<iframe> Displays a URL in an inline frame.
<img> Represents an image.
<input> Defines an input control.
<ins> Defines a block of text that has been inserted into a document.
<kbd> Specifies text as keyboard input.
<keygen> Represents a control for generating a public-private key pair.
<label> Defines a label for an <input> control.
<legend> Defines a caption for a <fieldset> element.
<li> Defines a list item.
<link> Defines the relationship between the current document and an external resource.
<main> Represents the main or dominant content of the document.
<map> Defines a client-side image-map.
<mark> Represents text highlighted for reference purposes.
Tag Description
<menu> Represents a list of commands.
<menuitem> Defines a list (or menuitem) of commands that a user can perform.
<meta> Provides structured metadata about the document content.
<meter> Represents a scalar measurement within a known range.
<nav> Defines a section of navigation links.
<noframes> Obsolete Defines an alternate content that displays in browsers that do not support frames.
<noscript> Defines alternative content to display when the browser doesn't support scripting.
<object> Defines an embedded object.
<ol> Defines an ordered list.
<optgroup> Defines a group of related options in a selection list.
<option> Defines an option in a selection list.
<output> Represents the result of a calculation.
<p> Defines a paragraph.
<param> Defines a parameter for an object or applet element.
<picture> Defines a container for multiple image sources.
<pre> Defines a block of preformatted text.
<progress> Represents the completion progress of a task.
<q> Defines a short inline quotation.
<rp> Provides fall-back parenthesis for browsers that that don't support ruby annotations.
<rt> Defines the pronunciation of character presented in a ruby annotations.
<ruby> Represents a ruby annotation.
<s> Represents contents that are no longer accurate or no longer relevant.
<samp> Specifies text as sample output from a computer program.
<script> Places script in the document for client-side processing.
<section> Defines a section of a document, such as header, footer etc.
<select> Defines a selection list within a form.
<small> Displays text in a smaller size.
<source> Defines alternative media resources for the media elements like <audio> or <video>.
<span> Defines an inline styleless section in a document.
<strike> Obsolete Displays text in strikethrough style.
<strong> Indicate strongly emphasized text.
<style> Inserts style information (commonly CSS) into the head of a document.
<sub> Defines subscripted text.
<summary> Defines a summary for the <details> element.
<sup> Defines superscripted text.
<svg> Embed SVG (Scalable Vector Graphics) content in an HTML document.
<table> Defines a data table.
<tbody> Groups a set of rows defining the main body of the table data.
<td> Defines a cell in a table.
<template> Defines the fragments of HTML that should be hidden when the page is loaded, but can be cloned a
Tag Description
inserted in the document by JavaScript.
<textarea> Defines a multi-line text input control (text area).
<tfoot> Groups a set of rows summarizing the columns of the table.
<th> Defines a header cell in a table.
<thead> Groups a set of rows that describes the column labels of a table.
<time> Represents a time and/or date.
<title> Defines a title for the document.
<tr> Defines a row of cells in a table.
<track> Defines text tracks for the media elements like <audio> or <video>.
<tt> Obsolete Displays text in a teletype style.
<u> Displays text with an underline.
<ul> Defines an unordered list.
<var> Defines a variable.
<video> Embeds video content in an HTML document.
<wbr> Represents a line break opportunity.
Approaches
There are many approaches to formal semantics; these belong to three major classes:
Denotational semantics, whereby each phrase in the language is interpreted as a denotation, i.e.
a conceptual meaning that can be thought of abstractly. Such denotations are often
mathematical objects inhabiting a mathematical space, but it is not a requirement that they
should be so. As a practical necessity, denotations are described using some form of
mathematical notation, which can in turn be formalized as a denotational metalanguage. For
example, denotational semantics of functional languages often translate the language into
domain theory. Denotational semantic descriptions can also serve as compositional translations
from a programming language into the denotational metalanguage and used as a basis for
designing compilers.
Operational semantics, whereby the execution of the language is described directly (rather than
by translation). Operational semantics loosely corresponds to interpretation, although again the
"implementation language" of the interpreter is generally a mathematical formalism.
Operational semantics may define an abstract machine (such as the SECD machine), and give
meaning to phrases by describing the transitions they induce on states of the machine.
Alternatively, as with the pure lambda calculus, operational semantics can be defined via
syntactic transformations on phrases of the language itself;
Axiomatic semantics, whereby one gives meaning to phrases by describing the axioms that apply
to them. Axiomatic semantics makes no distinction between a phrase's meaning and the logical
formulas that describe it; its meaning is exactly what can be proven about it in some logic. The
canonical example of axiomatic semantics is Hoare logic.
Apart from the choice between denotational, operational, or axiomatic approaches, most variations in
formal semantic systems arise from the choice of supporting mathematical formalism.
4. While the document outline is primarily defined by the 5 sectioning elements, it also needs proper
headings for each section.
5. It’s always the first heading element (let it be h1 or a lower rank heading tag) that defines the
heading of the given section. The following heading tags inside the same section need to be relative to
this. (If the first heading is an h4 inside a sectioning element, don’t put an h4 after that.)
6. The sections defined by the <nav></nav>, and the <aside></aside> tags don’t belong to the main
outline of the HTML document, they are usually not rendered initially by assistive technologies.
7. Each section (body, section, article, aside, nav) can have their own <header></header> and
<footer></footer> tags, that defines the header (such as logo, author’s name, dates, meta info, etc.)
and the footer (copyright, notes, links, etc.) of that section.
Let’s see an example for a semantic document outline to see clearer how it works. Our example code
will result in the following document structure:
<body>
<header>
</header>
<nav>
<header>
</header>
<ul>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>
</nav>
<article>
<header>
<h1>Title of Article</h1>
<h2>Subtitle of Article</h2>
</header>
<section>
</section>
<section>
</section>
<footer>
<h5>Author Bio</h5>
</footer>
</article>
<aside>
<section>
<h4>Popular Posts</h4>
<ul>...</ul>
</section>
<section>
<h4>Partners</h4>
<ul>...</ul>
</section>
<section>
<h4>Testimonials</h4>
<ul>...</ul>
</section>
</aside>
<footer>
<ul>
<li>Copyright</li>
</ul>
</footer>
</body>
For example, a “<p> </p>” tag indicates that the enclosed text is a paragraph. This is both
semantic and presentational because people know what paragraphs are, and browsers know
how to display them.
Tag Meaning
<abbr> Abbreviation
<acronym> Acronym
<blockquote> Long quotation
<dfn> Definition
<address> Address for author(s) of the document
<cite> Citation
<code> Code reference
<tt> Teletype text
<div> Logical division
<span> Generic inline style container
<del> Deleted text
<ins> Inserted text
<em> Emphasis
<strong> Strong emphasis
<h1> First-level headline
<h2> Second-level headline
<h3> Third-level headline
<h4> Fourth-level headline
<h5> Fifth-level headline
<h6> Sixth-level headline
<hr> Thematic break
<kbd> Text to be entered by the user
<pre> Pre-formatted text
<q> Short inline quotation
<samp> Sample output
<sub> Subscript
<sup> Superscript
<var> Variable or user defined text
Background of XHTML.
XHTML was developed by World Wide Web Consortium (W3C) to help web developers make
the transition from HTML to XML. By migrating to XHTML today, web developers can enter the
XML world with all of its benefits, while still remaining confident in the backward and future
compatibility of the content.
Unfortunately, because of historical reasons, the HTML specification (and all browsers, by default) treat
the <img> tag as if it is an inline element. Because of the way browsers handle white space, this can
cause problems if you are not careful.
There at least two easy ways to fix this. The simplest is to simply make sure there is a line break
before and after your images. This is fine if you don’t care much about flowing text around your
image.
A better, more systematic way of handling the inline image problem is to images into block
elements with CSS.
img {
display: block;
}
<!-- Image is block level. No need for line breaks. -->
This is some text that appears above the image.
<img src="/wp-content/uploads/flamingo.jpg">
Using the display: block; CSS rule is a good default way of presenting images, which you can then
build upon for other types of presentation — such as wrapping text around an image within the
flow of an article.
The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
Example
document.getElementById("demo").style.fontSize = "35px";
Example
document.getElementById("demo").style.display = "none";
Example
document.getElementById("demo").style.display = "block";
Canvas can respond to any user action (key clicks, mouse clicks, button clicks, finger movement).
The <canvas> element is only a container for graphics. You must use a script to actually draw the
graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Canvas has great features for graphical data presentation with an imagery of graphs and charts.
Canvas Example
In HTML, a <canvas> element looks like this:
Line Properties
There are several properties which allow us to style lines.
This property returns the current miter limit ratio and can be set, to change the miter
limit ratio.
Example
Following is a simple example which makes use of lineWidth property to draw lines of
different width.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
</style>
function drawShape() {
for (i=0;i<10;i++){
ctx.lineWidth = 1+i;
ctx.beginPath();
ctx.moveTo(5+i*14,5);
ctx.lineTo(5+i*14,140);
ctx.stroke();
} else {
</script>
</head>
<canvas id = "mycanvas"></canvas>
</body>
</html>
The above example would draw following shape –
The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter, the
type of context “2d” i.e. Two Dimensional.
Following is the code to get required context along with a check if your browser
supports <canvas> element −
if (canvas.getContext) {
} else {
Set font to 30px "Comic Sans MS" and write a filled red text in the center of the canvas:
Code:
External images can be used in any format supported by the browser, such as PNG, GIF, or
JPEG. You can even use the image produced by other canvas elements on the same page as the
source!
HTMLImageElement
SVGImageElement
HTMLCanvasElement
beginPath()
1
This method resets the current path.
moveTo(x, y)
2
This method creates a new subpath with the given point.
closePath()
3
This method marks the current subpath as closed, and starts a new subpath with
a point the same as the start and end of the newly closed subpath.
fill()
4
This method fills the subpaths with the current fill style.
stroke()
5
This method strokes the subpaths with the current stroke style.
drawImage(image, dx, dy)
6 This method draws the given image onto the canvas. Here image is a reference
to an image or canvas object. x and y form the coordinate on the target canvas
where our image should be placed.
Example
Following is a simple example which makes use of above mentioned methods to import
an image.
<!DOCTYPE HTML>
<html>
<head>
function drawShape() {
if (canvas.getContext) {
// Draw shapes
img.src = '/images/backdrop.jpg';
img.onload = function() {
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
} else {
</script>
</head>
<canvas id = "mycanvas"></canvas>
</body>
</html>
SVG is XML based, which means that every element is available within the SVG
DOM. You can attach JavaScript event handlers for an element.
Canvas SVG
Many new syntactic features are included. To natively include and handle multimedia and graphical
content, the new <video>, <audio> and <canvas> elements were added, and support for scalable vector
graphics (SVG) content and MathML for mathematical formulas was also added.
The first factor in HTML vs HTML5 is the introduction of audio and video in HTML5. There was no such
concept of media in case of HTML. But it is one of the integral part of the 5th Version.
Many new syntactic features are included. To natively include and handle multimedia and graphical
content, the new <video>, <audio> and <canvas> elements were added, and support for scalable vector
graphics (SVG) content and MathML for mathematical formulas was also added.
The first factor in HTML vs HTML5 is the introduction of audio and video in HTML5. There was no such
concept of media in case of HTML. But it is one of the integral part of the 5th Version.
Example
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes.
Plug-ins are mainly used to extend the functionality of the Html browser.
Using html, you can add or show your YouTube video on web page.
Steps to add video on web page.
Upload video on YouTube.
get video id.
Define an <iframe> element in your web page.
Specify height and width of iframe for display video.
As a real-world example, think about the electricity supply in your house, apartment, or other
dwellings. If you want to use an appliance in your house, you plug it into a plug socket and it
works. You don't try to wire it directly into the power supply — to do so would be really
inefficient and, if you are not an electrician, difficult and dangerous to attempt.
function allowDrop(ev) {
ev.preventDefault();
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
function drop(ev) {
ev.preventDefault();
The Local Storage is designed for storage that spans multiple windows and lasts beyond the current
session. In particular, Web applications may wish to store megabytes of user data, such as entire user-
authored documents or a user's mailbox, on the client side for performance reasons. Cookies do not
handle this case well because they are transmitted with every request.
Local Storage is available for every page and remains even when the web browser is closed, but you
cannot read it on the server.
The stored data has no expiration date in local storage. With cookies, you can set the expiration
duration.
If you want to clear local storage, then do it by clearing the browser cache. You can also use JavaScript
for this. Local Storage is for client side, whereas cookies are for the client as well as server side
After completing this topic, a student will be able to implement cache in web pages
The information stored in the web storage isn't sent to the web server as opposed to the cookies where
data sent to the server with every request. Also, where cookies let you store a small amount of data
(nearly 4KB), the web storage allows you to store up to 5MB of data.
There are two types of web storage, which differ in scope and lifetime:
Local storage — The local storage uses the local Storage object to store data for your entire website on
a permanent basis. That means the stored local data will be available on the next day, the next week, or
the next year unless you remove it.
Session storage — The session storage uses the session Storage object to store data on a temporary
basis, for a single browser window or tab. The data disappears when session ends i.e., when the user
closes that browser window or tab.
Advantages of Caching
Webpages can be cached pre-fetched on the clients, the proxies, and the servers. There are many
advantages of web caching, including an improved performance of the web.
Caching reduces bandwidth consumption; therefore, it decreases network traffic and diminishes
network congestion
Frequently accessed documents are fetched from a nearby proxy cache instead of remote data
servers; therefore, the transmission delay is minimized.
b) Caching can reduce the network traffic, so those documents that are not cached can also be
retrieved comparatively faster than without caching due to less congestion along the path and
with less work load on the server.
Caching reduces the workload of the remote web server by spreading the data widely among
the proxy caches over the WAN.
In a scenario where the remote server is not available due to a crash or network partitioning,
the client can obtain a cached copy at the proxy. Hence, the robustness of the Web service is
enhanced.
After completing this topic, a student will be able to implement cache in web page
Some texts call a thread a lightweight process. A thread is similar to a real process in
that both have a single sequential flow of control. However, a thread is considered
lightweight because it runs within the context of a full-blown program and takes
advantage of the resources allocated for that program and the program’s
environment.
As a sequential flow of control, a thread must carve out some of its own resources
within a running program. For example, a thread must have its own execution stack
and program counter. The code running within the thread works only within that
context. Some other texts use execution context as a synonym for thread.
After completing this topic, a student will be able to implement cache in web pages
PHP Introduction:
Because we will learn about some server code written in PHP in the lessen let’s look at php basics:
PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
<!DOCTYPE html><html><body>
<?php
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?></body></html>
SSE vs WebSockets
Similarities
I’m certain you’ve noticed certain similarities in the explanation of the two technologies thus far. If you
have, you’re not wrong — they both share the same functionality as you will see in detail now.
Apart from the fact that these two technologies operate through HTTP connections, the most noticeable
similarity is that they function exactly the same way. They both push data from the server to client, a
process also known as server push.
Differences
Obviously, the major difference between WebSockets and Server-Sent Events is that WebSockets are
bidirectional (allowing communication between the client and the server) while SSEs are mono-
directional (only allowing the client to receive data from the server).
As a result, if you are only interested in implementing server push functionalities in your application,
they are both good choices to consider. However, if you’re more interested in a bi-directional
communication system, WebSockets will serve your needs better.
Following is the code to get required context along with a check if your browser supports <canvas>
element −
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
} else {
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
Following are the two important JavaScript methods which would be used to animate an image on a
canvas −
The list does not end here, there are many other interesting things that you can do with CSS.
CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an
element. You can write CSS once; and then the same code can be applied to the groups
of HTML elements, and can also be reused in multiple HTML pages.
Easy Maintenance — CSS provides an easy means to update the formatting of the
documents, and to maintain the consistency across multiple documents. Because the
content of the entire set of web pages can be easily controlled using one or more style
sheets.
Pages Load Faster — CSS enables multiple pages to share the formatting information,
which reduces complexity and repetition in the structural contents of the documents. It
significantly reduces the file transfer size, which results in a faster page loading.
Superior Styles to HTML — CSS has much wider presentation capabilities than HTML
and provide much better control over the layout of your web pages. So, you can give far
better look to your web pages in comparison to the HTML presentational elements and
attributes.
Multiple Device Compatibility — CSS also allows web pages to be optimized for more
than one type of device or media. Using CSS, the same HTML document can be
presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc.
What is Selector?
A CSS selector is a pattern to match the elements on a web page. The style rules associated with
that selector will be applied to the elements that match the selector pattern.
Selectors are one of the most important aspects of CSS as they allow you to target specific
elements on your web page in various ways so that they can be styled.
Several types of selectors are available in CSS, let's take a closer look at them:
Universal Selector
The universal selector, denoted by an asterisk (*), matches every single element on the page.
The universal selector may be omitted if other conditions exist on the element. This selector is
often used to remove the default margins and paddings from the elements for quick testing
purpose.
We will learn more about CSS3 borders and making rounded corners using border-radius
What is CSS?
CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It
allows one to adapt the presentation to different types of devices, such as large screens, small screens,
or printers. CSS is independent of HTML and can be used with any XML-based markup language. The
separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and
tailor pages to different environments. This is referred to as the separation of structure (or: content)
from presentation.
CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes.
1.
1. CSS Borders
The CSS border properties allow you to specify the style, width, and color of an element's border.
1.
2. CSS Border Style
The border-style property can have from one to four values (for the top border, right border, bottom
border, and the left border).
You shall not have to worry if you are unfamiliar with the terms discussed in video. You will be able to
explore more as we dig deeper into the components of this course.
border-width
border-style (required)
border-color
If border-color is omitted, the color applied will be the color of the text.
The border property may be specified using one, two, or three of the values listed below. The
order of the values does not matter.
Values
<line-width>
Sets the thickness of the border. Defaults to medium if absent. See border-width.
<line-style>
Sets the style of the border. Defaults to none if absent. See border-style.
<color>
Sets the color of the border. Defaults to currentcolor if absent. See border-color.
border-image-source
border-image-slice
border-image-width
• background-image
• background-position
• background-size
• background-repeat
• background-attachment
• background-origin
• background-clip
• background-color
You can use any combination of these properties that you like, in almost any order
(although the order recommended in the spec is above). There is a gotcha though:
anything you don’t specify in the background property is automatically set to its
default.
Cards
You can also use the box-shadow property to create paper-like cards:
Code Example:
div.card {
width: 250px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
text-align: center;
}
CSS Borders
The CSS border properties allow you to specify the style, width, and color of an element's border.
CSS Text
Text Color
The color property is used to set the color of the text. The color is specified by:
Look at CSS Color Values for a complete list of possible color values.
The default text color for a page is defined in the body selector.
We Can define both the background-color property and the color property to body:
body {
background-color: lightgrey;
color: blue;
}
text-justify: Specifies how overflowed content that is not displayed should be signaled to the user
text-overflow: Specifies line breaking rules for non-CJK scripts
word-break: Allows long words to be able to be broken and wrap onto the next line
word-wrap: Specifies whether lines of text are laid out horizontally or vertically
Transition + Transformation
In CSS3 we can combine Transition with Transforms, as we have studied Transforms earlier let’s
take an example of this concepts.
div {
transition: width 2s, height 2s, transform 2s;
}
The animation-fill-mode property specifies a style for the target element when the animation is not
playing (before it starts, after it ends, or both).
none - Default value. Animation will not apply any styles to the element before or after it is
executing
forwards - The element will retain the style values that is set by the last keyframe (depends
on animation-direction and animation-iteration-count)
backwards - The element will get the style values that is set by the first keyframe (depends on
animation-direction), and retain this during the animation-delay period
both - The animation will follow the rules for both forwards and backwards, extending the
animation properties in both directions
The following example lets the <div> element retain the style values from the last keyframe when
the animation ends:
div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation-name: example;
animation-duration: 3s;
animation-fill-mode: forwards;
}
A responsive web design will automatically adjust for different screen sizes and viewports.
Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a
website, to make it look good on all devices (desktops, tablets, and phones).
A responsive web design will automatically adjust for different screen sizes and viewports.
Responsive Web Design is about using HTML and CSS to automatically resize, hide, shrink, or enlarge, a
website, to make it look good on all devices (desktops, tablets, and phones).
This will set the viewport of your page, which will give the browser instructions on how to control
the page's dimensions and scaling.
Here is an example of a web page without the viewport meta tag, and the same web page with the
viewport meta tag:
Lesson# 186 - Responsive Web Design (RWD) Grid-View
Learning objectives
What is a Grid-View?
Many web pages are based on a grid-view, which means that the page is divided into columns.
Using a grid-view is very helpful when designing web pages. It makes it easier to place elements on
the page.
A responsive grid-view often has 12 columns, and has a total width of 100%, and will shrink and
expand as you resize the browser window.
In the following snippet, we’re painting the body’s background purple when the viewport width is wider
than 30em and narrower than 80em. If the viewport width does not match that range of values, then it
will fallback to white.
body {
background-color: #fff;
body {
background-color: purple;
}
Media Queries Level 4 specifies a new and simpler syntax using less then (<), greater than (>) and equals
(=) operators.
<picture> lets us continue catering to older browsers. You can supply MIME types
inside type attributes so the browser can immediately reject unsupported file types:
<picture>
</picture>
Do not use the media attribute, unless you also need art direction.
In a <source> element, you can only refer to images of the type declared in type.
Use comma-separated lists with srcset and sizes, as needed.
width: 100%;
height: auto;
Here, the video player can be scaled up to be larger than its original size. A better solution, in many
cases, will be to use the max-width property instead.
If the max-width property is set to 100%, the video player will scale down if it has to, but never scale up
to be larger than its original size.