UI Development -1 ICAT
UI Development -1 ICAT
UI Development -1 ICAT
UNIT - I
INTRODUCTION TO SCRIPTING
Scripting is the action of writing scripts using a scripting language, distinguishing neatly
between programs, which are written in conventional programming language such as
C,C++,java, and scripts, which are written using a different kind of language.
We could reasonably argue that the use of scripting languages is just another kind of
programming. Scripting languages are used for is qualitatively different from conventional
programming languages like C++ and Ada address the problem of developing large
applications from the ground up, employing a team of professional programmers, starting
from well-defined specifications, and meeting specified performance constraints.
The most important difference is that scripting languages incorporate features that enhance
the productivity of the user in one way or another, making them accessible to people who
would not normally describe themselves as programmers, their primary employment being in
some other capacity. Scripting languages make programmers of us all, to some extent.
ActiveVFP
ASP
C
DC
Java
JavaScript (using Server-side JavaScript (SSJS) e.g., node.js)
Perl
PHP
Python
R
Ruby
Generally, compiled programs run faster than interpreted programs because they are first
converted native machine code. Also, compilers read and analyze the code only once, and
report the errors collectively that the code might have, but the interpreter will read and
analyze the code statements each time it meets them and halts at that very instance if there is
some error. In practice, the distinction between the two is getting blurred owing to improved
computation capabilities of the modern hardware and advanced coding practices.
Some scripting languages traditionally used without an explicit compilation step are
JavaScript, PHP, Python, VBScript.
Some programming languages traditionally used with an explicit compilation step are C,
C++.
External References
External scripts can be referenced with a full URL or with a path relative to the current web
page.
This example uses a full URL to link to a script:
<script src="https://www.w3schools.com/js/myScript1.js"></script>
JavaScript is a dynamic or loosely-typed language because a variable can hold value of any
data type at any point of time.
In the above example, myVar will hold last assigned value to it that is string "Steve".
JavaScript - String
String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in
single or double quotation marks.
A string can also be treated like zero index based character array.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String</h1>
<p id="p1"></p> <p id="p2"></p> <p id="p3"></p>
<p id="p4"></p> <p id="p5"></p> <p id="p6"></p>
<script>
var str = 'Hello World';
document.getElementById("p1").innerHTML = str[0];
document.getElementById("p2").innerHTML = str[1];
document.getElementById("p3").innerHTML = str[2];
document.getElementById("p4").innerHTML = str[3];
document.getElementById("p5").innerHTML = str[4];
document.getElementById("p6").innerHTML = str.length
</script>
</body>
</html>
Since, string is character index, it can be accessed using for loop and for-of loop.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String</h1>
<p id="p1"></p> <p id="p2"></p>
<script>
var str = 'Hello World';
for(var i =0; i< str.length;i++)
document.getElementById("p1").innerHTML =
document.getElementById("p1").innerHTML + str[i];
for(var ch of str)
document.getElementById("p2").innerHTML =
document.getElementById("p2").innerHTML + ch;
</script>
</body>
</html>
Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+) operator in
JavaScript.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript String Concatenation</h1>
<p id="p1"></p>
<script>
var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher';
document.getElementById("p1").innerHTML = str;
</script>
</body>
</html>
JavaScript - Number
The Number is a primitive data type in JavaScript. Number type represents integer, float,
hexadecimal, octal or exponential value. First character in a Number type must be an integer
value and it must not be enclosed in quotation marks.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Number in JavaScript</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var int = 100;
var float = 100.5;
var hex = 0xfff;
var exponential = 2.56e3;
var octal = 030;
document.getElementById("p1").innerHTML = int;
document.getElementById("p2").innerHTML = float;
document.getElementById("p3").innerHTML = hex;
document.getElementById("p4").innerHTML = exponential;
document.getElementById("p5").innerHTML = octal;
</script>
</body>
</html>
Number object
JavaScript also provides Number object which can be used with new keyword.
var hex = new Number(0xfff);
Caution: Be careful while working with the Number object because comparison of Number
objects using == operator compares Number objects and not the values. Consider the
following example.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Number object comparison</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var num1 = new Number(100);
var num2 = new Number(100);
var num3 = 100;
document.getElementById("p1").innerHTML = num1 == num2;
document.getElementById("p2").innerHTML = num1 == num3;
document.getElementById("p3").innerHTML = num1 === num3;
document.getElementById("p4").innerHTML = typeof(num1);
document.getElementById("p5").innerHTML = typeof(num3);
</script>
</body>
</html>
Number Properties
The Number type includes some default properties. JavaScript treats primitive values as
object, so all the properties and methods are applicable to both primitive number values and
number objects.
Property Description
MAX_VALUE Returns the maximum number value supported in JavaScript
MIN_VALUE Returns the smallest number value supported in JavaScript
NEGATIVE_INFIN
Returns negative infinity (-Infinity)
ITY
NaN Represents a value that is not a number.
POSITIVE_INFINI
Represents positive infinity (Infinity).
TY
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Number object comparison</h1>
<script>
alert(' Max Value: ' + Number.MAX_VALUE +
'\n Min Value:' + Number.MIN_VALUE +
'\n Negative Infinity:' + Number.NEGATIVE_INFINITY +
'\n Positive Infinity:' + Number.POSITIVE_INFINITY +
'\n NaN:' + Number.NaN
);
</script>
</body>
</html>
Number Methods
The following table lists all the methods of Number type
JavaScript Boolean
Boolean is a primitive data type in JavaScript. Boolean can have only two values, true or
false. It is useful in controlling program flow using conditional statements like if..else, switch,
while, do..while.
<!DOCTYPE html>
<html> <body>
<h1>Demo: JavaScript Boolean</h1>
<script> var YES = true; var NO = false;
alert(YES); alert(NO);
</script>
</body> </html>
The following example demonstrates how a Boolean value controls the program flow using if
condition.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Boolean</h1>
<script>
var YES = true;
var NO = false;
if(YES)
{
alert("This code block will be executed");
}
if(NO)
{
alert("This code block will not be executed");
}
</script>
</body>
</html>
Example: Boolean
In the above example, null is assigned to a variable myVar. It means we have defined a
variable but have not assigned any value yet, so value is absence.
If you try to find DOM element using document.getElelementByID for example, and if
element is found then it will return null. So it is recommended to check for null before doing
something with that element.
undefined
Undefined is also a primitive value in JavaScript. A variable or an object has an undefined
value when no value is assigned before using it. So you can say that undefined means lack of
value or unknown value.
var myVar;
alert(myVar); // undefined
In the above example, we have not assigned any value to a variable named 'myVar'. A
variable 'myVar' lacks a value. So it is undefined.
JavaScript Object
Object is a non-primitive data type in JavaScript. It is like any other variable, the only
difference is that an object holds multiple values in terms of properties and methods.
Properties can hold values of primitive data types and methods are functions.
In other programming languages like Java or C#, you need a class to create an object of it. In
JavaScript, an object is a standalone entity because there is no class in JavaScript.
However, you can achieve class like functionality using functions. We will learn how to treat
a function as a class in the advance JavaScript section.
Let's learn how to create an object in JavaScript.
In JavaScript, an object can be created in two ways:
Object literal
Object constructor
Object Literal
The object literal is a simple way of creating an object using { } brackets. You can include
key-value pair in { }, where key would be property or method name and value will be value
of property of any data type or a function. Use comma (,) to separate multiple key-value
pairs.
Syntax:
var <object-name> = { key1: value1, key2: value2,... keyN: valueN};
Object Constructor
The second way to create an object is with Object Constructor using new keyword. You can
attach properties and methods using dot notation. Optionally, you can also create properties
using [ ] brackets and specifying property name as string.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Object</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
var person = new Object();
// Attach properties and methods to person object
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
// access properties & methods
document.getElementById("p1").innerHTML = person.firstName;
document.getElementById("p2").innerHTML = person.lastName;
document.getElementById("p3").innerHTML = person["firstName"];
document.getElementById("p4").innerHTML = person["lastName"];
document.getElementById("p5").innerHTML = person.getFullName();
</script>
</body>
</html>
JavaScript - Date
The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time,
to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of
plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
JavaScript Array
Objects allow you to store keyed collections of values. That’s fine.
But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd
element and so on.
For example, we need that to store a list of something: users, goods, HTML elements etc.
It is not convenient to use an object here, because it provides no methods to manage the order
of elements. We can’t insert a new property “between” the existing ones.
Objects are just not meant for such use.
There exists a special data structure named Array, to store ordered collections.
Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
let fruits = ["Apple", "Orange", "Plum"];
For instance:
// mix of values
let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];
// get the object at index 1 and then show its name
alert( arr[1].name ); // John
// get the function at index 3 and run it
arr[3](); // hello
Performance
Why is it faster to work with the end of an array than with its beginning? Let’s see what
happens during the execution:
It’s not enough to take and remove the element with the number 0. Other elements need to be
renumbered as well.
The Array object has many properties and methods which help developers to handle arrays
easily and efficiently. You can get the value of a property by specifying arrayname.property
and the output of a method by specifying arrayname.method().
1. length property --> If you want to know the number of elements in an array, you can
use the length property.
2. prototype property --> If you want to add new properties and methods, you can use
the prototype property.
3. reverse method --> You can reverse the order of items in an array using a reverse
method.
4. sort method --> You can sort the items in an array using sort method.
5. pop method --> You can remove the last item of an array using a pop method.
6. shift method --> You can remove the first item of an array using shift method.
7. push method --> You can add a value as the last item of the array.
JAVASCRIPT VARIABLE
JavaScript has variables. Variables can be thought of as named containers. You can place
data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//--></script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//--></script>
Storing a value in a variable is called variable initialization. You can do variable
initialization at the time of variable creation or at a later point in time when you need that
variable.
For instance, you might create a variable named money and assign the value 2000.50 to it
later. For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//--></script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of
any data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
JAVASCRIPT CONSTANT
Constants are block-scoped, much like variables defined using the let statement. The value of
a constant can't be changed through reassignment, and it can't be re-declared.
Global constants do not become properties of the window object, unlike var variables.
The const declaration creates a read-only reference to a value. It does not mean the value it
holds is immutable, just that the variable identifier cannot be reassigned.
For instance, in the case where the content is an object, this means the object's contents (e.g.,
its properties) can be altered.
A constant cannot share its name with a function or a variable in the same scope.
Syntax
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
nameN
The constant's name, which can be any legal identifier.
valueN
The constant's value; this can be any legal expression, including a
function expression.
Example
const number = 42;
try {
number = 99;
}
catch(err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42
POINTERS
No, JS doesn't have pointers.
Objects are passed around by passing a copy of a reference. The programmer cannot access
any C-like "value" representing the address of an object.
Within a function, one may change the contents of a passed object via that reference, but you
cannot modify the reference that the caller had because your reference is only a copy:
var foo = {'bar': 1};
function tryToMungeReference(obj) {
obj = {'bar': 2}; // won't change caller's object}
function mungeContents(obj) {
obj.bar = 2; // changes _contents_ of caller's object}
tryToMungeReference(foo);
foo.bar === 1; // true - foo still references original object
mungeContents(foo);
foo.bar === 2; // true - object referenced by foo has been modified
OPERATORS
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’
is called the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators
Assume variable A holds 10 and variable B holds 20, then
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try…
Comparison Operators
JavaScript supports the following comparison operators
Logical Operators
JavaScript supports the following logical operators
Sr.No. Operator & Description
&& (Logical AND)
1 If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical NOT
3
operator will make it false.
Ex: ! (A && B) is false.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
Bitwise Operators
JavaScript supports the following bitwise operators
Sr.No. Operator & Description
& (Bitwise AND)
1 It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer arguments.
3 Exclusive OR means that either operand one is true or operand two is true, but not
both.
Ex: (A ^ B) is 1.
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the operand.
Ex: (~B) is -4.
5 << (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in
the second operand. New bits are filled with zeros. Shifting a value left by one
position is equivalent to multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.
Ex: (A << 1) is 4.
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of
6
bits specified by the right operand.
Ex: (A >> 1) is 1.
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
7
always zero.
Ex: (A >>> 1) is 1.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
Assignment Operators
JavaScript supports the following assignment operators
Sr.No. Operator & Description
= (Simple Assignment )
1 Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
+= (Add and Assignment)
2 It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
3
operand.
Ex: C -= A is equivalent to C = C - A
*= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result to the left
4
operand.
Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
5
operand.
Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment)
6 It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
Miscellaneous Operator
The conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
Sr.No. Operator and Description
? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be
of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
Tertiary Operators:
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a
condition followed by a question mark (?), then an expression to execute if the condition is
truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
This operator is frequently used as a shortcut for the if statement.
condition ? exprIfTrue : exprIfFalse
STATEMENTS
JavaScript supports a compact set of statements that you can use to incorporate a great deal of
interactivity in Web pages. This chapter provides an overview of these statements.
Use the semicolon (;) character to separate statements in JavaScript code.
Block Statement
A block statement is used to group statements. The block is delimited by a pair of curly
brackets:
{
statement_1;
statement_2;
.
.
.
statement_n;
}
Example
Block statements are commonly used with control flow statements (e.g. if, for, while).
while (x < 10){
x++;
}
Conditional Statements
A conditional statement is a set of commands that executes if a specified condition is true.
JavaScript supports two conditional statements: if...else and switch.
if…else Statement
Use the if statement to execute a statement if a logical condition is true. Use the optional else
clause to execute a statement if the condition is false. An if statement looks as follows:
if (condition)
statement_1
[else
statement_2]
condition can be any expression that evaluates to true or false. If condition evaluates to true,
statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2
can be any statement, including further nested if statements.
You may also compound the statements using else if to have multiple conditions tested in
sequence, as follows:
if (condition)
statement_1
[else if (condition_2)
statement_2]
...
[else if (condition_n_1)
statement_n_1]
[else
statement_n]
switch Statement
A switch statement allows a program to evaluate an expression and attempt to match the
expression’s value to a case label. If a match is found, the program executes the associated
statement. A switch statement looks as follows:
switch (expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}
The program first looks for a case clause with a label matching the value of expression and
then transfers control to that clause, executing the associated statements.
If no matching label is found, the program looks for the optional default clause, and if found,
transfers control to that clause, executing the associated statements.
If no default clause is found, the program continues execution at the statement following the
end of switch. By convention, the default clause is the last clause, but it does not need to be
so.
The optional break statement associated with each case clause ensures that the program
breaks out of switch once the matched statement is executed and continues execution at the
statement following switch.
If break is omitted, the program continues execution at the next statement in the switch
statement.
Example
In the following example, if fruittype evaluates to "Bananas", the program matches the value
with case “Bananas” and executes the associated statement.
When break is encountered, the program terminates switch and executes the statement
following switch.
If break were omitted, the statement for case “Cherries” would also be executed.
switch (fruittype) {
case "Oranges":
document.write("Oranges are $0.59 a pound.<br>");
break;
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Cherries":
document.write("Cherries are $3.00 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
}
document.write("Is there anything else you'd like?<br>");
Control Statements
Loop Statements
A loop is a set of commands that executes repeatedly until a specified condition is met.
JavaScript supports the for, do while, and while loop statements, as well as label (label is not
itself a looping statement, but is frequently used with these statements).
In addition, you can use the break and continue statements within loop statements.
Another statement, for...in, executes statements repeatedly but is used for object
manipulation.
The loop statements are:
for Statement
do…while Statement
while Statement
label Statement
break Statement
continue Statement
for Statement
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is
similar to the Java and C for loop. A for statement looks as follows:
for ([initialExpression]; [condition]; [incrementExpression])
statement
When a for loop executes, the following occurs:
1. The initializing expression initialExpression, if any, is executed. This expression
usually initializes one or more loop counters, but the syntax allows an expression of
any degree of complexity. This expression can also declare variables.
2. The condition expression is evaluated. If the value of condition is true, the loop
statements execute. If the value of condition is false, the for loop terminates. If the
condition expression is omitted entirely, the condition is assumed to be true.
3. The statement executes. To execute multiple statements, use a block statement ({ ... })
to group those statements.
4. The update expression incrementExpression, if there is one, executes, and control
returns to step 2.
do…while Statement
The do...while statement repeats until a specified condition evaluates to false. A do...while
statement looks as follows:
do
statement
while (condition);
statement executes once before the condition is checked. To execute multiple statements, use
a block statement ({ ... }) to group those statements. If condition is true, the statement
executes again. At the end of every execution, the condition is checked. When the condition
is false, execution stops and control passes to the statement following do...while.
while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A
while statement looks as follows:
while (condition)
statement
If the condition becomes false, statement within the loop stops executing and control passes
to the statement following the loop.
The condition test occurs before statement in the loop are executed. If the condition returns
true, statement is executed and the condition is tested again.
If the condition returns false, execution stops and control is passed to the statement following
while.
To execute multiple statements, use a block statement ({ … }) to group those statements.
label Statement
A label provides a statement with an identifier that lets you refer to it elsewhere in your
program. For example, you can use a label to identify a loop, and then use the break or
continue statements to indicate whether a program should interrupt the loop or continue its
execution.
The syntax of the label statement looks like the following:
label :
statement
break Statement
Use the break statement to terminate a loop, switch, or in conjunction with a label statement.
When you use break without a label, it terminates the innermost enclosing while,
do-while, for, or switch immediately and transfers control to the following statement.
When you use break with a label, it terminates the specified labeled statement.
continue Statement
The continue statement can be used to restart a while, do-while, for, or label statement.
When you use continue without a label, it terminates the current iteration of the
innermost enclosing while, do-while or for statement and continues execution of the
loop with the next iteration. In contrast to the break statement, continue does not
terminate the execution of the loop entirely. In a while loop, it jumps back to the
condition. In a for loop, it jumps to the increment-expression.
When you use continue with a label, it applies to the looping statement identified with
that label.
The syntax of the continue statement looks like the following:
1. continue
2. continue label
ARRAYS & STRINGS
The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same
type.
Syntax
Use the following syntax to create an Array object
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The
maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows
var fruits = [ "apple", "orange", "mango" ];
Array Properties
Sr.No. Property & Description
constructor
1
Returns a reference to the array function that created the object.
index
2
The property represents the zero-based index of the match in the string
input
3
This property is only present in arrays created by regular expression matches.
length
4
Reflects the number of elements in an array.
prototype
5
The prototype property allows you to add properties and methods to an object.
Array Methods
Sr.No. Method & Description
concat()
1
Returns a new array comprised of this array joined with other array(s) and/or value(s).
every()
2
Returns true if every element in this array satisfies the provided testing function.
filter()
3 Creates a new array with all of the elements of this array for which the provided
filtering function returns true.
forEach()
4
Calls a function for each element in the array.
indexOf()
5 Returns the first (least) index of an element within the array equal to the specified
value, or -1 if none is found.
join()
6
Joins all elements of an array into a string.
lastIndexOf()
7 Returns the last (greatest) index of an element within the array equal to the specified
value, or -1 if none is found.
map()
8 Creates a new array with the results of calling a provided function on every element in
this array.
pop()
9
Removes the last element from an array and returns that element.
push()
10 Adds one or more elements to the end of an array and returns the new length of the
array.
reduce()
11 Apply a function simultaneously against two values of the array (from left-to-right) as
to reduce it to a single value.
reduceRight()
12 Apply a function simultaneously against two values of the array (from right-to-left) as
to reduce it to a single value.
reverse()
13 Reverses the order of the elements of an array -- the first becomes the last, and the last
becomes the first.
shift()
14
Removes the first element from an array and returns that element.
slice()
15
Extracts a section of an array and returns a new array.
some()
16
Returns true if at least one element in this array satisfies the provided testing function.
toSource()
17
Represents the source code of an object
sort()
18
Sorts the elements of an array
splice()
19
Adds and/or removes elements from an array.
toString()
20
Returns a string representing the array and its elements.
unshift()
21 Adds one or more elements to the front of an array and returns the new length of the
array.
String
The String object lets you work with a series of characters; it wraps Javascript's string
primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can
call any of the helper methods of the String object on a string primitive.
Syntax
Use the following syntax to create a String object
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.
String Properties
Sr.No. Property & Description
constructor
1
Returns a reference to the String function that created the object.
length
2
Returns the length of the string.
prototype
3
The prototype property allows you to add properties and methods to an object.
String Methods
r.No. Method & Description
charAt()
1
Returns the character at the specified index.
charCodeAt()
2
Returns a number indicating the Unicode value of the character at the given index.
concat()
3
Combines the text of two strings and returns a new string.
indexOf()
4 Returns the index within the calling String object of the first occurrence of the specified
value, or -1 if not found.
lastIndexOf()
5 Returns the index within the calling String object of the last occurrence of the specified
value, or -1 if not found.
localeCompare()
6 Returns a number indicating whether a reference string comes before or after or is the
same as the given string in sort order.
match()
7
Used to match a regular expression against a string.
replace()
8
Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search()
9
Executes the search for a match between a regular expression and a specified string.
slice()
10
Extracts a section of a string and returns a new string.
split()
11
Splits a String object into an array of strings by separating the string into substrings.
substr()
12 Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring()
13
Returns the characters in a string between two indexes into the string.
toLocaleLowerCase()
14 The characters within a string are converted to lower case while respecting the current
locale.
toLocaleUpperCase()
15 The characters within a string are converted to upper case while respecting the current
locale.
toLowerCase()
16
Returns the calling string value converted to lower case.
toString()
17
Returns a string representing the specified object.
toUpperCase()
18
Returns the calling string value converted to uppercase.
valueOf()
19
Returns the primitive value of the specified object.
FUNCTIONS
What is a Function?
A function is a subprogram designed to perform a particular task.
Functions are executed when they are called. This is known as invoking a function.
Values can be passed into functions and used within the function.
Functions always return a value. In JavaScript, if no return value is specified, the function
will return undefined.
Define a Function.
There are a few different ways to define a function in JavaScript:
A Function Declaration defines a named function. To create a function declaration you use
the function keyword followed by the name of the function. When using function
declarations, the function definition is hoisted, thus allowing the function to be used before it
is defined.
function name(parameters){
statements
}
An Arrow Function Expression is a shorter syntax for writing function expressions. Arrow
functions do not create their own this value.
Arguments, on the other hand, are the values the function receives from each parameter when
the function is executed (invoked). In the above example, our two arguments are true & false.
Invoking a Function.
Functions execute when the function is called. This process is known as invocation. You can
invoke a function by referencing the function name, followed by an open and closed
parenthesis: ().
To invoke our function, we call it, while passing in the singular parameter. Here I am calling
this function with the name Joe:
logIt('Joe');
// Joe
If your function has no parameters, you can invoke it with an empty set of parenthesis:
function logIt2(){
console.log('The second one');
}logIt2();
// The second one
Function Return.
Every function in JavaScript returns undefined unless otherwise specified.
Let’s test this by creating and invoking an empty function:
function test(){};test();
// undefined
Pass by Value:
In Pass by Value, Function is called by directly passing the value of the variable as the
argument. Changing the argument inside the function doesn’t affect the variable passed from
outside the function.
Javascript always pass by value so changing the value of the variable never changes the
underlying primitive (String or number).
function callByValue(varOne, varTwo) {
console.log("Inside Call by Value Method");
varOne = 100;
varTwo = 200;
console.log("varOne =" + varOne +"varTwo =" +varTwo);
} let varOne = 10;
let varTwo = 20; console.log("Before Call by Value Method");
console.log("varOne =" + varOne +"varTwo =" +varTwo); callByValue(varOne,
varTwo) console.log("After Call by Value Method");
console.log("varOne =" + varOne +"varTwo =" +varTwo);
output will be :
---------------
Before Call by Value Method
varOne =10 varTwo =20
Inside Call by Value Method
varOne =100 varTwo =200
After Call by Value Method
varOne =10 varTwo =20
However, when a variable refers to an object which includes array, the value is the reference
to the object.
Pass by Reference:
In Pass by Reference, Function is called by directly passing the reference/address of the
variable as the argument. Changing the argument inside the function affect the variable
passed from outside the function. In Javascript objects and arrays follows pass by reference.
function callByReference(varObj) {
console.log("Inside Call by Reference Method");
varObj.a = 100;
console.log(varObj);
}
let varObj = {a:1};console.log("Before Call by Reference Method");
console.log(varObj);callByReference(varObj) console.log("After Call by Reference
Method");
console.log(varObj);output will be :
--------------- Before Call by Reference Method
{a: 1}
Inside Call by Reference Method
{a: 100}
After Call by Reference Method
{a: 100}
so if we are passing object or array as an argument to the method, then there is a possibility
that value of the object can change.
Within the function we are modifying the Formal Argument value and then outside of the
function we are printing the value of the old variable and we are seeing that the value within
the function has been changed though it is not reflected outside of the function.
The reason is, when are sending data to the function the new copy of the same variable is
being created within the calling function and the modification is happening to this local
variable, it's not effecting the original variable. This is the example of Call by Value in
JavaScript.
In this example we are sending a "person" object as a function argument and within the
function we are modifying a value (read property) of the object and we are seeing that that
actual object is affected. So, in an actual scenario, we are not sending a copy of an object,
we are sending an actual object as its reference.
Overloading
JavaScript does not support Function Overloading. The following shows function
overloading −
function funcONE(x,y) {
return x*y;}function funcONE(z) {
return z;}
The above will not show an error, but you won't get desired results. On calling,
// prints 5
funcONE(5);
// prints 5, not 30
funcONE(5,6);
JavaScript does not support function overloading natively. If we will add functions with the
same name and different arguments, it considers the last defined function.
Overriding
The JavaScript supports overriding, not overloading. When you define multiple functions
which have the same name, the last one defined will override all the previously defined ones
and every time when you invoke a function, the last defined one will get executed. The
following example overrides the user-defined function.
JavaScript Demo - Overriding user-defined function
<script type="text/javascript">
function multiplyNum(x, y, z) {
return x * y * z;
}
function multiplyNum(x, y) {
return x * y;
}
var result = multiplyNum(1, 2, 3);
document.write(result);
Output
2
Looking at the above example, the value of multiplication will be equal to 2 instead of 6.
In this case, the only function available is multiplyNum(x, y). So if we think we are making a
call to multiplyNum(x, y, z), it's actually calling multiplyNum(x, y). The remaining
parameter(s) will be ignored.
We can also override Javascript built-in functions. The following example overrides the
built-in JavaScript alert() function.
Learn JavaScript
By default, alert() function displays the message in the alert box. But here we have
overridden it. Now it is displaying the message in the document.
Recursive
Recursive function is a technique for iterating over an operation by having a function call
itself repeatedly until it arrives at a result. Most loops can be rewritten in a recursive style,
and in some functional languages this approach to looping is the default.
The three key features of recursion
All recursive functions should have three key features:
A Termination Condition
Simply put: if(something bad happened){ STOP }; The Termination Condition is our
recursion fail-safe. Think of it like your emergency brake. It’s put there in case of bad input
to prevent the recursion from ever running.
In our factorial example, if (x < 0) return; is our termination condition. It’s not possible to
factorial a negative number and thus, we don’t even want to run our recursion if a negative
number is input.
A Base Case
Simply put: if(this happens) { Yay! We're done }; The Base Case is similar to our termination
condition in that it also stops our recursion.
But remember, the termination condition is a catch-all for bad data. Whereas the base case is
the goal of our recursive function. Base cases are usually within an if statement.
In the factorial example, if (x === 0) return 1; is our base case. We know that once we’ve
gotten x down to zero, we’ve succeeded in determining our factorial!
The Recursion
Simply put: Our function calling itself. In the factorial example, return x * factorial(x — 1);
is where the recursion actually happens. We’re returning the value of the number x multiplied
by the value of whatever factorial(x-1) evaluates to.
function factorial(x) {
// TERMINATION
if (x < 0) return;
// BASE
if (x === 0) return 1;
// RECURSION
return x * factorial(x - 1);
}factorial(3);
// 6
Factorial Function Flow
Lets examine exactly what happens when we call our Factorial Function:
1. We first call our function passing in the value of 3.
factorial(3);
2. This results in the function being run. Both if statements fail and our recursion line runs.
We return the integer 3 multiplied by the value of factorial(3-1).
return 3 * factorial(2);
3. When factorial(2) is run, both if statements fail again and recursion occurs. We return the
integer 2 multiplied by the value of factorial(2-1).
return 2 * factorial(1);
4. When factorial(1) is run, both if statements fail again and recursion occurs. We return the
integer 1 multiplied by the value of factorial(1-1).
return 1 * factorial(0);
5. When factorial(0) is run, something different happens. Zero is our base case, so that if
statement passes and our function returns 1.
if (x === 0)
return 1;
DERIVED DATA TYPES
Array
Objects allow you to store keyed collections of values. That’s fine.
But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd
element and so on.
For example, we need that to store a list of something: users, goods, HTML elements etc.
It is not convenient to use an object here, because it provides no methods to manage the order
of elements. We can’t insert a new property “between” the existing ones.
Objects are just not meant for such use.
There exists a special data structure named Array, to store ordered collections.
Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
let fruits = ["Apple", "Orange", "Plum"];
For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out)
principle. For queues, we have FIFO (First-In-First-Out).
Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove
elements both to/from the beginning or the end.
In computer science the data structure that allows it is called deque.
Performance
Why is it faster to work with the end of an array than with its beginning? Let’s see what
happens during the execution:
It’s not enough to take and remove the element with the number 0. Other elements need to be
renumbered as well.
Move all elements to the left, renumber them from the index 1 to 0, from 2 to 1 and so on.
The more elements in the array, the more time to move them, more in-memory
operations.
The similar thing happens with unshift: to add an element to the beginning of the array, we
need first to move existing elements to the right, increasing their indexes.
And what’s with push/pop? They do not need to move anything. To extract an element from
the end, the pop method cleans the index and shortens length.
The actions for the pop operation:
fruits.pop(); // take 1 element from the end
The Array object has many properties and methods which help developers to handle arrays
easily and efficiently. You can get the value of a property by specifying arrayname.property
and the output of a method by specifying arrayname.method().
length property --> If you want to know the number of elements in an array, you can
use the length property.
prototype property --> If you want to add new properties and methods, you can use the
prototype property.
reverse method --> You can reverse the order of items in an array using a reverse
method.
sort method --> You can sort the items in an array using sort method.
pop method --> You can remove the last item of an array using a pop method.
shift method --> You can remove the first item of an array using shift method.
push method --> You can add a value as the last item of the array.
Union
Union is a collection of variables of different data types, in case of union information can
only be stored In one field at any one time.
A unionis a special data type available in C that enables you to store different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.
Declaring Union
union union-name {
data_type var-name;
data_type var-name;
};
The union tagis optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition.
At the end of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional.
Here is the way you would define a union type named Data which has the three members i, f,
and str.
Now, a variable of Datatype can store an integer, a floating-point number, or a string of
characters. This means that a single variable ie. same memory location can be used to store
multiple types of data.
You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the
union.
For example, in above example Data type will occupy 20 bytes of memory space because this
is the maximum space which can be occupied by character string. Following is the example
which will display total memory size occupied by the above union:
Accessing a Member of a Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;}
Dot operator can be used to access a member of the union . The member access operator is
coded as a period between the union variable name and the union member that we wish to
access. You would use union keyword to define variables of union type.
Enum
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented
languages like Java and C# use enums. This is now available in TypeScript too.
In simple words, enums allow us to declare a set of named constants i.e. a collection of
related values that can be numeric or string values.
There are three types of enums:
Numeric enum
String enum
Heterogeneous enum
Numeric Enum
Numeric enums are number-based enums i.e. they store string values as numbers.
Enums can be defined using the keyword enum. Let's say we want to store a set of print
media types. The corresponding enum in TypeScript would be:
Computed Enums:
Numeric enums can include members with computed numeric value. The value of an enum
member can be either a constant or computed.
The following enum includes members with computed values.
PrintMedia.Newsetter; // returns 5
PrintMedia.Magazine; // returns 15
When the enum includes computed and constant members, then uninitiated enum members
either must come first or must come after other initialized members with numeric constants.
The following will give an error.
enum PrintMedia {
Newsletter = getPrintMediaCode('newsletter'),
Newspaper, // Error: Enum member must have initializer
Book,
Magazine = Newsletter * 3,
}
The above enum can be declared as below.
enum PrintMedia {
Newspaper,
Book,
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3
}// orenum PrintMedia {
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3,
Newspaper = 0,
Book,
}
String Enum
String enums are similar to numeric enums, except that the enum values are initialized with
string values rather than numeric values.
The benefits of using string enums is that string enums offer better readability. If we were to
debug a program, it is easier to read string values rather than numeric values.
Consider the same example of a numeric enum, but represented as a string enum:
Heterogeneous Enum
Heterogeneous enums are enums that contain both string and numeric values.
Example: Heterogeneous Enum
enum Status {
Active = 'ACTIVE',
Deactivate = 1,
Pending
}
Reverse Mapping
Enum in TypeScript supports reverse mapping. It means we can access the value of a member
and also a member name from its value. Consider the following example.
Example: Reverse Mapping
enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}
PrintMedia.Magazine; // returns 3
PrintMedia["Magazine"];// returns 3
PrintMedia[3]; // returns Magazine
As you can see in the above example, PrintMedia[3] returns its member name "Magazine".
This is because of reverse mapping.
Let's see how TypeScript implements reverse mapping using the following example.
enum PrintMedia {
Newspaper = 1,
Newsletter,
Magazine,
Book
}
console.log(PrintMedia)
The above example gives the following output in the browser console.
{
'1': 'Newspaper',
'2': 'Newsletter',
'3': 'Magazine',
'4': 'Book',
Newspaper: 1,
Newsletter: 2,
Magazine: 3,
Book: 4
}
You will see that each value of the enum appears twice in the internally stored enum object.
We know that num values can be retrieved using the corresponding enum member value.
But it is also true that enum members can be retrieved using their values. This is called
reverse mapping.
TypeScript can compile the above enum into the following JavaScript function.
STRUCTURE:
A Structure is a user defined data type that can store related information together.
The variable within a structure are of different data types and each has a name that is used to
select it from the structure.C arrays allow you to define type of variables that can hold several
data items of the same kind but structure is another user defined data type available in C
programming, which allows you to combine data items of different kinds.
Structures are used to represent a record, Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book:
•Title
•Author
•Subject
•Book ID
Structure Declaration It is declared using a keyword struct followed by the name of the
structure. The variables of the structure are declared within the structure.
Example:
Struct struct-name {
data_type var-name;
data_type var-name; };
Structure Initialization Assigning constants to the members of the structure is called
initializing ofstructure.
Syntax:
struct struct_name {
data _type member_name1;
data _type member_name2;
}
struct_var={constant1,constant2};
Accessing the Members of a structure A structure member variable is generally accessed
using a ‘.’ operator.
Syntax:
strcut_var. member_name;
The dot operator is used to select a particular member of the structure.
To assign value to the individual Data members of the structure variable stud, we write,
stud.roll=01;
stud.name=”Rahul”;
To input values for data members of the structure variable stud, can be written as,
scanf(“%d”,&stud.roll);scanf(‘’%s”,&stud.name);
To print the values of structure variablestud, can be written as:
printf(“%s”,stud.roll);printf(“%f”,stud.name);
NESTED STRUCTURES
The structure that contains another structure as its members is called a nested structure or a
structure within a structure is called nested structure.
The structure should be declared separately and then be grouped into high level structure.
Passing Structures through pointers Pointer to a structure is a variable that holds the address
of a structure.
The syntax to declare pointer to a structure can be given as:
strcut struct_name *ptr;
To assign address of stud to the pointer using address operator(&) we would write
ptr_stud=&stud;
To access the members of the structure (->) operator is used. for example
Ptr_stud->name=Raj;
{ lines of code} };
OOPS Constructor
But creating objects of this kind is not that useful because here also, you will have to create
different objects for different students. Here comes object constructor into picture. Object
constructor helps you create an object type which can be reused to meet the need of
individual instance.
<html>
<head>
<script type="text/javascript">
function Student(first, last, id, english, maths, science)
{
this.fName = first;
this.lName = last;
this.id = id;
this.markE = english;
this.markM = maths;
this.markS = science;
this.calculateAverage = function()
{
return (this.markE + this.markM + this.markS)/3;
}
this.displayDetails = function()
{
document.write("Student Id: " + this.id + "<br />");
document.write("Name: " + this.fName + " " + this.lName + "<br
/>");
var avg = this.calculateAverage();
document.write("Average Marks: " + avg + "<br /><br />");
}
}
var st1 = new Student("John", "Smith", 15, 85, 79, 90);
var st2 = new Student("Hannah", "Turner", 23, 75, 80, 82);
var st3 = new Student("Kevin", "White", 4, 93, 89, 90);
var st4 = new Student("Rose", "Taylor", 11, 55, 63, 45);
st1.displayDetails();
st2.displayDetails();
st3.displayDetails();
st4.displayDetails();
</script>
</head>
<body>
</body>
</html>
EXCEPTIONAL HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (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.
<script type = "text/javascript">
<!--
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
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
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.
<script type = "text/javascript">
<!--
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.
The try block must be followed by either exactly one catch block or one finally block (or
one of both). When an exception occurs in the try block, the exception is placed in e and the
catch block is executed. The optional finally block executes unconditionally after try/catch.
Examples
Here is an example where we are trying to call a non-existing function which in turn is
raising an exception. Let us see how it behaves without try...catch−
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script> </head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
Now let us try to catch this exception using try...catch and display a user-friendly message.
You can also suppress this message, if you want to hide this error from a user.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
You can use finally block which will always execute unconditionally after the try/catch. Here
is an example.
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body></html>
UNIT - II
ADVANCED JAVA SCRIPT
DOCUMENT OBJECT MODEL
What is Document Object Model (DOM)
The Document Object Model (DOM) is an API for manipulating HTML and XML
documents.
The DOM represents a document as a tree of nodes. It provides API that allows you to add,
remove, and modify parts of the document effectively.
Note that the DOM is cross-platform and language-independent ways of manipulating HTML
and XML documents.
A document as a hierarchy of nodes
The DOM represents an HTML or XML document as a hierarchy of nodes. Consider the
following HTML document:
<html>
<head>
<title>JavaScript DOM</title>
</head>
<body>
<p>Hello DOM!</p>
</body>
</html>
The following tree represents the above HTML document:
In this DOM tree, the root node is a document node. The root node has only one child which
is the <html> element. The html element is called the document element.
Each document can have only one document element. In HTML pages, the document element
is the <html> element. Each markup can be represented by a node in the tree.
Node Types
Each node in the DOM tree is identified by a node type. JavaScript uses integer numbers to
determine node types. The following table illustrates the node type constants:
Constant Value Description
Node.ELEMENT_NODE 1 An Element node like <p> or <div>.
The actual Text inside an Element or
Node.TEXT_NODE 3
Attr.
A CDATASection, such as
Node.CDATA_SECTION_NODE 4
<!CDATA[[ … ]]>.
A ProcessingInstruction of an XML
Node.PROCESSING_INSTRUCTION_NODE 7 document, such as
<?xml-stylesheet … ?>.
Node.COMMENT_NODE 8 A Comment node, such as <!-- … -->.
Node.DOCUMENT_NODE 9 A Document node.
A DocumentType node, such as
Node.DOCUMENT_TYPE_NODE 10
<!DOCTYPE html>.
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.
The document node (shown as #document) at the top of the tree is called the root
node,because it has no parent. The HEAD and BODY nodes are siblings, since they are both
children of the HTMLnode.
The HEAD contains two #comment nodes, representing lines 5–6. The TITLE node has a
child text node (#text) containing the text DOM Tree Demonstration, visible in theright pane
of the DOM inspector when the text node is selected.
The BODY node containsnodes representing each of the elements in the page. Note that the
LI nodes are childrenof the UL node, since they are nested inside it.
The DOM gives you access to the elements of a document, allowing you to modify
thecontents of a page dynamically using event-driven JavaScript.
Each element has an idattribute, which is also displayed at the beginning of the element in
square brackets.
Forexample, the id of the h1 element in lines
<body onload ="currentNode = document.getElementById( 'bigheading' )">
<h1 id = "bigheading"class = "highlighted">
[bigheading] DHTML Object Model
</h1>
is set to bigheading, and the headingtext begins with [bigheading]. This allows the user to
see the id of each element in thepage.
The HTML DOM model is constructed as a tree of Objects
With a programmable object model, JavaScript gets all the power it needs to create dynamic
HTML:
•JavaScript can change all the HTML elements in the page
•JavaScript can change all the HTML attributes in the page
•JavaScript can change all the CSS styles in the page
•JavaScript can react to all the events in the page
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event
attribute:
onclick=JavaScript
Examples of HTML events:
•When a user clicks the mouse
•When a web page has loaded
•When an image has been loaded
•When the mouse moves over an element
•When an input field is changed
•When an HTML form is submitted
•When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
Example Explained
This code creates a new <p> element:
var para=document.createElement("p");
To add text to the <p> element, you must create a text node first.
This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.This code finds an existing
element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);
INTRODUCTION - ARRAYS
In JavaScript, an array is an ordered list of data. An array has the following special
characteristics in comparison with the array of other programming languages such as Java
and C/C++.
1. First, an array can hold data of the different types in each slot i.e., an array can hold
elements with mixed of numbers, strings, objects, etc.
2. Second, the length of an array is dynamically sized and auto-growing.
The array literal form uses the square brackets [] to wrap a comma-separated list of elements.
For example, the following statement creates colors array of three colors:
The following statements show how to access the elements of the mountains array.
console.log(mountains[0]); // 'Everest'
console.log(mountains[1]); // 'Fuji'
console.log(mountains[2]); // 'Nanga Parbat'
To change the value of an element in the array, you use assign that element a value as
follows:
mountains[2] = 'K2';
The size of an array
The array uses the length property to store the current number of elements it holds. You can
access get the value of the length property as shown in the following example.
console.log(mountains.length); // 3
The length property is writable therefore you can insert or delete elements by changing the
value of the length property.
If you set the length property to a value that is greater than the number of elements in the
array, the new elements will be added with the initial values of undefined.
For example, we change the length property of the mountains array to 4 to append one
element with an initial value of undefined at the end of the array.
// append 1 element
mountains.length = 4;
console.log(mountains[3]); // undefined
Similarly, the following example sets the length property of the mountains array to 2 to
remove the last two elements of the array. When we access the third element of the array, it
returns undefined.
// remove the last 2 elements
mountains.length = 2;
console.log(mountains[2]); // undefined
Note that the maximum number of elements that the JavaScript array can hold is
4,294,967,295 which is sufficient enough for a typical application.
Basic operations on arrays
All arrays are instances of the Array type. Therefore, the typeof of an array variable returns
object as shown in the following example:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
console.log(typeof seas); // object
When you call the toString() and valueOf() methods of an array, you get a string represented
as a comma-separated list of elements as shown in the following example:
console.log(seas.toString()); // Black Sea,Caribbean Sea,North Sea,Baltic Sea
console.log(seas.valueOf());
If you want to have a string representation of an array differently, you can use the join()
method.
The following example uses the join() method to returns a string representation of the
mountains array. However, the elements are separated by the pipe (|) character instead.
console.log(seas.join('|'));
// Black Sea|Caribbean Sea|North Sea|Baltic Sea
If an element of the array is null or undefined, the toString(), valueOf(), and join() will treats
it as an empty string in the resulting string. Here is an example.
let mixedValues = [1, 2, null, 'A', undefined, 3];
console.log(mixedValues.toString()); // 1,2,,A,,3
In the activities array, the first dimension represents the activity and the second one shows
the number of hours spent per day for each.
The following figure illustrates the activities array:
To access an element of the multidimensional array, you first use square brackets to access an
element of the outer array that returns an inner array; and use another square bracket to
access the element of the inner array.
The following example returns the second element of the first inner array in the activities
array above.
console.log(activities[0][1]); // 9
activities.push(['Study',2]);
This example calculates the percentage of the hours spent on each activity and appends the
percentage to the inner array.
Similarly, you can remove the elements from the inner array of the multidimensional array by
using the pop() method.
Here is an example of removing the percentage element from the inner arrays of the activities
array.
for (var i = 0; i < activities.length; i++) {
activities[i].pop(2);
}
console.log(activities.join('\n'));
Work,9
Eat,2
Commute,2
Play Game,2
Sleep,7
The following shows the output of the script in the web console.
[0,0] = Work
[0,1] = 9
[1,0] = Eat
[1,1] = 2
[2,0] = Commute
[2,1] = 2
[3,0] = Play Game
[3,1] = 2
[4,0] = Sleep
[4,1] = 7
CALLBACK FUNCTIONS
Callback Definition
A callback function is a function that is passed as an argument to another function, to be
“called back” at a later time. A function that accepts other functions as arguments is called a
higher-order function, which contains the logic for when the callback function gets
executed. It’s the combination of these two that allow us to extend our functionality.
To implement a callback function, the JavaScript code in a page must first define the function.
The following sample code defines a function and stores a variable reference to it:
var callbackDefinition = function(numParam) {
alert(numParam);
};
The function uses a numerical parameter for demonstration.
The callback function can contain any JavaScript code a standard function could include. The
code will now be able to pass a reference to the function as parameter to another function,
using the variable name.
Callback Parameter
Once a script has a function defined as a variable, it can pass that variable as parameter to
another function. The following sample code demonstrates the technique:
mainFunction(10, callbackDefinition);
This code calls a named function, passing a number parameter and the name of the variable
storing the callback function code.
The outline of the function being called here must match these two parameters. The function
receiving the callback variable will be able to call the function it stores.
Function Execution
Once passed to the main function, a callback function can be executed. The following sample
code demonstrates:
function mainFunction(myNum, callbackFn) {
alert(myNum); callbackFn(myNum*2);
}
For demonstration, this code first outputs a JavaScript alert which will cause a dialog to
appear in the user's browser. Once this code executes, the function calls the callback function
using the name specified as parameter.
The callback function call includes a numerical parameter, which is expected by the function
that was initially defined as a variable.
Function Call
Once a page has a function defined, including a callback, it can execute this code. Often,
developers instruct the browser to listen for a user event, executing functions when this
occurs.
For example, the following HTML code calls a function:
Here is a click-able section
If the function specified as parameter contains the callback variable definition and the call to
the main function, this will create the callback effect, as follows:
function doCallback() {
var callFn = function(numParam) { alert(numParam); };
mainFunction(10, callFn);
}
Once the main function executes its own code content, it calls the callback function.
To illustrate callbacks, let’s start with a simple example:
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2}
function logQuote(quote){
console.log(quote);}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!
In the above example, createQuote is the higher-order function, which accepts two arguments,
the second one being the callback.
The logQuote function is being used to pass in as our callback function.
When we execute the createQuote function (1), notice that we are not appending parentheses
to logQuote when we pass it in as an argument.
This is because we do not want to execute our callback function right away, we simply want
to pass the function definition along to the higher-order function so that it can be executed
later.
Also, we need to ensure that if the callback function we pass in expects arguments, that we
supply those arguments when executing the callback (2).
In the above example, that would be the callback(myQuote); statement, since we know that
logQuote expects a quote to be passed in.
Additionally, we can pass in anonymous functions as callbacks. The below call to
createQuote would have the same result as the above example:
Incidentally, you don’t have to use the word “callback” as the name of your argument,
Javascript just needs to know that it’s the correct argument name.
Based on the above example, the below function will behave in exactly the same manner.
function createQuote(quote, functionToCall) {
var myQuote = "Like I always say, " + quote;
functionToCall(myQuote);
}
functionName(argument1, argument2);
When you call a function, you can pass along some values to it, these values are called
arguments or parameters.
These arguments can then be used inside of the function.
You can send as many arguments as you like, separated by commas (,)
To use the arguments inside of the function, you must declare the arguments as variables
when defining the function
The variables and arguments must be in expected order.
That is, the first argument gets assigned to the first variable.
functionTwo(functionOne);
Because you can assign functions to variables, and because functions are objects in
JavaScript, you can pass functions to other functions as variables
Which means that in this case, we are passing functionOne as a variable to be used inside of
functionTwo
Inside of functionTwo, var1's value will be functionOne
This is how you can pass functions to other functions in JavaScript.
In this case, functionTwo can use functionOne inside of it.
FORM HANDLING
GET/POST METHOD
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
FORM VALIDATION
Form validation normally used to occur at the server, after the client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client was
incorrect or was simply missing, the server would have to send all the data back to the client
and request that the form be resubmitted with correct information. This was really a lengthy
process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to
the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and check
for data.
Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test correctness of
data.
Example
We will take an example to understand the process of validation. Here is a simple form in
html format.
<html> <head>
<title>Form Validation</title>
<script type = "text/javascript">
<!-- // Form validation code will come here. //-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body></html>
Example
Email validation.
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
Password Validation
Sometimes a password validation in a form is essential. You can create a password in
different ways, it's structure may be simple, reasonable or strong. Here we validate various
type of password structure through JavaScript codes and regular expression.
Check a password between 7 to 16 characters which contain only characters, numeric
digits and underscore and first character must be a letter.
Check a password between 6 to 20 characters which contain at least one numeric digit,
one uppercase and one lowercase letter.
Check a password between 7 to 15 characters which contain at least one numeric
digit and a special character.
Check a password between 8 to 15 characters which contain at least one lowercase letter,
one uppercase letter, one numeric digit, and one special character.
Following code blocks contain actual codes for the said validations. We have kept the CSS
code part common for all the validations.
To check a password between 7 to 16 characters which contain only characters, numeric
digits, underscore and first character must be a letter
To validate the said format we use the regular expression ^[A-Za-z]\w{7,15}$, where \w
matches any word character (alphanumeric) including the underscore (equivalent to
[A-Za-z0-9_]). Next the match() method of string object is used to match the said regular
expression against the input value. Here is the complete web document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - Password Checking - 1</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input Password and Submit [7 to 15 characters which contain only
characters, numeric digits, underscore and first character must be a
letter]</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li> </li>
<li class="submit"><input type="submit" name="submit"
value="Submit"
nclick="CheckPassword(document.form1.text1)"/> </li>
<li> </li>
</ul>
</form>
</div>
<script src="check-password-1.js"></script>
</body>
</html>
function CheckPassword(inputtxt) {
var passw= /^[A-Za-z]\w{7,14}$/;
if(inputtxt.value.match(passw)) {
alert('Correct, try another...')
return true; }
else {
alert('Wrong...!') return false;
}
}
Number Validation
The validating phone number is an important point while validating an HTML form. In this
page we have discussed how to validate a phone number (in different format) using
JavaScript :
At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation
and there will be no + sign in front the number. Simply the validation will remove all
non-digits and permit only phone numbers with 10 digits. Here is the function.
function phonenumber(inputtxt) {
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno)) {
return true; }
else {
alert("message");
return false; }
}
HTML Events
Events are actions or occurrences that happen in the system you are programming, which the
system tells you about so you can respond to them in some way if desired. For example, if the
user clicks a button on a webpage, you might want to respond to that action by displaying an
information box.
Attaching Events
Attach events to any tag by adding a special attribute to that tag. The name of the attribute
specifies the event and you set the attribute equal to a string that contains a function call.
Every time the event occurs the function is executed.
<h1 onclick="myFunction()">
Accessing Tags
Your event connected JavaScript functions can modify the tags in your document. First, the
JavaScript needs to know which tag you want to modify. You can use the id attribute inside
any of the XHTML tags to give a tag a name. Later you can access the object associated with
that tag by using its id.
<img id="cat" src="cat.jpg"/>
You can access this image object using the JavaScript code
object=document.getElementById("cat");
The variable object now refers to the image object that was created by the previous img tag.
Modifying Tags
Once you have an object you can access or modify it in various ways
You can modify the text in the tag.
Given a tag (object) you modify the text inside the tag using the innerHTML property.
object.innerHTML="Hello World"
You can change the style.
Given a tag (object) you modify a style using the style name.
object.style.fontSize="20pt"
Warning: the style name is changed slightly because JavaScript interprets a - as subtraction.
Therefore font-size becomes fontSize.
You can change the style class.
Given a tag (object) you modify a class using the className property. Remember that the
class name must already be defined with CSS.
object.className="center"
You can modify some of the tag attributes.
Given a tag (object) you modify a tag attribute using it name.
object.src="hat.jpg";
The previous example will only work for an img object because it has a src attribute. Almost
any legal attribute of a tag can be changed: event attributes, id attributes, etc..
An attribute that is often used inside input tags is the value attribute. You can use this
attribute to see what a user has typed into an input and change to the value of the input.
object.value="Hello World";
Notice that you don't have to modify the tag. You can also just check it's value perhaps to
compare it to something else. However most of the time you will want to modify the tag.
Timer Events
One type of useful event is not based on user input but is based on the time. The
window.setInterval() function allows you to tell JavaScript to repeatedly run a function at a
set interval of time.
var interval=window.setInterval("func()",10);
The previous statement causes the function func() to execute every 10 milliseconds.
Often one wants to stop a interval from running. In the previous example, we created a
variable called interval that stored what was returned from window.setInterval("func()",10).
This variable holds an identifier for the interval function. We need this identifier to turn off
the interval function. (You probably will need to make this identifier variable global.)
window.clearInterval(interval);
The previous statement turns off the previous interval. The identifier is necessary because
one can have several interval functions running at the same time and JavaScript needs to
know which one you want to turn off.
First, get the namefield element, and then add an event to it.
//get the ID and assign it as a variable
var nameField = document.getElementbyId("name");
//when the ID is clicked, run this function
nameField.onfocus = function() {
//if the field has the value "your name", leave it blank
if ( nameField.value == "your name" ) {
nameField.value = "";
}
};
You can also add an onblur event to take place when the user leaves the field.
//get the ID and assign it as a variable
var nameField = document.getElementbyId("name");
//when the user leaves the ID, run this function
nameField.onblur = function() {
//if the field's value is "your name", don't write anything
if ( nameField.value == "your name" ) {
emailField.value = "";
}
};
Timers
You can add events that have a time delay. For example, if you want a pop-up message to
appear after the user has been on the page for 10 seconds, you can do this through
the setTimeOut method.
For example, let's say you have a simple message:
function welcomeVisitor() {alert("Welcome to the site");}
However, you don't want this message to appear until the user has been on the page for a
while. You delay the action through the setTimeOut function:
setTimeOut(welcomeVisitor,8000);
The setTimeOut function has two parameters. The first allows you to call a function (which
we declared earlier), and the second refers to the timer. The function will not be called for
8000 milliseconds.
There are other timer functions, such as setInterval, that initiate the function at the interval
you specify.
JQuery
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML
document traversal and manipulation, event handling, animation, and Ajax much simpler
with an easy-to-use API that works across a multitude of browsers. With a combination of
versatility and extensibility, jQuery has changed the way that millions of people write
JavaScript.
Javascript Frameworks
The five JavaScript frameworks that currently dominate the market in terms of popularity and
usage are:
React - React is a JavaScript library for building user interfaces.
Vue - Vue is a progressive framework for building user interfaces. Unlike other monolithic
frameworks, Vue is designed from the ground up to be incrementally adoptable. The core
library is focused on the view layer only, and is easy to pick up and integrate with other
libraries or existing projects.
Angular - Angular is an app-design framework and development platform for creating
efficient and sophisticated single-page apps.
Ember - Ember.js is a productive, battle-tested JavaScript framework for building modern
web applications. It includes everything you need to build rich UIs that work on any device.
Backbone.js - Backbone.js gives structure to web applications by providing models with
key-value binding and custom events, collections with a rich API of enumerable
functions, views with declarative event handling, and connects it all to your existing API over
a RESTful JSON interface.
Introduction to JQuery
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice
motto: Write less, do more. jQuery simplifies HTML document traversing, event handling,
animating, and Ajax interactions for rapid web development.
jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is
the list of important core features supported by jQuery:
DOM manipulation: The jQuery made it easy to select DOM elements, negotiate them and
modifying their content by using cross-browser open source selector engine called Sizzle.
Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as
a user clicking on a link, without the need to clutter the HTML code itself with event
handlers.
AJAX Support: The jQuery helps you a lot to develop a responsive and feature-rich site using
AJAX technology.
Animations: The jQuery comes with plenty of built-in animation effects which you can use in
your websites.
Lightweight: The jQuery is very lightweight library - about 19KB in size (Minified and
gzipped). Cross Browser Support: The jQuery has cross-browser support, and works well
in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.
<script>
$(document).ready(function(){
// Fading out displayed paragraphs with different speeds
$(".out-btn").click(function(){
$("p.normal").fadeOut();
$("p.fast").fadeOut("fast");
$("p.slow").fadeOut("slow");
$("p.very-fast").fadeOut(50);
$("p.very-slow").fadeOut(2000);
});
// Fading in hidden paragraphs with different speeds
$(".in-btn").click(function(){
$("p.normal").fadeIn();
$("p.fast").fadeIn("fast");
$("p.slow").fadeIn("slow");
$("p.very-fast").fadeIn(50);
$("p.very-slow").fadeIn(2000);
});
});
</script>
<script>
$(document).ready(function(){
// Hide displayed paragraphs
$(".hide-btn").click(function(){
$("p").hide();
});
// Show hidden paragraphs
$(".show-btn").click(function(){
$("p").show();
});
});
</script>
You can optionally specify the duration (also referred as speed) parameter for making the
jQuery show hide effect animated over a specified period of time.
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a
number of milliseconds, for greater precision; higher values indicate slower animations.
<script>
$(document).ready(function(){
// Hide displayed paragraphs with different speeds
$(".hide-btn").click(function(){
$("p.normal").hide();
$("p.fast").hide("fast");
$("p.slow").hide("slow");
$("p.very-fast").hide(50);
$("p.very-slow").hide(2000);
});
// Show hidden paragraphs with different speeds
$(".show-btn").click(function(){
$("p.normal").show();
$("p.fast").show("fast");
$("p.slow").show("slow");
$("p.very-fast").show(50);
$("p.very-slow").show(2000);
});
});
</script>
// Smooth scrolling
scrollLink.click(function(e) {
e.preventDefault();
$('body,html').animate({
scrollTop: $(this.hash).offset().top
}, 1000 );
});
scrollLink.each(function() {
})
})
#sliderContainer {
width: 800px;
margin: 0;
padding: 0px;
position: relative;
overflow: hidden;
}
#sliderContainer .slider {
margin: 0;
padding: 0;
width: 800px;
float: left;
position: relative;
}
jQuery Code
First, define few variables.
The first variable curPos, indicates the current position and it is set to 0.
Second variable is slider which gets the references of all images with CSS class
“.slider†.
Third variable is cntImages, which gets the count of total number of images which are part of
slider.
And the fourth variable is sliderWidth, which gets the width of slider container.
There were 2 div element defined in the HTML markup sliderContainer and sliderWrapper.
The logic of creating image slider is, assign the total width to sliderWrapper which is
sliderWidth * cntImages. So in this case, this value comes to 4000px (800x5). But it
won’t be visible on the screen as parent element is having overflow:hidden property.
Next, create a function called SlideImage, which will be called by setInterval function with
delay of 2 seconds. This ensures that images rotates automatically. Inside this function,
First checks, if the current image is the last image. If yes, then set curPos variable to 0 so that
first image is shown again. And if not, then we increment the value of curPos variable.
To show next image as part of image slider, we play with the margin-left property of
sliderWrapper so that next image becomes part of slider visible area. We
use animate method of jQuery which provides us the slide animation. And we set
margin-left property to sliderWidth * (-curPos). So the value for image 2 would be -800,
-1600 for third image, -2400 for fourth image and -3200 for last image. And again back to 0
for first image. And that would make images to rotate.
Here is complete jQuery code.
$(function() {
var curPos = 0;
var slider = $('.slider');
var cntImages= slider.length;
var sliderWidth = slider.width();
$('#sliderWrapper').css('width', sliderWidth * cntImages);
setInterval(SlideImage, 2000);
function SlideImage() {
if (curPos == cntImages - 1)
curPos = 0;
else
curPos++;
$('#sliderWrapper').animate({
'marginLeft': sliderWidth * (-curPos)
});
}
});
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
<button id="btn2"><span id="choice2"></span></button>
<button id="btn3"><span id="choice3"></span></button>
</div>
<script src="question.js"></script>
</body>
</html>
le.css
CSS
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border: 2px solid #cbcbcb;
.grid h1 {
font-family: "sans-serif";
background-color: #01BBFF;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
#score {
color: #01BBFF;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #01BBFF;
}
.buttons {
margin-top: 30px;
}
#progress {
color: #2b2b2b;
font-size: 18px;
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function populate() {
if(quiz.isEnded()) {
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " +
quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();
HTML5 export buttons – makes use of HTML5 APIs to create files client-side
Flash export buttons – uses Adobe Flash for legacy browsers
Print button
You can also check other tutorials of export table data,
Exporting a DataTable into PDF File
Exporting a DataTable to CSV
DataTables Export to Excel using HTML5
Popular JavaScript and jQuery PDF Viewer Plugins
I am extending excelHtml5 so that you can use export to excel only on latest browser not on
legacy browser.I am explaining steps by step jQuery datatable export to excel tutorial, I am
extending previous tutorial that’s why i will change extension format and label from
previous Export jQuery datatable to pdf tutorial.
We have learn Export Datatable to CSV and Export Datatable to PDF in earlier datatables
tutorial, Now i am extending this datatables tutorial and adding export datatable to Excel file.
Exporting jQuery Datatables data to Excel File
Step 1: We need to include all datatables library files in head section of index.html file.
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,
b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
<script type="text/javascript"
src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmak
Step 2: Created HTML layout for jQuery datatables listing in index.html file.
<thead>
<tr>
<th>User ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
Step 3: Fetched data from restful web service and processed data as required for jQuery
datatables.
var arrayReturn = [];
$.ajax({
url: "http://jsonplaceholder.typicode.com/posts",
async: true,
dataType: 'json',
success: function (data) {
for (var i = 0, len = data.length; i < len; i++) {
var desc = data[i].body;
var title = data[i].title;
var id = (data[i].id).toString();
arrayReturn.push([id, '<a href="http://google.com" target="_blank">'+title.substring(0,
20)+'</a>', desc.substring(0, 120)]);
}
inittable(arrayReturn);
}
});
Step 4: Now I will passed formatted data to jQuery datatables "aaData" property.
function inittable(data) {
$('#listing').DataTable({
"aaData": data,
"dom": 'lBfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Export to Excel',
title: 'js-tutorials.com : Export to datatable data to Excel',
download: 'open',
orientation:'landscape',
exportOptions: {
columns: ':visible'
}
}] } ); }
XML Parsing
Parses a string into an XML document.
In web application response may be in the form of XML. With the help of that xml response
you are going to display your web contents.
Create Sample Xml String
In below example nothing special to explain . Here I have taken employee details xml
example and assigned to xml variable. First you need to parsexml using this code $xml =
$( $.parseXML( xml ) ); and then find the respected xml tag using find method.
1. <employees>
2. <employee id="1000">
3. <first_name>Yashwant</first_name>
4. <last_name>Chavan</last_name>
5. </employee>
6.
7. <employee id="2000">
8. <first_name>Mahesh</first_name>
9. <last_name>Divan</last_name>
10. </employee>
11. </employees>';
Complete Code to Parse Xml Suing Jquery
JSON Parsing
Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown. For
example, the following are all invalid JSON strings:
"{test: 1}" (test does not have double quotes around it).
"{'test': 1}" ('test' is using single quotes instead of double quotes).
"'test'" ('test' is using single quotes instead of double quotes).
".1" (a number must start with a digit; "0.1" would be valid).
"undefined" (undefined cannot be represented in a JSON string; null, however, can be).
"NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is
also not permitted).
The JSON standard does not permit "control characters" such as a tab or newline. An
example like $.parseJSON( '{ "testing":"1\t2\n3" }' ) will throw an error in most
implementations because the JavaScript parser converts the string's tab and newline escapes
into literal tab and newline; doubling the backslashes like "1\\t2\\n3" yields expected results.
This problem is often seen when injecting JSON into a JavaScript file from a server-side
language such as PHP.
Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse
the string. For details on the JSON format, see https://json.org/.
Prior to jQuery 1.9, $.parseJSON returned null instead of throwing an error if it was passed
an empty string, null, or undefined, even though those are not valid JSON.
Example
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
Note that the target value of the height property is 'toggle'. Since the image was visible before,
the animation shrinks the height to 0 to hide it. A second click then reverses this transition:
The opacity of the image is already at its target value, so this property is not animated by the
second click. Since the target value for left is a relative value, the image moves even farther
to the right during this second animation.
Directional properties (top, right, bottom, left) have no discernible effect on elements if
their position style property is static, which it is by default.
Step Function
The second version of .animate() provides a step option — a callback function that is fired at
each step of the animation. This function is useful for enabling custom animation types or
altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set
to the DOM element being animated.
now: the numeric value of the property being animated at each step
fx: a reference to the jQuery.fx prototype object, which contains a number of properties
such as elem for the animated element, start and end for the first and last value of the
animated property, respectively, and prop for the property being animated.
For example, given two list items, the step function fires four times at each step of the
animation:
$( "li" ).animate({
opacity: .5,
height: "50%"
}, {
step: function( now, fx ) {
var data = fx.elem.id + " " + fx.prop + ": " + now;
$( "body" ).append( "<div>" + data + "</div>" );
}
});
Easing
The remaining parameter of .animate() is a string naming an easing function to use. An
easing function specifies the speed at which the animation progresses at different points
within the animation. The only easing implementations in the jQuery library are the default,
called swing, and one that progresses at a constant pace, called linear. More easing functions
are available with the use of plug-ins, most notably the jQuery UI suite.
Per-property Easing
As of jQuery version 1.4, you can set per-property easing functions within a
single .animate() call. In the first version of .animate(), each property can take an array as its
value: The first member of the array is the CSS property and the second member is an easing
function. If a per-property easing function is not defined for a particular property, it uses the
value of the .animate() method's optional easing argument. If the easing argument is not
defined, the default swing function is used.
For example, to simultaneously animate the width and height with the swing easing function
and the opacity with the linear easing function:
$( "#clickme" ).click(function() {
$( "#book" ).animate({
width: [ "toggle", "swing" ],
height: [ "toggle", "swing" ],
opacity: "toggle"
}, 5000, "linear", function() {
$( this ).after( "<div>Animation complete.</div>" );
});
});
UNIT - IV
Bulma
Bulma is one of the free open source CSS framework that is based on Flexbox. Now it has
become widely popular and more than 150000 developers are using this framework without
any worries. This framework is meant to include only the minimum requirements to get you
started on your web development project. This lightweight framework is absolutely
responsive and based on a 12 column grid system. If you are a newbie then you can learn
very easier and faster with Bulma. In case of problems, a huge community is available for
this framework.
Once you know how to use Bulma, you can quickly customize your website. This framework
has 33.3K stars on github repo and updated very frequently.
Pros:
Very quick to customize.
It integrates in any JS environment.
Cons:
CSS only - doesn’t include any JS or jQuery plugins.
UIKIT
UIKIT is a very lightweight and highly modular front-end framework that helps to develop
powerful and fast web interfaces. This mighty fact that includes in this framework is, it
includes both Sass and LESS CSS preprocessors.
UIKit has become one of the most popular front-end frameworks out there with an array of
nimble responsive components with consistent naming conventions. This framework comes
with more than 30+ extendable, modular components which can be combined for even more
versatility.
It includes elements like HTML forms and tables; navigation components like side
navigation bars; JavaScript components like modal dialogs and off-canvas bars; common
elements like badges, buttons, and overlays; and layout components with an entirely
responsive grid system.
Currently, UIKIT has 14k stars in github repository and updated regularly.
Pros:
Outstandingly modular, so that you can add components to the stylesheet without
negatively impacting your overall style.
Highly customizable.
Create advanced user interfaces with components like nestables.
Cons:
The number of resources is very low due to relative newness.
Bootstrap
incomplete without the most popular, faster and user-friendly framework, Bootstrap. This
framework is released in 2011 and created by Twitter developers. Currently, there are
millions of amazing websites across the web that are running this amazing framework. You
can check its popularity by counting its stars at GitHub repo, its more than 131K.
Like the all other effective front-end frameworks, Bootstrap includes HTML, CSS, and
JavaScript. You can easily develop responsive sites of all sizes and complexities. As this
framework is updated regularly, it always includes the best and latest features.
Quickly build your entire app or prototype your ideas with Bootstraps Sass variables and
mixins. Earlier it was based on LESS but as the popularity is increasing to SASS, Bootstrap
made its version 4 in SASS. Our classic version of Quix Joomla page builder is built with
Bootstrap version 3, which is based on LESS.
Pros:
Extensive documentation.
Responsive web design support, which can also be disabled if required.
Cons:
An immoderate number of DOM elements and HTML classes can be confusing and
messy.
Out of the box file size of 276kB due to an excessive number of rarely used styles.
Foundation
Foundation framework is one of the highly advanced frameworks that has been created by a
web design company called Zurb. It is an enterprise grade front end framework that is ideal
for developing a responsive website, nimbles. Many popular organizations like FaceBook,
eBay, Mozilla, Adobe, hp, Cisco, Disney, and other popular organizations use this framework
on their sites.
If you are a newbie than definitely, this is not the framework you are looking for. It is fairly
complex and not suitable for persons who are unknown with frameworks. If you have earlier
experience, you can easily design beautiful apps, emails, and websites that will look
mindblowing on any device. Foundation is readable, flexible, semantic and entirely
customizable.
Foundation comes with GPU acceleration for lightning fast and smooth animations. It offers
Fastclick.js for fast rendering at mobile devices. This versatile framework runs on Sass
preprocessor and includes data interchange attribute that is developed by Foundation.
This attribute lets you load heavier HTML sections for larger screens and lightweight HTML
sections for mobile screens. Currently, this framework has more than 28K stars in the GitHub
repository with a big user community.
Pros:
Great flexibility as no style lock-in.
Instead of pixels uses REMS, eliminates the need of explicitly state height, width and
other attributes for each device.
Cons:
Size is fairly big out of the box.
A bit of complex for the beginners.
Materialize
Materialize is a responsive, modern front-end development framework that is based on
Google’s material design specifications. This framework comes with ready to use icons,
buttons, forms, cards, and other components. It is offered in both standard version and one
that runs on SASS, use any that you like.
The convenient IZ column grid feature is included with Materialize so that it can be used for
website layouts. This framework is loaded with CSS, which is ready to use out of the box for
material design colors, shadows, typography, and other features.
Additional features of this framework include drag out mobile menus, SASS mixins, ripple
effect animation and more. This framework is rated with 35K+ stars on the GitHub
repository. Pros:
A huge number of components.
Support for all types of devices.
Cons:
Very large size.
No flexbox model support.
CSS Preprocessors
A CSS preprocessor is a program that lets you generate CSS from the preprocessor's own
unique syntax. There are many CSS preprocessors to choose from, however most CSS
preprocessors will add some features that don't exist in pure CSS, such as mixin, nesting
selector, inheritance selector, and so on. These features make the CSS structure more
readable and easier to maintain.
Sass is a stylesheet language that’s compiled to CSS. It allows you to use variables, nested
rules, mixins, functions, and more, all with a fully CSS-compatible syntax. Sass helps keep
large stylesheets well-organized and makes it easy to share design within and across projects.
If you’re looking for an introduction to Sass, check out the tutorial.
If you want to look up a built-in Sass function, look no further than the built-in module
reference.
If you’re calling Sass from JavaScript, you may want the JS API documentation.
Or the Dart API documentation if you’re calling it from Dart.
Otherwise, use the table of contents for the language reference!
display: inline-flex
position: relative
height: $button-height
border: none
vertical-align: middle
&:hover
cursor: pointer
&:disabled
color: $mdc-button-disabled-ink-color
cursor: default
pointer-events: none
Variables
Sass variables are simple: you assign a value to a name that begins with $, and then you can
refer to that name instead of the value itself. But despite their simplicity, they're one of the
most useful tools Sass brings to the table. Variables make it possible to reduce repetition, do
complex math, configure libraries, and much more.
A variable declaration looks a lot like a property declaration: it’s written <variable>:
<expression>. Unlike a property, which can only be declared in a style rule or at-rule,
variables can be declared anywhere you want. To use a variable, just include it in a value.
$base-color: #c6538c
$border-dark: rgba($base-color, 0.88)
.alert
border: 1px solid $border-dark
Default Values
Normally when you assign a value to a variable, if that variable already had a value, its old
value is overwritten. But if you’re writing a Sass library, you might want to allow your users
to configure your library’s variables before you use them to generate CSS.
To make this possible, Sass provides the !default flag. This assigns a value to a variable only
if that variable isn’t defined or its value is null. Otherwise, the existing value will be used.
Built-in Variables
Variables that are defined by a built-in module cannot be modified.
@use "sass:math" as math;
// This assignment will fail.math.$pi: 0;
Operators
Sass supports a handful of useful operators for working with different values. These include
the standard mathematical operators like + and *, as well as operators for various other types:
== and != are used to check if two values are the same.
+, -, *, /, and % have their usual mathematical meaning for numbers, with special
behaviors for units that matches the use of units in scientific math.
<, <=, >, and >= check whether two numbers are greater or less than one another.
and, or, and not have the usual boolean behavior. Sass considers every value “true”
except for false and null.
+, -, and / can be used to concatenate strings.
Order of Operations
Sass has a pretty standard order of operations, from tightest to loosest:
The unary operators not, +, -, and /.
The *, /, and % operators.
The + and - operators.
The >, >=, < and <= operators.
The == and != operators.
The and operator.
The or operator.
The = operator, when it’s available.
Equality Operators
The equality operators return whether or not two values are the same. They’re
written <expression> == <expression>, which returns whether two expressions are equal,
and <expression> != <expression>, which returns whether two expressions are not equal.
Two values are considered equal if they’re the same type and the same value, which means
different things for different types:
Numbers are equal if they have the same value and the same units, or if their values are
equal when their units are converted between one another.
Strings are unusual in that unquoted and quoted strings with the same contents are
considered equal.
Colors are equal if they have the same red, green, blue, and alpha values.
Lists are equal if their contents are equal. Comma-separated lists aren’t equal to
space-separated lists, and bracketed lists aren’t equal to unbracketed lists.
Maps are equal if their keys and values are both equal.
true, false, and null are only equal to themselves.
Functions are equal to the same function. Functions are compared by reference, so even
if two functions have the same name and definition they’re considered different if they
aren’t defined in the same place.
Example
@debug 1px == 1px // true@debug 1px != 1em
Relational Operators
Relational operators determine whether numbers are larger or smaller than one another. They
automatically convert between compatible units.
<expression> < <expression> returns whether the first expression’s value is less than
the second’s.
<expression> <= <expression> returns whether the first expression’s value is less than or
equal to the second’s.
<expression> > <expression> returns whether the first expression’s value is greater than
to the second’s.
<expression> >= <expression>, returns whether the first expression’s value is greater
than or equal to the second’s.
Example
@debug 100 > 50 // true
@debug 10px < 17px // true
@debug 96px >= 1in // true
@debug 1000ms <= 1s // true
Numeric Operators
Sass supports the standard set of mathematical operators for numbers. They automatically
convert between compatible units.
<expression> + <expression> adds the first expression’s value to the second’s.
<expression> - <expression> subtracts the first expression’s value from the second’s.
<expression> * <expression> multiplies the first expression’s value by the second’s.
<expression> / <expression> divides the first expression’s value by the second’s.
<expression> % <expression> returns the remainder of the first expression’s value
divided by the second’s. This is known as the modulo operator.
Example
@debug 10s + 15s // 25s
@debug 1in - 10px // 0.8958333333in
@debug 5px * 3px // 15px*px
@debug (12px/4px) // 3
@debug 1in % 9px // 0.0625in
String Operators
Sass supports a few operators that generate strings:
<expression> + <expression> returns a string that contains both expressions’ values. If
the either value is a quoted string, the result will be quoted; otherwise, it will be unquoted.
<expression> / <expression> returns an unquoted string that contains both expressions’
values, separated by /.
<expression> - <expression> returns an unquoted string that contains both expressions’
values, separated by -. This is a legacy operator, and interpolation should generally be
used instead.
Example
@debug "Helvetica" + " Neue" // "Helvetica Neue"
@debug sans- + serif // sans-serif
@debug #{10px + 5px} / 30px // 15px/30px
@debug sans - serif // sans-serif
These operators don’t just work for strings! They can be used with any values that can be
written to CSS, with a few exceptions:
Numbers can’t be used as the left-hand value, because they have their own operators.
Colors can’t be used as the left-hand value, because they used to have their own
operators.
@debug "Elapsed time: " + 10s // "Elapsed time: 10s";
@debug true + " is a boolean value" // "true is a boolean value";
Boolean Operators
Unlike languages like JavaScript, Sass uses words rather than symbols for
its boolean operators.
not <expression> returns the opposite of the expression’s value:
it turns true into false and false into true.
<expression> and <expression> returns true if both expressions’ values are true,
and false if either is false.
<expression> or <expression> returns true if either expression’s value is true, and false if
both are false.
Example
@debug not true // false
@debug not false // true
@debug true and true // true
@debug true and false // false
@debug true or false // true
@debug false or false // false
Funtions
Functions can be values too! You can’t directly write a function as a value, but you can pass a
function’s name to the [meta.get-function() function][] to get it as a value. Once you have a
function value, you can pass it to the meta.call() function to call it. This is useful for
writing higher-order functions that call other functions.
@use "sass:list"@use "sass:meta"@use "sass:string"
/// Return a copy of $list with all elements for which $condition returns `true`
/// removed.@function remove-where($list, $condition)
$new-list: ()
$separator: list.separator($list)
@each $element in $list
@if not meta.call($condition, $element)
$new-list: list.append($new-list, $element, $separator: $separator)
@return $new-list
Arguments
Arguments allow functions’ behavior to be customized each time they’re called. The
arguments are specified in the @function rule after the function’s name, as a list of variable
names surrounded by parentheses. The function must be called with the same number of
arguments in the form of SassScript expressions. The values of these expression are available
within the function’s body as the corresponding variables.
Optional Arguments
Normally, every argument a function declares must be passed when that function is included.
However, you can make an argument optional by defining a default value which will be used
if that arguments isn’t passed. Default values use the same syntax as variable declarations:
the variable name, followed by a colon and a SassScript expression. This makes it easy to
define flexible function APIs that can be used in simple or complex ways.
@function invert($color, $amount: 100%)
$inverse: change-color($color, $hue: hue($color) + 180)
@return mix($inverse, $color, $amount)
$primary-color: #036.header
background-color: invert($primary-color, 80%)
Keyword Arguments
When a function is called, arguments can be passed by name in addition to passing them by
their position in the argument list. This is especially useful for functions with multiple
optional arguments, or with boolean arguments whose meanings aren’t obvious without a
name to go with them. Keyword arguments use the same syntax as variable
declarations and optional arguments.
$primary-color: #036.banner
background-color: $primary-color
color: scale-color($primary-color, $lightness: +40%)
Taking Arbitrary Arguments
Sometimes it’s useful for a function to be able to take any number of arguments. If the last
argument in a @function declaration ends in ..., then all extra arguments to that function are
passed to that argument as a list. This argument is known as an argument list
@function sum($numbers...)
$sum: 0
@each $number in $numbers
$sum: $sum + $number
@return $sum
.micro
width: sum(50px, 30px, 100px)
Taking Arbitrary Keyword Arguments
Argument lists can also be used to take arbitrary keyword
arguments. The meta.keywords() function takes an argument list and returns any extra
keywords that were passed to the function as a map from argument names (not including $)
to those arguments’ values.
Passing Arbitrary Arguments
Just like argument lists allow functions to take arbitrary positional or keyword arguments, the
same syntax can be used to pass positional and keyword arguments to a function. If you pass
a list followed by ... as the last argument of a function call, its elements will be treated
as additional positional arguments. Similarly, a map followed by ... will be treated as
additional keyword arguments. You can even pass both at once!
@return
The @return at-rule indicates the value to use as the result of calling a function. It’s only
allowed within a @function body, and each @function must end with a @return.
When a @return is encountered, it immediately ends the function and returns its result.
Returning early can be useful for handling edge-cases or cases where a more efficient
algorithm is available without wrapping the entire function in an @else block.
@use "sass:string"
@function str-insert($string, $insert, $index)
// Avoid making new strings if we don't need to. @if string.length($string) == 0
@return $insert
Types of Functions
CSS defines many functions, and most of them work just fine with Sass’s normal function
syntax. They’re parsed as function calls, resolved to plain CSS functions, and compiled as-is
to CSS. There are a few exceptions, though, which have special syntax that can’t just be
parsed as a SassScript expression. All special function calls return unquoted strings
url()
The url() function is commonly used in CSS, but its syntax is different than other functions:
it can take either a quoted or unquoted URL. Because an unquoted URL isn’t a valid
SassScript expression, Sass needs special logic to parse it.
If the url()’s argument is a valid unquoted URL, Sass parses it as-is,
although interpolation may also be used to inject SassScript values. If it’s not a valid
unquoted URL—for example, if it contains variables or function calls—it’s parsed as a
normal plain CSS function call.
$roboto-font-path: "../fonts/roboto"
@font-face
// This is parsed as a normal function call that takes a quoted string.
src: url("#{$roboto-font-path}/Roboto-Thin.woff2") format("woff2")
font-family: "Roboto"
font-weight: 100
$padding: 12px
.post
// Since these max() calls don't use any Sass features other than
// interpolation, they're compiled to CSS max() calls.
padding-left: max(#{$padding}, env(safe-area-inset-left))
padding-right: max(#{$padding}, env(safe-area-inset-right))
.sidebar
// Since these refer to a Sass variable without interpolation, they call
// Sass's built-in max() function.
padding-left: max($padding, 20px)
padding-right: max($padding, 20px)
Inheritance
The @extend directive lets you share a set of CSS properties from one selector to another.
The @extend directive is useful if you have almost identically styled elements that only differ
in some small details.
The following Sass example first creates a basic style for buttons (this style will be used for
most buttons). Then, we create one style for a "Report" button and one style for a "Submit"
button. Both "Report" and "Submit" button inherit all the CSS properties from
the .button-basic class, through the @extend directive. In addition, they have their own colors
defined:
.button-basic {
border: none;
padding: 15px 30px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button-report {
@extend .button-basic;
background-color: red;
}
.button-submit {
@extend .button-basic;
background-color: green;
color: white;
}
By using the @extend directive, you do not need to specify several classes for an element in
your HTML code, like this: <button class="button-basic button-report">Report this</button>.
You just need to specify .button-report to get both sets of styles.
The @extend directive helps keep your Sass code very DRY.
Media Queris
What are media queries and why should I care?
If you've ever created a print style sheet you've used media-specific CSS. In that case you
called a separate CSS file just for print by setting the media attribute of a link:
<link rel="stylesheet" href="paper.css" media="print" />
This gave us some control over media types, but that's it. Then CSS3 introduced the concept
of using a query in that space as well. You can add your query in the <link> tag, or join the
cool kids and use the @media rule in CSS. More on that later.
First let's look at what kind of queries we can write. If you look at the W3C Spec you'll see a
dazzling array of different properties you can check. The ones I'm most interested in are the
ones concerning width, height, orientation, and ratio. By swapping out different rules based
on these properties you can change the size and shape of your design to truly fit the viewing
area.
Here's a simple query in the <link> tag that will load a css file for small screens.
<link rel="stylesheet" media="screen and (max-width: 480px)" href="small.css" />
This is great, but if we want to manage a lot of different options these files can add up
quickly. Fortunately we have the @media rule. You can use these inside any CSS file to
apply specific rules only when the query expression is true.
Here I'm setting the font-size of an <h1> to be larger on a large screen.
// set a variable for the font size$h1-size: 36px
h1 {
font-size: $h1-size;}
// this will only affect wide screens@media screen and (min-width: 1024px) {
h1 {
font-size: $h1-size * 1.5;
}}
Which compiles to:
h1 {
font-size: 36px;}@media screen and (min-width: 1024px) {
h1 {
font-size: 54px;
}}
You can use these in Sass just fine, and inside a query you can use all the Sass features you
like. In the above example I used and manipulated a variable. You should note, however, that
you can't use variables in the query declaration itself. It would be nice to write the following,
but it won't work.
$breakpoint: 1024px;
@media screen and (min-width: $breakpoint) {
content: "this won't work :(";}
@media Bubbling
Sass does provide what I consider to be a pretty killer feature for authoring @media when
you nest them inside other selectors. If you add a @media query by nesting it inside a
selector Sass will "bubble" that @media query and the new rule outside of the nest and back
out to the root of your style sheet.
I use @media un-nested (as mentioned above) when I'm setting up large-scale changes like a
responsive master grid, but I find that I need to make small adjustments much more often.
For example, lets say you have a profile picture that looks great large and floated to the left
on a desktop, but needs to shrink on a smaller screen. It also needs to stop floating on a really
wide screen.
In Sass we can write that like this.
.profile-pic {
float: left;
width: 250px;
@media screen and (max-width: 320px) {
width: 100px;
}
@media screen and (min-width: 1200px) {
float: none;
}}
Sass will see this and know that you want to apply that query to the selector it's nested in. It
compiles to CSS like so:
.profile-pic {
float: left;
width: 250px;}@media screen and (max-width: 320px) {
.profile-pic {
width: 100px;
}}@media screen and (min-width: 1200px) {
.profile-pic {
float: none;
}}
Mixins - Partials
Mixins allow you to define styles that can be re-used throughout your stylesheet. They make
it easy to avoid using non-semantic classes like .float-left, and to distribute collections of
styles in libraries.
Mixins are defined using the @mixin at-rule, which is written @mixin <name>
{ ... } or @mixin name(<arguments...>) { ... }. A mixin’s name can be any Sass identifier,
and it can contain any statement other than top-level statements. They can be used to
encapsulate styles that can be dropped into a single style rule; they can contain style rules of
their own that can be nested in other rules or included at the top level of the stylesheet; or
they can just serve to modify variables.
Mixins are included into the current context using the @include at-rule, which is
written @include <name> or @include <name>(<arguments...>), with the name of the mixin
being included.
Example
@mixin reset-list
margin: 0
padding: 0
list-style: none
@mixin horizontal-list
@include reset-list
li
display: inline-block
margin:
left: -2px
right: 2em
nav ul
@include horizontal-list
UNIT - V
Less framework
Scaling Scrum starts with understanding standard one-team Scrum. From that point, your
organization must be able to understand and adopt LeSS, which requires examining the
purpose of one-team Scrum elements and figuring out how to reach the same purpose while
staying within the constraints of the standard Scrum rules.
Agile development with Scrum requires a deep organizational change to become agile.
Therefore, neither Scrum nor LeSS should be considered as merely a practice. Rather, they
form an organizational design framework.
Two Agile Scaling Frameworks
LeSS provides two different large-scale Scrum frameworks. Most of the scaling elements of
LeSS are focused on directing the attention of all of the teams onto the whole product instead
of “my part.” Global and “end-to-end” focus are perhaps the dominant problems to solve in
scaling. The two frameworks – which are basically single-team Scrum scaled up – are:
LeSS: Up to eight teams (of eight people each).
LeSS Huge: Up to a few thousand people on one product.
What does it mean to be the same as One-Team Scrum?
LeSS is a scaled up version of one-team Scrum, and it maintains many of the practices and
ideas of one-team Scrum. In LeSS, you will find:
a single Product Backlog (because it’s for a product, not a team),
one Definition of Done for all teams,
one Potentially Shippable Product Increment at the end of each Sprint,
one Product Owner,
many complete, cross-functional teams (with no single-specialist teams),
one Sprint.
In LeSS all Teams are in a common Sprint to deliver a common shippable product, every
Sprint.
What’s Different in LeSS?
Sprint Planning Part 1: In addition to the one Product Owner, it includes people from all
teams. Let team members self-manage to decide their division of Product Backlog Items.
Team members also discuss opportunities to find shared work and cooperate, especially
for related items.
Sprint Planning Part 2: This is held independently (and usually in parallel) by each Team,
though sometimes for simple coordination and learning two or more Teams may hold it
in the same room (in different areas).
Daily Scrum: This is also held independently by each Team, though a member of Team
A may observe Team B’s Daily Scrum, to increase information sharing.
Coordination: Just Talk, Communicate in Code, Travelers, Open Space, and
Communities.
Overall PBR: There may be an optional and short overall Product Backlog Refinement
(PBR) meeting that includes the one Product Owner and people from all teams. The key
purpose is to decide which teams are likely to implement which items and therefore
select those items for later in-depth single-team PBR. It is also a chance to increase
alignment with the Product Owner and all teams.
Product Backlog Refinement: The only requirement in LeSS is single-team PBR, the
same as in one-team Scrum. But a common and useful variation is multi-team PBR,
where two or more Teams are in the same room together, to increase learning and
coordination.
Sprint Review: In addition to the one Product Owner, it includes people from all teams,
and relevant customers/users and other stakeholders. For the phase of inspecting the
product increment and new items, consider a “bazaar” or “science fair” style: a large
room with multiple areas, each staffed by team members, where the items developed by
teams are shown and discussed.
Overall Retrospective: This is a new meeting not found in one-team Scrum, and its
purpose is to explore improving the overall system, rather than focusing on one Team.
The maximum duration is 45 minutes per week of Sprint. It includes the Product Owner,
Scrum Masters, and rotating representatives from each Team.
Variables
These are pretty self-explanatory:
@width: 10px;@height: @width + 10px;
#header {
width: @width;
height: @height;
}
Outputs:
#header {
width: 10px;
height: 20px;
}
It's not uncommon to see the same value repeated dozens if not hundreds of times across your
stylesheets:
a,.link {
color: #428bca;
}.widget {
color: #fff;
background: #428bca;
}
Variables make your code easier to maintain by giving you a way to control those values
from a single location:
// Variables@link-color: #428bca; // sea blue@link-color-hover:
darken(@link-color, 10%);
// Usagea,.link {
color: @link-color;
}a:hover {
color: @link-color-hover;
}.widget {
color: #fff;
background: @link-color;
}
Variable Interpolation
The examples above focused on using variables to control values in CSS rules, but they can
also be used in other places as well, such as selector names, property names, URLs
and @import statements.
Selectors
v1.4.0
// Variables@my-selector: banner;
// Usage.@{my-selector} {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
Compiles to:
.banner {
font-weight: bold;
line-height: 40px;
margin: 0 auto;
}
Variable Variables
In Less, you can define a variable's name using another variable.
@primary: green;@secondary: blue;
.section {
@color: primary;
.element {
color: @@color;
}
}
Which compiles to:
.section .element {
color: green;
}
Lazy Evaluation
Variables do not have to be declared before being used.
Valid Less snippet:
.lazy-eval {
width: @var;
}
@var: @a;@a: 9%;
this is valid Less too:
.lazy-eval {
width: @var;
@a: 9%;
}
@var: @a;@a: 100%;
both compile into:
.lazy-eval {
width: 9%;
}
When defining a variable twice, the last definition of the variable is used, searching from the
current scope upwards. This is similar to css itself where the last property inside a definition
is used to determine the value.
For instance:
@var: 0;.class {
@var: 1;
.brass {
@var: 2;
three: @var;
@var: 3;
}
one: @var;
}
Compiles to:
.class {
one: 1;
}.class .brass {
three: 3;
}
Essentially, each scope has a "final" value, similar to properties in the browser, like this
example using custom properties:
.header {
--color: white;
color: var(--color); // the color is black
--color: black;
}
This means that, unlike other CSS pre-processing languages, Less variables behave very
much like CSS's.
Properties as Variables (NEW!)
v3.0.0
You can easily treat properties like variables using the $prop syntax. Sometimes this can
make your code a little lighter.
.widget {
color: #efefef;
background-color: $color;
}
Compiles to:
.widget {
color: #efefef;
background-color: #efefef;
}
Note that, like variables, Less will choose the last property within the current/parent scope as
being the "final" value.
.block {
color: red;
.inner {
background-color: $color;
}
color: blue;
}
Compiles to:
.block {
color: red;
color: blue;
} .block .inner {
background-color: blue;
}
Default Variables
We sometimes get requests for default variables - an ability to set a variable only if it is not
already set. This feature is not required because you can easily override a variable by putting
the definition afterwards.
For instance:
// library@base-color: green;@dark-color: darken(@base-color, 10%);
// use of library@import "library.less";@base-color: red;
This works fine because of Lazy Loading - @base-color is overridden and @dark-color is a
dark red.
Functions
Less provides a variety of functions which transform colors, manipulate strings and do maths.
They are documented fully in the function reference.
Using them is pretty straightforward. The following example uses percentage to convert 0.5
to 50%, increases the saturation of a base color by 5% and then sets the background color to
one that is lightened by 25% and spun by 8 degrees:
@base: #f04615;@width: 0.5;
.class {
width: percentage(@width); // returns `50%`
color: saturate(@base, 5%);
background-color: spin(lighten(@base, 25%), 8);
}
Types of Functions
Logical Functions
if
Returns one of two values depending on a condition.
Parameters:
condition: A boolean expression
value1: A value returned if condition is true.
value2: A value returned if condition is not true.
Released: v3.0.0 Updated: v3.6.0
Examples:
@some: foo;
div {
margin: if((2 > 1), 0, 3px);
color: if((iscolor(@some)), darken(@some, 10%), black);
}
Result:
div {
margin: 0;
color: black;
}
A boolean expression supported as the conditional parameter are the same as of Guard
Statements.
if(not (true), foo, bar);
if((true) and (2 > 1), foo, bar);
if((false) or (isstring("boo!")), foo, bar);
before Less 3.6, the condition required a set of parentheses.
if(2 > 1, blue, green); // Causes an error in 3.0-3.5.3
if((2 > 1), blue, green); // Ok 3.0+
boolean
Evaluates to true or false
You can "store" a boolean test for later evaluation in a guard or if().
Parameters:
condition: A boolean expression
Released: v3.0.0 Updated: v3.6.0
Examples:
@bg: black;@bg-light: boolean(luma(@bg) > 50%);
div {
background: @bg;
color: if(@bg-light, black, white);
}
Result:
div {
background: black;
color: white;
}
String Functions
Applies URL-encoding to special characters found in the input string.
These characters are not encoded: ,, /, ?, @, &, +, ', ~, ! and $.
Most common encoded characters are: \<space\>, #, ^, (, ), {, }, |, :, >, <, ;, ], [ and =.
Parameters: string: a string to escape.
Returns: escaped string content without quotes.
Example:
escape('a=1')
Output:
a%3D1
If the parameter is not a string, output is not defined. The current implementation
returns undefined on color and unchanged input on any other kind of argument. This behavior
should not be relied on and may change in the future.
String escaping.
It expects string as a parameter and return its content as is, but without quotes. It can be used
to output CSS value which is either not valid CSS syntax, or uses proprietary syntax which
Less doesn't recognize.
Parameters: string - a string to escape.
Returns: string - the escaped string, without quotes.
Example:
@mscode: "ms:alwaysHasItsOwnSyntax.For.Stuff()"
filter: e(@mscode);
Output:
filter: ms:alwaysHasItsOwnSyntax.For.Stuff();
% format
The function %(string, arguments ...) formats a string.
The first argument is string with placeholders. All placeholders start with percentage
symbol % followed by letter s,S,d,D,a, or A. Remaining arguments contain expressions to
replace placeholders. If you need to print the percentage symbol, escape it by another
percentage %%.
Use uppercase placeholders if you need to escape special characters into their utf-8 escape
codes. The function escapes all special characters except ()'~!. Space is encoded as %20.
Lowercase placeholders leave special characters as they are.
Placeholders:
d, D, a, A - can be replaced by any kind of argument (color, number, escaped value,
expression, ...). If you use them in combination with string, the whole string will be used -
including its quotes. However, the quotes are placed into the string as they are, they are not
escaped by "/" nor anything similar.
s, S - can be replaced by any expression. If you use it with string, only the string value is used
- quotes are omitted.
Parameters:
string: format string with placeholders,
anything* : values to replace placeholders.
Returns: formatted string.
Example:
format-a-d:%("repetitions:%a file: %d", 1 + 2, "directory/file.less");
format-a-d-upper: %('repetitions: %A file: %D', 1 + 2, "directory/file.less");
format-s: %("repetitions: %s file: %s", 1 + 2, "directory/file.less");
format-s-upper: %('repetitions: %S file: %S', 1 + 2, "directory/file.less");
Output:
format-a-d: "repetitions:
3 file: "directory/file.less"";format-a-d-upper: "repetitions:
3 file: %22directory%2Ffile.less%22";format-s: "repetitions:
3 file: directory/file.less";format-s-upper: "repetitions:
3 file: directory%2Ffile.less";
replace
Replaces a text within a string.
Released v1.7.0
Parameters:
string: The string to search and replace in.
pattern: A string or regular expression pattern to search for.
replacement: The string to replace the matched pattern with.
flags: (Optional) regular expression flags.
Returns: a string with the replaced values.
Example:
replace("Hello, Mars?", "Mars\?", "Earth!");
replace("One + one = 4", "one", "2", "gi");
replace('This is a string.', "(string)\.$", "new $1.");
replace(~"bar-1", '1', '2');
Result:
"Hello, Earth!";
"2 + 2 = 4";
'This is a new string.';
bar-2;
List Functions
length
Returns the number of elements in a value list.
Parameters
list - a comma or space separated list of values.
Example: length(1px solid #0080ff);
Output: 3
Example:
@list: "banana", "tomato", "potato", "peach";n: length(@list);
Output:
n: 4;
extract
Returns the value at a specified position in a list.
Parameters
list - a comma or space separated list of values.
index - an integer that specifies a position of a list element to return.
Example: extract(8px dotted red, 2);
Output: dotted
Example:
@list: apple, pear, coconut, orange;value: extract(@list, 3);
Output:
value: coconut;
range
Released v3.9.0
Generate a list spanning a range of values
Parameters
start - (optional) The start value e.g. 1 or 1px
end - The end value e.g. 5px
step - (optional) The amount to increment by
Examples:
value: range(4);
Outputs:
value: 1 2 3 4;
The output of each value in the range will be the same unit as the end value. For example:
value: range(10px, 30px, 10);
Outputs:
value: 10px 20px 30px;
each
Released v3.7.0
Bind the evaluation of a ruleset to each member of a list.
Parameters
list - a comma or space separated list of values.
rules - An anonymous ruleset/mixin
Example:
@selectors: blue, green, red;
each(@selectors, {
.sel-@{value} {
a: b;
}
});
Outputs:
.sel-blue {
a: b;
}.sel-green {
a: b;
}.sel-red {
a: b;
}
By default, each ruleset is bound, per list member, to a @value, @key, and @index variable.
For most lists, @key and @index will be assigned the same value (numerical position,
1-based). However, you can also use rulesets themselves as structured lists. As in:
@set: {
one: blue;
two: green;
three: red;
}
.set {
each(@set, {
@{key}-@{index}: @value;
});
}
This will output:
.set {
one-1: blue;
two-2: green;
three-3: red;
}
Since you can, of course, call mixins with guards for each ruleset call, this makes each() a
very powerful function.
Setting variable names in each()
You don't have to use @value, @key, and @index in your each() function. In Less 3.7, with
the each() function, Less is introducing the concept of anonymous mixins, which may expand
to other parts of the syntax at a later date.
An anonymous mixin uses the form of #() or .() starting with . or # just like a regular mixin
would. In each(), you can use it like this:
.set-2() {
one: blue;
two: green;
three: red;
}.set-2 {
// Call mixin and iterate each rule
each(.set-2(), .(@v, @k, @i) {
@{k}-@{i}: @v;
});
}
This outputs, as expected:
.set-2 {
one-1: blue;
two-2: green;
three-3: red;
}
The each() function will take the variable names defined in the anonymous mixin and bind
them to the @value, @key and @index values, in that order. If you only write each(@list,
#(@value) {}), then neither @key nor @index will be defined.
Creating a for loop using range and each
Requires Less v3.9.0
You can emulate a for loop simply by generating a numerical list and using each to expand it
to a ruleset.
Example:
each(range(4), {
.col-@{value} {
height: (@value * 50px);
}
});
Outputs:
.col-1 {
height: 50px;
}.col-2 {
height: 100px;
}.col-3 {
height: 150px;
}.col-4 {
height: 200px;
}
Math Functions
ceil
Rounds up to the next highest integer.
Parameters: number - a floating point number.
Returns: integer
Example: ceil(2.4)
Output: 3
floor
Rounds down to the next lowest integer.
Parameters: number - a floating point number.
Returns: integer
Example: floor(2.6)
Output: 2
percentage
Converts a floating point number into a percentage string.
Parameters: number - a floating point number.
Returns: string
Example: percentage(0.5)
Output: 50%
round
Applies rounding.
Parameters:
number: A floating point number.
decimalPlaces: Optional: The number of decimal places to round to. Defaults to 0.
Returns: number
Example: round(1.67)
Output: 2
Example: round(1.67, 1)
Output: 1.7
sqrt
Calculates square root of a number. Keeps units as they are.
Parameters: number - floating point number.
Returns: number
Example:
sqrt(25cm)
Output:
5cm
Example:
sqrt(18.6%)
Output:
4.312771730569565%;
abs
Calculates absolute value of a number. Keeps units as they are.
Parameters: number - a floating point number.
Returns: number
Example #1: abs(25cm)
Output: 25cm
Example #2: abs(-18.6%)
Output: 18.6%;
sin
Calculates sine function.
Assumes radians on numbers without units.
Parameters: number - a floating point number.
Returns: number
Example:
sin(1); // sine of 1 radiansin(1deg); // sine of 1 degreesin(1grad); // sine of 1 gradian
Output:
0.8414709848078965; // sine of 1 radian
0.01745240643728351; // sine of 1 degree
0.015707317311820675; // sine of 1 gradian
asin
Calculates arcsine (inverse of sine) function.
Returns number in radians e.g. a number between -π/2 and π/2.
Parameters: number - floating point number from [-1, 1] interval.
Returns: number
Example:
asin(-0.8414709848078965)asin(0)asin(2)
Output:
-1rad
0rad
NaNrad
cos
Calculates cosine function.
Assumes radians on numbers without units.
Parameters: number - a floating point number.
Returns: number
Example:
cos(1) // cosine of 1 radiancos(1deg) // cosine of 1 degreecos(1grad) // cosine of 1 gradian
Output:
0.5403023058681398 // cosine of 1 radian
0.9998476951563913 // cosine of 1 degree
0.9998766324816606 // cosine of 1 gradian
acos
Calculates arccosine (inverse of cosine) function.
Returns number in radians e.g. a number between 0 and π.
Parameters: number - a floating point number from [-1, 1] interval.
Returns: number
Example:
acos(0.5403023058681398)acos(1)acos(2)
Output:
1rad
0rad
NaNrad
tan
Calculates tangent function.
Assumes radians on numbers without units.
Parameters: number - a floating point number.
Returns: number
Example:
tan(1) // tangent of 1 radiantan(1deg) // tangent of 1 degreetan(1grad) // tangent of 1 gradian
Output:
1.5574077246549023 // tangent of 1 radian
0.017455064928217585 // tangent of 1 degree
0.015709255323664916 // tangent of 1 gradian
atan
Calculates arctangent (inverse of tangent) function.
Returns number in radians e.g. a number between -π/2 and π/2.
Parameters: number - a floating point number.
Returns: number
Example:
atan(-1.5574077246549023)atan(0)round(atan(22), 6) // arctangent of 22 rounded to 6
decimal places
Output:
-1rad
0rad
1.525373rad;
pi
Returns π (pi);
Parameters: none
Returns: number
Example:
pi()
Output:
3.141592653589793
pow
Returns the value of the first argument raised to the power of the second argument.
Returned value has the same dimension as the first parameter and the dimension of the
second parameter is ignored.
Parameters:
number: base -a floating point number.
number: exponent - a floating point number.
Returns: number
Example:
pow(0cm, 0px)pow(25, -2)pow(25, 0.5)pow(-25, 0.5)pow(-25%, -0.5)
Output:
1cm
0.0016
5
NaN
NaN%
mod
Returns the value of the first argument modulus second argument.
Returned value has the same dimension as the first parameter, the dimension of the second
parameter is ignored. The function is able to handle also negative and floating point numbers.
Parameters:
number: a floating point number.
number: a floating point number.
Returns: number
Example:
mod(0cm, 0px)mod(11cm, 6px);mod(-26%, -5);
Output:
NaNcm;
5cm
-1%;
min
Returns the lowest of one or more values.
Parameters: value1, ..., valueN - one or more values to compare.
Returns: the lowest value.
Example: min(5, 10);
Output: 5
Example: min(3px, 42px, 1px, 16px);
Output: 1px
max
Returns the highest of one or more values.
Parameters: value1, ..., valueN - one or more values to compare.
Returns: the highest value.
Example: max(5, 10);
Output: 10
Example: max(3%, 42%, 1%, 16%);
Output: 42%
Type Functions
isnumber
Returns true if a value is a number, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a number, false otherwise.
Example:
isnumber(#ff0); // false
isnumber(blue); // false
isnumber("string"); // false
isnumber(1234); // true
isnumber(56px); // true
isnumber(7.8%); // true
isnumber(keyword); // false
isnumber(url(...)); // false
isstring
Returns true if a value is a string, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a string, false otherwise.
Example:
isstring(#ff0); // false
isstring(blue); // false
isstring("string"); // true
isstring(1234); // false
isstring(56px); // false
isstring(7.8%); // false
isstring(keyword); // false
isstring(url(...)); // false
iscolor
Returns true if a value is a color, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a color, false otherwise.
Example:
iscolor(#ff0); // true
iscolor(blue); // true
iscolor("string"); // false
iscolor(1234); // false
iscolor(56px); // false
iscolor(7.8%); // false
iscolor(keyword); // false
iscolor(url(...)); // false
iskeyword
Returns true if a value is a keyword, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a keyword, false otherwise.
Example:
iskeyword(#ff0); // false
iskeyword(blue); // false
iskeyword("string"); // false
iskeyword(1234); // false
iskeyword(56px); // false
iskeyword(7.8%); // false
iskeyword(keyword); // true
iskeyword(url(...)); // false
isurl
Returns true if a value is a url, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a url, false otherwise.
Example:
isurl(#ff0); // false
isurl(blue); // false
isurl("string"); // false
isurl(1234); // false
isurl(56px); // false
isurl(7.8%); // false
isurl(keyword); // false
isurl(url(...)); // true
ispixel
Returns true if a value is a number in pixels, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a pixel, false otherwise.
Example:
ispixel(#ff0); // false
ispixel(blue); // false
ispixel("string"); // false
ispixel(1234); // false
ispixel(56px); // true
ispixel(7.8%); // false
ispixel(keyword); // false
ispixel(url(...)); // false
isem
Returns true if a value is an em value, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is an em value, false otherwise.
Example:
isem(#ff0); // false
isem(blue); // false
isem("string"); // false
isem(1234); // false
isem(56px); // false
isem(7.8em); // true
isem(keyword); // false
isem(url(...)); // false
ispercentage
Returns true if a value is a percentage value, false otherwise.
Parameters: value - a value or variable being evaluated.
Returns: true if value is a percentage value, false otherwise.
Example:
ispercentage(#ff0); // false
ispercentage(blue); // false
ispercentage("string"); // false
ispercentage(1234); // false
ispercentage(56px); // false
ispercentage(7.8%); // true
ispercentage(keyword); // false
ispercentage(url(...)); // false
isunit
Returns true if a value is a number in specified units, false otherwise.
Parameters:
value - a value or variable being evaluated.
unit - a unit identifier (optionally quoted) to test for.
Returns: true if value is a number in specified units, false otherwise.
Example:
isunit(11px, px); // true
isunit(2.2%, px); // false
isunit(33px, rem); // false
isunit(4rem, rem); // true
isunit(56px, "%"); // false
isunit(7.8%, '%'); // true
isunit(1234, em); // false
isunit(#ff0, pt); // false
isunit("mm", mm); // false
isruleset
Returns true if a value is a ruleset, false otherwise.
Parameters:
value - a variable being evaluated.
Returns: true if value is a ruleset, false otherwise.
Example:
@rules: {
color: red;
}
isruleset(@rules); // true
isruleset(#ff0); // false
isruleset(blue); // false
isruleset("string"); // false
isruleset(1234); // false
isruleset(56px); // false
isruleset(7.8%); // false
isruleset(keyword); // false
isruleset(url(...)); // false
Misc Functions
color
Parses a color, so a string representing a color becomes a color.
Parameters: string: a string of the specified color.
Returns: color
Example: color("#aaa");
Output: #aaa
image-size
Gets the image dimensions from a file.
Parameters: string: the file to get the dimensions for.
Returns: dimension
Example: image-size("file.png");
Output: 10px 10px
Note: this function needs to be implemented by each environment. It is currently only
available in the node environment.
Added in: v2.2.0
image-width
Gets the image width from a file.
Parameters: string: the file to get the dimensions for.
Returns: dimension
Example: image-width("file.png");
Output: 10px
Note: this function needs to be implemented by each environment. It is currently only
available in the node environment.
Added in: v2.2.0
image-height
Gets the image height from a file.
Parameters: string: the file to get the dimensions for.
Returns: dimension
Example: image-height("file.png");
Output: 10px
Note: this function needs to be implemented by each environment. It is currently only
available in the node environment.
Added in: v2.2.0
convert
Convert a number from one unit into another.
The first argument contains a number with units and second argument contains units. If the
units are compatible, the number is converted. If they are not compatible, the first argument
is returned unmodified.
See unit for changing the unit without conversion.
Compatible unit groups:
lengths: m, cm, mm, in, pt and pc,
time: s and ms,
angle: rad, deg, grad and turn.
Parameters:
number: a floating point number with units.
identifier, string or escaped value: units
Returns: number
Example:
convert(9s, "ms")convert(14cm, mm)convert(8, mm) // incompatible unit types
Output:
9000ms
140mm
8
data-uri
Inlines a resource and falls back to url() if the ieCompat option is on and the resource is too
large, or if you use the function in the browser. If the MIME type is not given then node uses
the mime package to determine the correct mime type.
Parameters:
mimetype: (Optional) A MIME type string.
url: The URL of the file to inline.
If there is no mimetype, data-uri function guesses it from filename suffix. Text and svg files
are encoded as utf-8 and anything else is encoded as base64.
If user provided mimetype, the function uses base64 if mimetype argument ends with ;base64.
For example, image/jpeg;base64 is encoded into base64 while text/html is encoded into utf-8.
Example: data-uri('../data/image.jpg');
Output: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
Output in browser: url('../data/image.jpg');
Example:
data-uri('image/jpeg;base64', '../data/image.jpg');
Output:
url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
Example:
data-uri('image/svg+xml;charset=UTF-8', 'image.svg');
Output:
url("data:image/svg+xml;charset=UTF-8,%3Csvg%3E%3Ccircle%20r%3D%229%22%2F%
3E%3C%2Fsvg%3E");
default
Available only inside guard conditions and returns true only if no other mixin
matches, false otherwise.
Example:
.mixin(1) {x: 11}.
mixin(2) {y: 22}.
mixin(@x) when (default()) {z: @x}
div {
.mixin(3);
}
div.special {
.mixin(1);
}
Output:
div {
z: 3;
}div.special {
x: 11;
}
It is possible to use the value returned by default with guard operators. For example .mixin()
when not(default()) {} will match only if there's at least one more mixin definition that
matches.mixin() call:
.mixin(@value) when (ispixel(@value)) {width: @value}.mixin(@value) when not(default())
{padding: (@value / 5)}
div-1 {
.mixin(100px);
}
div-2 {
/* ... */
.mixin(100%);
}
result:
div-1 {
width: 100px;
padding: 20px;
}div-2 {
/* ... */
}
It is allowed to make multiple default() calls in the same guard condition or in a different
conditions of a mixins with the same name:
div {
.m(@x) when (default()), not(default()) {always: @x}
.m(@x) when (default()) and not(default()) {never: @x}
.m(1); // OK
}
However Less will throw a error if it detects a potential conflict between multiple mixin
definitions using default():
div {
.m(@x) when (default()) {}
.m(@x) when not(default()) {}
.m(1); // Error
}
In above example it is impossible to determine what value each default() call should return
since they recursively depend on each other.
Advanced multiple default() usage:
.x {
.m(red) {case-1: darkred}
.m(blue) {case-2: darkblue}
.m(@x) when (iscolor(@x)) and (default()) {default-color: @x}
.m('foo') {case-1: I am 'foo'}
.m('bar') {case-2: I am 'bar'}
.m(@x) when (isstring(@x)) and (default()) {default-string: and I am the default}
&-blue {.m(blue)}
&-green {.m(green)}
&-foo {.m('foo')}
&-baz {.m('baz')}
}
Result:
.x-blue {
case-2: #00008b;
}.x-green {
default-color: #008000;
}.x-foo {
case-1: I am 'foo';
}.x-baz {
default-string: and I am the default;
}
The default function is available as a Less built-in function only inside guard expressions. If
used outside of a mixin guard condition it is interpreted as a regular CSS value:
Example:
div {
foo: default();
bar: default(42);
}
Result:
div {
foo: default();
bar: default(42);
}
unit
Remove or change the unit of a dimension
Parameters:
dimension: A number, with or without a dimension.
unit: (Optional) the unit to change to, or if omitted it will remove the unit.
See convert for changing the unit with conversion.
Example: unit(5, px)
Output: 5px
Example: unit(5em)
Output: 5
get-unit
Returns units of a number.
If the argument contains a number with units, the function returns its units. The argument
without units results in an empty return value.
Parameters:
number: a number with or without units.
Example: get-unit(5px)
Output: px
Example: get-unit(5)
Output: //nothing
svg-gradient
Generates multi-stop svg gradients.
Svg-gradient function generates multi-stop svg gradients. It must have at least three
parameters. First parameter specifies gradient type and direction and remaining parameters
list colors and their positions. The position of first and last specified color are optional,
remaining colors must have positions specified.
The direction must be one of to bottom, to right, to bottom right, to top right, ellipse or ellipse
at center. The direction can be specified as both escaped value ~'to bottom' and space
separated list of words to bottom.
The direction must be followed by two or more color stops. They can be supplied either
inside a list or you can specify each color stops in separate argument.
Parameters - colors stops in list:
escaped value or list of identifiers: direction
list - all colors and their positions in list
Parameters - color stops in arguments:
escaped value or list of identifiers: direction
color [percentage] pair: first color and its relative position (position is optional)
color percent pair: (optional) second color and its relative position
...
color percent pair: (optional) n-th color and its relative position
color [percentage] pair: last color and its relative position (position is optional)
Returns: url with "URI-Encoded" svg gradient.
Example - colors stops in list:
div {
@list: red, green 30%, blue;
background-image: svg-gradient(to right, @list);
}
equivalent - color stops in arguments:
div {
background-image: svg-gradient(to right, red, green 30%, blue);
}
Mixins
"mix-in" properties from existing styles
You can mix-in class selectors and id selectors, e.g.
.a, #b {
color: red;
}.mixin-class {
.a();
}.mixin-id {
#b();
}
which results in:
.a, #b {
color: red;
}.mixin-class {
color: red;
}.mixin-id {
color: red;
}
Currently and historically, the parentheses in a mixin call are optional, but optional
parentheses are deprecated and will be required in a future release.
.a(); .a; // currently works, but deprecated; don't use
Not Outputting the Mixin
If you want to create a mixin but you do not want that mixin to be in your CSS output, put
parentheses after the mixin definition.
.my-mixin {
color: black;
}.my-other-mixin() {
background: white;
}.class {
.my-mixin();
.my-other-mixin();
}
outputs
.my-mixin {
color: black;
}.class {
color: black;
background: white;
}
Selectors in Mixins
Mixins can contain more than just properties, they can contain selectors too.
For example:
.my-hover-mixin() {
&:hover {
border: 1px solid red;
}
}button {
.my-hover-mixin();
}
Outputs
button:hover {
border: 1px solid red;
}
Operations
Arithmetical operations +, -, *, / can operate on any number, color or variable. If it is possible,
mathematical operations take units into account and convert numbers before adding,
subtracting or comparing them. The result has leftmost explicitly stated unit type. If the
conversion is impossible or not meaningful, units are ignored. Example of impossible
conversion: px to cm or rad to %.
// numbers are converted into the same units@conversion-1: 5cm + 10mm;
// result is 6cm@conversion-2: 2 - 3cm - 5mm; // result is -1.5cm
// conversion is impossible@incompatible-units: 2 + 5px - 3cm; // result is 4px
// example with variables@base: 5%;@filler: @base * 2;
// result is 10%@other: @base + @filler; // result is 15%
Multiplication and division do not convert numbers. It would not be meaningful in most cases
- a length multiplied by a length gives an area and css does not support specifying areas. Less
will operate on numbers as they are and assign explicitly stated unit type to the result.
@base: 2cm * 3mm; // result is 6cm
You can also do arithmetic on colors:
@color: #224488 / 2; //results in #112244background-color: #112244 + #111; //
result is #223355
However, you may find Less's Color Functions more useful.
calc() exception
For CSS compatibility, calc() does not evaluate math expressions, but will evaluate variables
and math in nested functions.
@var: 50vh/2;width: calc(50% + (@var - 20px)); // result is calc(50% + (25vh -
20px))
Nesting
Less gives you the ability to use nesting instead of, or in combination with cascading. Let's
say we have the following CSS:
#header {
color: black;
}#header .navigation {
font-size: 12px;
}#header .logo {
width: 300px;
}
In Less, we can also write it this way:
#header {
color: black;
.navigation {
font-size: 12px;
}
.logo {
width: 300px;
}
}
The resulting code is more concise, and mimics the structure of your HTML.
You can also bundle pseudo-selectors with your mixins using this method. Here's the classic
clearfix hack, rewritten as a mixin (& represents the current selector parent):
.clearfix {
display: block;
zoom: 1;
&:after {
content: " ";
display: block;
font-size: 0;
height: 0;
clear: both;
visibility: hidden;
}
}
Nested At-Rules and Bubbling
At-rules such as @media or @supports can be nested in the same way as selectors. The
at-rule is placed on top and relative order against other elements inside the same ruleset
remains unchanged. This is called bubbling.
.component {
width: 300px;
@media (min-width: 768px) {
width: 600px;
@media (min-resolution: 192dpi) {
background-image: url(/img/retina2x.png);
}
}
@media (min-width: 1280px) {
width: 800px;
}
}
outputs:
.component {
width: 300px;
}@media (min-width: 768px) {
.component {
width: 600px;
}
}@media (min-width: 768px) and (min-resolution: 192dpi) {
.component {
background-image: url(/img/retina2x.png);
}
}@media (min-width: 1280px) {
.component {
width: 800px;
}
}
Scope
Scope in Less is very similar to that of CSS. Variables and mixins are first looked for locally,
and if they aren't found, it's inherited from the "parent" scope.
@var: red;
#page {
@var: white;
#header {
color: @var; // white
}
}
Like CSS custom properties, mixin and variable definitions do not have to be placed before a
line where they are referenced. So the following Less code is identical to the previous
example:
@var: red;
#page {
#header {
color: @var; // white
}
@var: white;
}
Escaping
Escaping allows you to use any arbitrary string as property or variable value. Anything
inside ~"anything" or ~'anything' is used as is with no changes except interpolation.
@min768: ~"(min-width: 768px)";.element {
@media @min768 {
font-size: 1.2rem;
}
}
results in:
@media (min-width: 768px) {
.element {
font-size: 1.2rem;
}
}
Note, as of Less 3.5, you can simply write:
@min768: (min-width: 768px);.element {
@media @min768 {
font-size: 1.2rem;
}
}
Maps
As of Less 3.5, you can also use mixins and rulesets as maps of values.
#colors() {
primary: blue;
secondary: green;
}
.button {
color: #colors[primary];
border: 1px solid #colors[secondary];
}
This outputs, as expected:
.button {
color: blue;
border: 1px solid green;
}
Comments
Both block-style and inline comments may be used:
/* One heck of a block
* style comment! */@var: red;
// Get in line!@var: white;
Imports
Importing works pretty much as expected. You can import a .less file, and all the variables in
it will be available. The extension is optionally specified for .less files.
@import "library"; // library.less@import "typo.css";
CSS Guards
Like Mixin Guards, guards can also be applied to css selectors, which is syntactic sugar for
declaring the mixin and then calling it immediately.
For instance, before 1.5.0 you would have had to do this:
.my-optional-style() when (@my-option = true) {
button {
color: white;
}
}.my-optional-style();
Now, you can apply the guard directly to a style.
button when (@my-option = true) {
color: white;
}
You can also achieve an if type statement by combining this with the & feature, allowing you
to group multiple guards.
& when (@my-option = true) {
button {
color: white;
}
a{
color: blue;
}
}
Note that you can also achieve a similar pattern by using the actual if() function and a
variable call. As in:
@dr: if(@my-option = true, {
button {
color: white;
}
a{
color: blue;
}
});@dr();