├── 1. Javascript Basics ├── Ex 01 - Internal & External Scripts │ ├── index.html │ └── scripts.js ├── Ex 02 - Variables │ ├── index.html │ └── scripts.js ├── Ex 03 - Arithmetic Operators │ ├── index.html │ └── scripts.js ├── Ex 04 - Assignment Operators │ ├── index.html │ └── scripts.js ├── Ex 05 - Challenge 1 │ ├── index.html │ └── scripts.js ├── Ex 06 - If Else │ ├── index.html │ └── scripts.js ├── Ex 07 - Comparison Operators │ ├── index.html │ └── scripts.js ├── Ex 08 - Logical Operators │ ├── index.html │ └── scripts.js ├── Ex 09 - Switch Case │ ├── index.html │ └── scripts.js ├── Ex 10 - Bitwise Operators │ ├── index.html │ └── scripts.js ├── Ex 11 - Challenge 2 │ ├── index.html │ └── scripts.js ├── Ex 12 - Functions │ ├── index1.html │ ├── index2.html │ ├── scripts1.js │ └── scripts2.js ├── Ex 13 - Arrays │ ├── index.html │ └── scripts.js ├── Ex 14 - Challenge 3 │ ├── index.html │ └── scripts.js ├── Ex 15 - Objects │ ├── index.html │ └── scripts.js ├── Ex 16 - Challenge 4 │ ├── index.html │ └── scripts.js ├── Ex 17 - Loops │ ├── index.html │ └── scripts.js ├── Ex 18 - Error Handling │ ├── index.html │ └── scripts.js ├── Ex 19 - Javascript Scope │ ├── index.html │ └── scripts.js └── Ex 20 - Challenge 5 │ ├── index.html │ └── scripts.js └── 2. Javascript Document Object Model (DOM) ├── index.html ├── scripts1.js ├── scripts2.js └── scripts3.js /1. Javascript Basics/Ex 01 - Internal & External Scripts/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Internal & External Scripts 7 | 8 | 9 |
10 |

Javascript Language Basics - Internal & External Scripts

11 |
12 | 13 | 14 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 01 - Internal & External Scripts/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // ---------External--------------- 3 | // -------------------------------- 4 | 5 | // Print 6 | console.log("Hope you are fine!"); -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 02 - Variables/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Variables 7 | 8 | 9 |
10 |

Javascript Language Basics - Variables

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 02 - Variables/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // ---------Variables-------------- 3 | // -------------------------------- 4 | 5 | // --Primitive Data Types-- 6 | /* Number - Floating point numbers, for decimals and integers 7 | String - Sequence of characters, used for text 8 | Boolean - Logical data type that can only be true or false 9 | Undefined - Data type of a variable that does not have a value yet 10 | Null - Non-existent */ 11 | 12 | // You only can start a varible name with a letter, underscore or dollar sign. 13 | // And can't use any reserved keywords as variable names 14 | 15 | // Create variables 16 | var firstName = 'Chamara'; 17 | var lastName = 'Perera'; 18 | var age = 26; 19 | var isOk = true; 20 | var job, height; 21 | 22 | // Print only variable 23 | console.log(firstName); 24 | // Print the variable with a string 25 | console.log('My name is '+lastName); 26 | // Type Coercion 27 | console.log('My age is '+age); 28 | console.log('It is '+isOk); 29 | console.log('I am a '+job); 30 | 31 | // Get variable type 32 | console.log(typeof(lastName)); 33 | console.log(typeof(age)); 34 | console.log(typeof(isOk)); 35 | console.log(typeof(job)); 36 | 37 | // Define 38 | job = 'Doctor'; 39 | // Variable Mutation 40 | lastName = 'Fernando'; 41 | console.log('I am '+lastName+' I am a '+job); 42 | 43 | // Dsiplay an alert 44 | alert('My name is '+lastName+'. I am '+age+' years old. And am I ok? '+isOk+'.'); 45 | 46 | // Get user input 47 | height = prompt('What is your height?'); 48 | alert('My height is '+height+' feet.'); 49 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 03 - Arithmetic Operators/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Arithmetic Operators 7 | 8 | 9 |
10 |

Javascript Language Basics - Arithmetic Operators

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 03 - Arithmetic Operators/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // ------Arithmetic Operators------ 3 | // -------------------------------- 4 | 5 | // --Single Operators-- 6 | var myAge, yourAge, year, result; 7 | myAge = 26; 8 | yourAge = 20; 9 | year = 2021; 10 | 11 | // Substraction 12 | result = year - myAge; 13 | console.log('I was born in '+result); 14 | 15 | // Addition 16 | result = year + 10; 17 | console.log('After 10 years, It will be '+result); 18 | 19 | // Multiplication 20 | result = myAge * yourAge; 21 | console.log('Product of our ages '+result); 22 | 23 | // Division 24 | console.log('Division of our ages '+(myAge/yourAge)); 25 | 26 | // Modulus 27 | console.log('Modulus of our ages '+(myAge%yourAge)); 28 | 29 | // Exponentiation 30 | console.log('Exponent of my age '+(myAge**2)); 31 | 32 | // Increment 33 | console.log(myAge++); 34 | console.log('Post Increment of my age '+myAge); 35 | 36 | console.log(++myAge); 37 | console.log('Pre Increment of my age '+myAge); 38 | 39 | // Decrement 40 | console.log(myAge--); 41 | console.log('Post Decrement of my age '+myAge); 42 | 43 | console.log(--myAge); 44 | console.log('Pre Decrement of my age '+myAge); 45 | 46 | 47 | // --Operator Precedence-- 48 | var cal = (20+30)/10+4.5-2*4**2; 49 | console.log(cal); 50 | 51 | // --Multiple Operators-- 52 | var ans1, ans2; 53 | ans1 = ans2 = (((30+40-29)*2)/8)**4; // Assignment operator | right to left 54 | console.log(ans1+' | '+ans2); 55 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 04 - Assignment Operators/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Assignment Operators 7 | 8 | 9 |
10 |

Javascript Language Basics - Assignment Operators

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 04 - Assignment Operators/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // ------Assignment Operators------ 3 | // -------------------------------- 4 | 5 | // Equal 6 | var myName = 'Kasun'; 7 | console.log(myName); 8 | 9 | // Addition with equal 10 | var age = 24; 11 | age += 10; // age = age + 10 12 | console.log(age); 13 | 14 | // Substraction with equal 15 | age -= 10; 16 | console.log(age); 17 | 18 | // Multiplication with equal 19 | age *= 10; 20 | console.log(age); 21 | 22 | // Division with equal 23 | age /= 4; 24 | console.log(age); 25 | 26 | // Modulus with equal 27 | age %= 13; 28 | console.log(age); 29 | 30 | // Exponentiation with equal 31 | age **= 2; 32 | console.log(age); -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 05 - Challenge 1/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - BMI Comparison 7 | 8 | 9 |
10 |

Javascript Language Basics - BMI Comparison

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 05 - Challenge 1/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // ---------BMI Comparison--------- 3 | // -------------------------------- 4 | 5 | /* 6 | Kasun and Chamal are trying to compare their BMI (Body Mass Index), which is calculated using the formula: 7 | BMI = mass / height ^ 2 8 | (Mass is kg and Height in meter) 9 | 10 | 1. Store Kasun's and Chamal's mass and height in variables 11 | 2. Calculate both their BMIs 12 | 3. Create a boolean variable containing information about whether Kasun has a higher BMI than Chamal. 13 | 4. Print a string to in alert box containing the variable from step 3. 14 | */ 15 | 16 | var mass, height, bmik, bmic, isKasun; 17 | 18 | // Kasun's BMI 19 | mass = prompt("Kasun's mass : "); 20 | height = prompt("Kasun's height : "); 21 | bmik = mass / (height * height); 22 | 23 | // Chamal's BMI 24 | mass = prompt("Chamal's mass : "); 25 | height = prompt("Chamal's height : "); 26 | bmic = mass / (height * height); 27 | 28 | // Boolean 29 | isKasun = (bmik > bmic); 30 | 31 | alert(isKasun); 32 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 06 - If Else/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - If Else 7 | 8 | 9 |
10 |

Javascript Language Basics - If Else

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 06 - If Else/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // -------------If Else------------ 3 | // -------------------------------- 4 | 5 | var a = 10; 6 | var b = 20; 7 | 8 | // Condition 9 | if(a > b){ 10 | console.log("a is greater than b"); 11 | } 12 | // Condition 13 | else if(a < b){ 14 | console.log("a is less than b"); 15 | } 16 | else{ 17 | console.log("a is equal to b"); 18 | } 19 | 20 | // Condition 21 | if(a == 10){ 22 | console.log("a is equal to 10"); 23 | } -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 07 - Comparison Operators/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Comparison Operators 7 | 8 | 9 |
10 |

Javascript Language Basics - Comparison Operators

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 07 - Comparison Operators/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // -----Comparison Operators------- 3 | // -------------------------------- 4 | 5 | var a = 20; 6 | var b = '20'; 7 | var c = 5; 8 | var d = 15; 9 | 10 | // Equal to 11 | if(a == b){ 12 | // Equal value and equal type 13 | if(a === b){ 14 | console.log('Both value and type of a is equal to b'); 15 | } 16 | // Not equal value or not equal type 17 | else if(a !== b){ 18 | console.log('Only value or type of a is equal to b'); 19 | } 20 | } 21 | // Greater than or equal to 22 | else if(a >= 10){ 23 | // Greater than 24 | if(a > 10){ 25 | console.log('a is greater than 10'); 26 | } 27 | // Equal to 28 | else if(a == 10){ 29 | console.log('a is equal to 10'); 30 | } 31 | } 32 | // Not equal 33 | else if(a != c){ 34 | // Less than 35 | if(a < c){ 36 | console.log('a is less than c'); 37 | } 38 | else{ 39 | console.log('a is greater than c'); 40 | } 41 | } 42 | else{ 43 | // Less than or equal to 44 | if(c <= d){ 45 | // if(c <= 5){ 46 | // console.log('c is less than or equal to 5'); 47 | // } 48 | // else{ 49 | // console.log('c is greater than to 5'); 50 | // } 51 | 52 | // Ternary operator 53 | c <= 5 ? console.log('c is less than or equal to 5') : console.log('c is greater than to 5'); 54 | } 55 | else{ 56 | console.log('c is greater d'); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 08 - Logical Operators/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Logical Operators 7 | 8 | 9 |
10 |

Javascript Language Basics - Logical Operators

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 08 - Logical Operators/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // --------Logical Operators------- 3 | // -------------------------------- 4 | 5 | var a = 20; 6 | var b = 10; 7 | var c = 5; 8 | 9 | // And 10 | if(a == 10 && a == b){ 11 | console.log('It is good'); 12 | } 13 | // Or 14 | else if(a > 10 || c > b){ 15 | console.log('It is ok'); 16 | } 17 | // Not 18 | else if(a != c){ 19 | console.log('It is normal'); 20 | } 21 | else{ 22 | console.log("It is bad"); 23 | } 24 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 09 - Switch Case/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Switch Case 7 | 8 | 9 |
10 |

Javascript Language Basics - Switch Case

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 09 - Switch Case/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // -----------Switch Case---------- 3 | // -------------------------------- 4 | 5 | var empName = "Kasun"; 6 | var jobRole = "Doctor"; 7 | 8 | switch(jobRole.toLowerCase()){ 9 | case 'teacher': 10 | console.log(empName+' is a Teacher.'); 11 | break; 12 | case 'doctor': 13 | case 'professor': 14 | console.log(empName+' is a Doctor.'); 15 | break; 16 | case 'engineer': 17 | console.log(empName+' is a Teacher.'); 18 | break; 19 | case 'singer': 20 | console.log(empName+' is a Teacher.'); 21 | break; 22 | default: 23 | console.log(empName+' does something else.'); 24 | break; 25 | } 26 | 27 | // ----------------------------------- 28 | 29 | var age = 20; 30 | 31 | switch(true){ 32 | case age < 20: 33 | console.log(empName + ' is under age.'); 34 | break; 35 | case age >= 20 && age < 30: 36 | console.log(empName + ' is in perfect age.'); 37 | break; 38 | case age >= 30 && age < 50: 39 | console.log(empName + ' is mature.'); 40 | break; 41 | default: 42 | console.log(empName + ' is too old.'); 43 | } -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 10 - Bitwise Operators/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Bitwise Operators 7 | 8 | 9 |
10 |

Javascript Language Basics - Bitwise Operators

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 10 - Bitwise Operators/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------- 2 | // --------Bitwise Operators------- 3 | // -------------------------------- 4 | 5 | /* 6 | A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values. 7 | */ 8 | 9 | // 5 - 00000101 10 | // 1 - 00000001 11 | 12 | // And 13 | console.log(5 & 1); 14 | 15 | // Or 16 | console.log(5 | 1) 17 | 18 | // Not 19 | // 5 - 0000000000000000000000000000 0101 20 | // ~5 - 1111111111111111111111111111 1010 21 | // (2 ^ 32)- 1 - 5 22 | console.log(~5); 23 | 24 | // Xor 25 | console.log(5 ^ 1); 26 | 27 | // Zero fill left shift 28 | console.log(5 << 1); 29 | 30 | // Signed right shift 31 | console.log(5 >> 1); 32 | 33 | // Zero fill right shift 34 | console.log(5 >>> 1); 35 | 36 | // --Convert decimal to binary-- 37 | console.log((10).toString(2)); 38 | 39 | // --Convert binary to decimal-- 40 | console.log((0b1100).toString(10)); 41 | console.log(parseInt("1100", 2)); 42 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 11 - Challenge 2/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Winning Team 7 | 8 | 9 |
10 |

Javascript Language Basics - Winning Team

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 11 - Challenge 2/scripts.js: -------------------------------------------------------------------------------- 1 | // --------------------------- 2 | // --------Winning Team------- 3 | // --------------------------- 4 | 5 | /* 6 | Sri Lanka & England both played 3 match one day cricket series. In last 3 games Sri Lanka scored 250, 277, 300 runs, while England scored 185, 244, 360 runs. 7 | 8 | 1. Calculate the average score for each team 9 | 2. Decide which teams wins in average (highest average score), and display the winner with the average score 10 | 3. Then change scores to show different winners. Don't forget to take into account there might be a draw (same average score) 11 | */ 12 | 13 | var score1, score2, score3, averageSri, averageEng; 14 | 15 | // Sri Lanka average 16 | score1 = parseInt(prompt("First match score of team Sri Lanka : ")); 17 | score2 = parseInt(prompt("Second match score of team Sri Lanka : ")); 18 | score3 = parseInt(prompt("Third match score of team Sri Lanka : ")); 19 | 20 | averageSri = (score1+score2+score3)/3; 21 | 22 | // England average 23 | score1 = parseInt(prompt("First match score of team England : ")); 24 | score2 = parseInt(prompt("Second match score of team England : ")); 25 | score3 = parseInt(prompt("Third match score of team England : ")); 26 | 27 | averageEng = (score1+score2+score3)/3; 28 | 29 | // Find the winner 30 | if(averageSri > averageEng){ 31 | alert("Winner is team Sri Lanka | Average Score : "+averageSri); 32 | console.log("Winner is team Sri Lanka | Average Score : "+averageSri); 33 | } 34 | else if(averageSri < averageEng){ 35 | alert("Winner is team England | Average Score : "+averageEng); 36 | console.log("Winner is team England | Average Score : "+averageEng); 37 | } 38 | else{ 39 | alert("Match drawn, average scores are equal!"); 40 | console.log("Match drawn, average scores are equal!"); 41 | } 42 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 12 - Functions/index1.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Introduction of Functions 7 | 8 | 9 |
10 |

Javascript Language Basics - Introduction of Functions

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 12 - Functions/index2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Function Expressions 7 | 8 | 9 |
10 |

Javascript Language Basics - Function Expressions

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 12 - Functions/scripts1.js: -------------------------------------------------------------------------------- 1 | // ---------------------------------------------- 2 | // -----------Introduction of Functions---------- 3 | // ---------------------------------------------- 4 | 5 | /* 6 | Funtion is a re-usable peace of code that does a specific thing. 7 | */ 8 | 9 | // --Define functions-- 10 | 11 | // Without return 12 | function addNumbers(num1, num2){ 13 | var ans = num1 + num2; 14 | console.log("Additon : "+ans); 15 | } 16 | 17 | // With return 18 | function subNumbers(num1, num2){ 19 | // Returns the value to where we called the function 20 | // Exit the function 21 | return num1 - num2; 22 | } 23 | 24 | // Calling functions 25 | addNumbers(20, 32.5); 26 | 27 | var sub = subNumbers(30, 12); 28 | console.log("Substraction :"+sub); 29 | 30 | // ---------------------------------- 31 | 32 | // Define 33 | function calculateAge(birthYear){ 34 | return 2021 - birthYear; 35 | } 36 | 37 | // Calling 38 | console.log("Kasun is "+calculateAge(1996)+" years old."); 39 | console.log("Priyan is "+calculateAge(2000)+" years old."); 40 | 41 | // Define 42 | function retiringYear(firstName, birthYear){ 43 | // Calling 44 | var age = calculateAge(birthYear); 45 | var retire = 60 - age; 46 | console.log(firstName+" retires in "+retire+" years, in "+(birthYear+age+retire)); 47 | } 48 | 49 | // Calling 50 | retiringYear("Namal", 1990); 51 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 12 - Functions/scripts2.js: -------------------------------------------------------------------------------- 1 | // ----------------------------------------- 2 | // -----------Function Expressions---------- 3 | // ----------------------------------------- 4 | 5 | // --Function declaration-- 6 | // function profession(job, firstName){} 7 | 8 | // --Function expression-- 9 | var profession = function(job, firstName){ 10 | switch(job){ 11 | case 'doctor': 12 | return firstName+' is treating patients.'; 13 | case 'teacher': 14 | return firstName+' is teaching students.'; 15 | case 'engineer': 16 | return firstName+' is working with buildings.'; 17 | default: 18 | return firstName+' is doing something else.'; 19 | } 20 | } 21 | 22 | // Calling 23 | console.log(profession('doctor', 'Kasun')); 24 | console.log(profession('engineer', 'Sashini')); 25 | console.log(profession('professor', 'Kamal')); 26 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 13 - Arrays/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Arrays 7 | 8 | 9 |
10 |

Javascript Language Basics - Arrays

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 13 - Arrays/scripts.js: -------------------------------------------------------------------------------- 1 | // --------------------- 2 | // --------Arrays------- 3 | // --------------------- 4 | 5 | /* 6 | In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. 7 | */ 8 | 9 | // Ways to define an array 10 | var students = ['Ruwan', 'Namal', 'Piyal', 'Kasuni', 'Danushka']; 11 | var marks = new Array(60,55,66,44,78); 12 | 13 | // Print array 14 | console.log(students); 15 | console.log(students.length); 16 | console.log(students[3]+' got '+marks[3]+' marks for Maths.'); 17 | 18 | // Array mutation 19 | students[3] = 'Sanduni'; 20 | students[5] = 'Thilini'; 21 | students[students.length] = 'Chamara'; 22 | console.log(students); 23 | 24 | // Different data types in an array 25 | var std1 = ['Kamal', 'Perera', 22, 'Civil', 'Panadura', true]; 26 | console.log(std1); 27 | 28 | // Add elements 29 | std1.push('green'); 30 | std1.unshift('Mr.'); 31 | console.log(std1); 32 | 33 | // Remove elements 34 | std1.pop(); 35 | std1.pop(); 36 | std1.shift(); 37 | console.log(std1); 38 | 39 | // Get index of an element 40 | console.log(std1.indexOf(22)); 41 | 42 | var isAgriStudent = std1.indexOf('Agri') === -1 ? std1[0]+' is not a Agri student' : std1[0]+' is a Civil student'; 43 | 44 | console.log(isAgriStudent); 45 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 14 - Challenge 3/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Tip Calculator 7 | 8 | 9 |
10 |

Javascript Language Basics - Tip Calculator

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 14 - Challenge 3/scripts.js: -------------------------------------------------------------------------------- 1 | // ----------------------------- 2 | // --------Tip Calculator------- 3 | // ----------------------------- 4 | 5 | /* 6 | Dasun and his freinds went on a picnic. To get food they went to 3 different restaurants for each meal. The bills are Rs. 1230, Rs. 982, Rs. 1640. 7 | 8 | To tip the waiter a fair amount, Dasun created a simple tip calculator (as a function). He likes to tip 20% of the bill when the bill is less than Rs. 1000, 15% when the bill is between Rs. 1000 and Rs. 1500, and 10% if the bill is more than Rs. 1500. 9 | 10 | In the end, Dasun would like to have 2 arrays: 11 | 1. Containing all 3 tips 12 | 2. Containing all three final paid amounts (bill + tip) 13 | */ 14 | 15 | var tips = new Array(); 16 | var amount = new Array(); 17 | 18 | // Function 19 | function tipCalculator(bill){ 20 | var tip; 21 | if(bill < 1000){ 22 | // Calculate 23 | tip = bill * (20 / 100); 24 | } 25 | else if(bill >= 1000 && bill < 1500){ 26 | // Calculate 27 | tip = bill * (15 / 100); 28 | } 29 | else{ 30 | // Calculate 31 | tip = bill * (10 / 100); 32 | } 33 | 34 | // Store in array 35 | tips.push(tip); 36 | amount.push(bill+tip); 37 | 38 | return tip; 39 | } 40 | 41 | // Calling 42 | console.log('1 - Tip : '+tipCalculator(1230)); 43 | console.log('2 - Tip : '+tipCalculator(982)); 44 | console.log('3 - Tip : '+tipCalculator(1640)); 45 | 46 | // Arrays 47 | console.log(tips); 48 | console.log(amount); 49 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 15 - Objects/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Objects 7 | 8 | 9 |
10 |

Javascript Language Basics - Objects

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 15 - Objects/scripts.js: -------------------------------------------------------------------------------- 1 | // ---------------------- 2 | // --------Objects------- 3 | // ---------------------- 4 | 5 | /* 6 | In Javascript objects are variables that has many values. 7 | Those values written as name:value pairs called properties or methods. 8 | */ 9 | 10 | // --Object Literals-- 11 | // Comma-separated list of name-value pairs wrapped in curly braces. 12 | var nimal = { 13 | firstName: 'Nimal', 14 | lastName: 'Perera', 15 | age: 24, 16 | isMarried: false, 17 | job: 'Developer', 18 | subjects: ['Java Programming', 'Web Development', 'Graphic Design', 'Database Management'], 19 | degree: { 20 | name: 'Software Eng.', 21 | duration: '4 years', 22 | credits: 120 23 | }, 24 | projects: [ 25 | { 26 | name: 'Ecomerce App', 27 | technology: 'Flutter', 28 | version: 1.1 29 | }, 30 | { 31 | name: 'Music Player', 32 | technology: 'Java', 33 | version: 1.2 34 | }, 35 | { 36 | name: 'POS', 37 | technology: 'C#', 38 | version: 2.0 39 | } 40 | ], 41 | yearOfBirth: function(year){ 42 | return year-this.age; 43 | } 44 | } 45 | 46 | // Get values 47 | console.log(nimal); 48 | console.log(nimal.firstName); 49 | console.log(nimal['lastName']); 50 | var x = 'age'; 51 | console.log(nimal[x]); 52 | console.log(nimal.subjects[2]); 53 | console.log(nimal['subjects'][3]); 54 | console.log(nimal.degree.name); 55 | console.log(nimal['degree'].credits); 56 | console.log(nimal.projects[1].technology); 57 | console.log('Year of Birth : '+nimal.yearOfBirth(2021)); 58 | 59 | // Modify values 60 | nimal.job = 'Engineer'; 61 | nimal['isMarried'] = true; 62 | console.log(nimal); 63 | 64 | // --new Object syntax-- 65 | var kasun = new Object(); 66 | // Add Properties 67 | kasun.firstName = 'Kasun'; 68 | kasun.lastName = 'Fernando'; 69 | kasun['age'] = 30; 70 | 71 | console.log(kasun); 72 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 16 - Challenge 4/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - BMI with Objects 7 | 8 | 9 |
10 |

Javascript Language Basics - BMI with Objects

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 16 - Challenge 4/scripts.js: -------------------------------------------------------------------------------- 1 | // ------------------------------- 2 | // --------BMI with Objects------- 3 | // ------------------------------- 4 | 5 | /* 6 | Let's remember the first coding challenge where Kasun and Chamal compared their BMIs. Let's now implement the same functionality with objects and methods. 7 | 1. For each of them, create an object with full name, mass and height. 8 | 2. Then, add a method to each object to calculate the BMI. Save the BMI to the object and also return it from the method. 9 | 3. In the end, display the highest BMI with the full name. Don't forget they might have the same BMI. 10 | 11 | BMI = mass / height ^ 2 12 | */ 13 | 14 | // Declare objects 15 | var kasun = new Object(); 16 | var chamal = new Object(); 17 | 18 | // Add properties to Kasun 19 | kasun.fullName = prompt("Enter Kasun's full name : "); 20 | kasun.mass = prompt("Enter Kasun's mass : "); 21 | kasun.height = prompt("Enter Kasun's height : "); 22 | 23 | // Add properties to Chamal 24 | chamal.fullName = prompt("Enter Chamal,s full name : "); 25 | chamal.mass = prompt("Enter Chamal,s mass : "); 26 | chamal.height = prompt("Enter Chamal,s height : "); 27 | 28 | // Add bmi() method for both 29 | kasun.bmi = chamal.bmi = function(){ 30 | this.bmiVal = this.mass / (this.height**2); 31 | return this.bmiVal; 32 | } 33 | 34 | console.log(kasun); 35 | console.log(chamal); 36 | 37 | // Find the highest BMI 38 | if(kasun.bmi() > chamal.bmi()){ 39 | alert(kasun.fullName+" has the highest BMI "+kasun.bmiVal); 40 | } 41 | else if(kasun.bmi() < chamal.bmi()){ 42 | alert(chamal.fullName+" has the highest BMI "+chamal.bmiVal); 43 | } 44 | else{ 45 | alert("Both BMIs are equal!"); 46 | } 47 | 48 | console.log(kasun); 49 | console.log(chamal); -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 17 - Loops/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Loops 7 | 8 | 9 |
10 |

Javascript Language Basics - Loops

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 17 - Loops/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------- 2 | // --------Loops------- 3 | // -------------------- 4 | 5 | /* 6 | loops are control structure that repeatedly run a block of code until a certain condition get false. 7 | */ 8 | 9 | // --Whithout Loops-- 10 | console.log(1); 11 | console.log(2); 12 | console.log(3); 13 | 14 | // --For Loop-- 15 | for(var i=0; i<10; i++){ // i += 1 => i = i + 1 16 | console.log(i); 17 | } 18 | /* 19 | i = 0, 0 < 10 true, log i to the console, i++ 20 | i = 1, 1 < 10 true, log i to the console, i++ 21 | ... 22 | i = 9, 9 < 10 true, log i to the console, i++ 23 | i = 10, 10 < 10 false, exit the loop 24 | */ 25 | 26 | for(var i=10; i>0; i--){ 27 | console.log(i); 28 | } 29 | 30 | // Iterate an array 31 | var students = ['Namal','Kumara','Dasun','Sachini','John']; 32 | for(var i = 0; i < students.length; i++){ 33 | console.log(students[i]); 34 | } 35 | 36 | // --For/In Loop-- 37 | // The JavaScript for/in statement loops through the properties of an object 38 | var person = {fname:"Chamara", lname:"Silva", age:25}; 39 | var i; 40 | for(i in person){ 41 | console.log(person[i]); 42 | } 43 | 44 | // --For/Of Loop-- 45 | // For/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more. 46 | var fullName = 'Chamara Perera'; 47 | var j; 48 | for(j of fullName){ 49 | console.log(j); 50 | } 51 | 52 | // --While Loop-- 53 | var marks = [33,55,66,88,22]; 54 | var k = 0; 55 | while(k < marks.length){ 56 | console.log(marks[k]); 57 | k++; 58 | } 59 | 60 | // --Do-While Loop-- 61 | var l = 10; 62 | do{ 63 | console.log(l); 64 | l--; 65 | }while(l >= 1); 66 | 67 | // --Continue & Break-- 68 | // The break and the continue statements are the only JavaScript statements that can "jump out of" a code block. 69 | var data = ['Saman','Galle',1996,'Maths',true,'Chocolate']; 70 | 71 | // Continue 72 | // If a specified condition occurs, and continues with the next iteration in the loop. 73 | for(var i = 0; i < data.length; i++){ 74 | if(typeof(data[i]) !== 'string') continue; 75 | console.log(data[i]); 76 | } 77 | 78 | // Break 79 | // Breaks the loop and continues executing the code after the loop (if any) 80 | for(var i = 0; i < data.length; i++){ 81 | if(typeof(data[i]) !== 'string') break; 82 | console.log(data[i]); 83 | } 84 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 18 - Error Handling/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Error Handling 7 | 8 | 9 |
10 |

Javascript Language Basics - Error Handling

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 18 - Error Handling/scripts.js: -------------------------------------------------------------------------------- 1 | // ----------------------------- 2 | // --------Error Handling------- 3 | // ----------------------------- 4 | 5 | // --Try Catch-- 6 | /* 7 | try - Let you test a block of code for errors 8 | catch - Lets you handle the error 9 | throw - lets you create custom errors 10 | finally - lets you execute code, after try and catch, regardless of the result 11 | */ 12 | 13 | // Function to find the largest number 14 | function findLargest(a, b, c){ 15 | try{ 16 | if(typeof(a) !== 'number' || typeof(b) !== 'number' || typeof(c) !== 'number'){ 17 | throw "Error : Enter only numbers!"; 18 | } 19 | else if(a == b || a == c || b == c){ 20 | throw "Error : Enter different numbers!"; 21 | } 22 | else{ 23 | if(a > b && a > c){ 24 | console.log("a is the largest number!"); 25 | } 26 | else if(b > a && b > c){ 27 | console.log("b is the largest number!"); 28 | } 29 | else if(c > a && c > b){ 30 | console.log("c is the largest number!"); 31 | } 32 | else{ 33 | console.log("Invalid inputs!"); 34 | } 35 | } 36 | } 37 | catch(err){ 38 | console.log(err); 39 | } 40 | finally{ 41 | console.log("Input values are "+a+", "+b+" and "+c); 42 | } 43 | } 44 | 45 | // Calling 46 | findLargest(7,7,5); 47 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 19 - Javascript Scope/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Javascript Scope 7 | 8 | 9 |
10 |

Javascript Language Basics - Javascript Scope

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 19 - Javascript Scope/scripts.js: -------------------------------------------------------------------------------- 1 | // ------------------------------- 2 | // --------Javascript Scope------- 3 | // ------------------------------- 4 | 5 | /* 6 | Scope determines the accessibility (visibility) of variables. In JavaScript there are two types of scope. 7 | 1. Local 8 | 2. Global 9 | */ 10 | 11 | // --Local Variables-- 12 | // Variables declared within a JavaScript function, They can only be accessed from within the function. Local variables are deleted when the function is completed. 13 | function addNum(){ 14 | var a = 10; 15 | var b = 20; 16 | console.log(a+b); 17 | } 18 | 19 | // Calling 20 | addNum(); 21 | // console.log(a); 22 | 23 | // --Global Variables-- 24 | // A variable declared outside a function, All scripts and functions on a web page can access it. In a web browser, global variables are deleted when you close the browser window (or tab) 25 | var subject = "Maths"; 26 | function mySub(){ 27 | console.log("My favourite subject is "+subject); 28 | subject = "Science"; 29 | } 30 | 31 | // Calling 32 | mySub(); 33 | mySub(); 34 | console.log(subject); -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 20 - Challenge 5/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Javascript Basics - Tip Calculator with Objects & Loops 7 | 8 | 9 |
10 |

Javascript Language Basics - Tip Calculator with Objects & Loops

11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /1. Javascript Basics/Ex 20 - Challenge 5/scripts.js: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------- 2 | // --------Tip Calculator with Objects & Loops------- 3 | // -------------------------------------------------- 4 | 5 | /* 6 | Remember the tip calculator challenge? Let's create a more advanced versio using Objects and Loops. 7 | 8 | Dasun and his freinds went on a picnic. To get food they went to 5 different restaurants for each meal. The bills are Rs. 1230, Rs. 982, Rs. 1640, Rs. 1460, Rs. 944. 9 | 10 | To tip the waiter a fair amount, Dasun created a simple tip calculator (as a function). He likes to tip 20% of the bill when the bill is less than Rs. 1000, 15% when the bill is between Rs. 1000 and Rs. 1500, and 10% if the bill is more than Rs. 1500. 11 | 12 | Implement a Tip calculator using Objects & Loops: 13 | 1. Create an object with an array for bill values 14 | 2. Add a method to calculate tips 15 | 3. This method should include a loop to iterate over all the paid bills and do the tip calculations 16 | 4. As an output create 2 new arrays inside the object to store all tips and final amounts(bill + tip). 17 | */ 18 | 19 | // Object 20 | var billPay = { 21 | bill: [], 22 | tip: [], 23 | final: [], 24 | calTip: function(){ 25 | for(var i=0; i= 1000){ 31 | tp = 15/100; 32 | } 33 | else{ 34 | tp = 10/100; 35 | } 36 | 37 | // Calculation and add tip to the array 38 | this.tip[i] = this.bill[i] * tp; 39 | // Add final amount to the array 40 | this.final[i] = this.bill[i] + this.tip[i]; 41 | } 42 | } 43 | } 44 | 45 | // Get Inputs 46 | for(var i=0; i<5; i++){ 47 | billPay.bill[i] = parseInt(prompt("Enter bill amount : ")); 48 | } 49 | 50 | // Calling Function 51 | billPay.calTip(); 52 | console.log(billPay); 53 | -------------------------------------------------------------------------------- /2. Javascript Document Object Model (DOM)/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | DOM 7 | 87 | 88 | 89 | 90 | 93 | 94 |
95 |
96 |

Add Items

97 |
98 | 99 | 105 | 106 |
107 |
108 |
109 |
110 |

Shopping Items

111 |
    112 |
  • Item 1
  • 113 |
  • Item 2
  • 114 |
  • Item 3
  • 115 |
  • Item 4
  • 116 |
  • Item 5
  • 117 |
118 |
119 |

testing...

120 |
121 |
122 |
123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 |
131 |

Bubbling:

132 |

Click me!

133 |

134 | 135 |
136 |

Capturing:

137 |

Click me!

138 |

139 | 140 | 141 | 142 |

143 | 144 | 145 |

146 |
147 |

How are you!

148 |
149 |
150 | 151 | 152 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /2. Javascript Document Object Model (DOM)/scripts1.js: -------------------------------------------------------------------------------- 1 | // ------------------------------------------- 2 | // -------Select & Update DOM Elements-------- 3 | // ------------------------------------------- 4 | 5 | // ---Examine the document object--- 6 | console.dir(document); 7 | 8 | // --Get Properties-- 9 | console.log(document.URL); 10 | console.log(document.charset); 11 | console.log(document.lastModified); 12 | console.log(document.title); 13 | console.log(document.doctype); 14 | 15 | console.log(document.head); 16 | console.log(document.body); 17 | 18 | console.log(document.all); 19 | console.log(document.all[11]); 20 | 21 | console.log(document.forms[0]); 22 | console.log(document.links); 23 | console.log(document.images); 24 | 25 | // --Change values-- 26 | document.title = "Document Object Model"; 27 | console.log(document.title); 28 | 29 | // --Not the best way-- 30 | document.all[11].textContent = "Shopping Item List" 31 | console.log(document.all[16]); 32 | 33 | // ----------------------------------- 34 | 35 | // ---Select elements using ID--- 36 | console.log(document.getElementById('hdt')); 37 | var formTitle = document.getElementById('frmt'); 38 | console.log(formTitle); 39 | 40 | // --textContent, innerText & innerHTML-- 41 | formTitle.textContent = 'Add Shopping Items'; 42 | formTitle.innerText = 'Shopping Items'; 43 | formTitle.innerHTML = 'Hello Add Items'; 44 | 45 | /* 46 | 1. The innerText property returns just the text, without spacing and inner element tags. And it cares about styling. 47 | 2. The innerHTML property returns the text, including all spacing and inner element tags. 48 | 3. The textContent property returns the text with spacing, but without inner element tags. 49 | */ 50 | console.log(formTitle.textContent); 51 | console.log(formTitle.innerText); 52 | console.log(formTitle.innerHTML); 53 | 54 | // --Styling-- 55 | var navigation = document.getElementById('navbar'); 56 | navigation.style.backgroundColor = '#090209'; 57 | navigation.style.color = '#fff'; 58 | 59 | // ----------------------------------- 60 | 61 | // ---Select elements using Class name--- 62 | var items = document.getElementsByClassName('items'); 63 | console.log(items); 64 | console.log(items[0]); 65 | items[2].textContent = 'Hand Bag'; 66 | console.log(items[2]); 67 | 68 | // --Styling-- 69 | items[2].style.fontFamily = 'serif'; 70 | items[2].style.backgroundColor = '#ebca14'; 71 | 72 | // --Change back color of all the list items-- 73 | for(var i of items){ 74 | i.style.backgroundColor = '#a7520c'; 75 | } 76 | 77 | // ----------------------------------- 78 | 79 | // ---Select elements using Tag name--- 80 | var li = document.getElementsByTagName('li'); 81 | console.log(li); 82 | console.log(li[0]); 83 | li[2].textContent = 'Book'; 84 | console.log(li[2]); 85 | 86 | // --Styling-- 87 | li[2].style.color = '#fff'; 88 | li[2].style.backgroundColor = '#ebca14'; 89 | 90 | // --Change back color of all the list items-- 91 | for(var i of li){ 92 | i.style.backgroundColor = '#1422eb'; 93 | } 94 | 95 | // ----------------------------------- 96 | 97 | // ---Select elements using Query selector--- 98 | // The querySelector() method returns the first element that matches a specified CSS selector(s) in the document. 99 | 100 | // --ID-- 101 | var hd = document.querySelector('#navbar'); 102 | hd.style.border = 'solid #000 2px'; 103 | 104 | // --Tag-- 105 | var input = document.querySelector('input'); 106 | input.style.backgroundColor = '#ebca14'; 107 | input.value = 'Paint Bucket'; 108 | 109 | // --Class-- 110 | var item = document.querySelector('.items'); 111 | item.style.fontSize = 28+'px'; 112 | 113 | // --Pseudo Classes-- 114 | var item = document.querySelector('.items:nth-child(even)'); 115 | item.style.backgroundColor = '#ebca14'; 116 | 117 | // --Mix Selectors-- 118 | var it = document.querySelector('div .frm #frmt'); 119 | item.style.color = '#eb1478'; 120 | 121 | // ----------------------------------- 122 | 123 | // ---Select elements using Query selector all--- 124 | // The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object. 125 | 126 | // --ID-- 127 | var hd = document.querySelectorAll('#hdt'); 128 | console.log(hd); 129 | 130 | // --Tag-- 131 | var dv = document.querySelectorAll('div'); 132 | console.log(dv); 133 | console.log(dv[1]); 134 | 135 | // --Class-- 136 | var cl = document.querySelectorAll('.items'); 137 | console.log(cl); 138 | 139 | // --Mix Selectors-- 140 | var mx = document.querySelectorAll('div .list li'); 141 | console.log(mx); 142 | 143 | // --Pseudo Classes-- 144 | // Grab all the odd list items 145 | var odd = document.querySelectorAll('li:nth-child(odd)'); 146 | var even = document.querySelectorAll('li:nth-child(even)'); 147 | console.log(odd); 148 | for(var i of odd){ 149 | i.style.backgroundColor = '#ebca14'; 150 | } 151 | 152 | for(var j of even){ 153 | j.style.backgroundColor = '#1422eb'; 154 | } 155 | -------------------------------------------------------------------------------- /2. Javascript Document Object Model (DOM)/scripts2.js: -------------------------------------------------------------------------------- 1 | // --------------------------------- 2 | // -------Traversing the DOM-------- 3 | // --------------------------------- 4 | 5 | var itemList = document.querySelector('#li-items'); 6 | 7 | // ---Parent Node--- 8 | console.log(itemList.parentNode); 9 | itemList.parentNode.style.backgroundColor = '#afafaf'; 10 | console.log(itemList.parentNode.parentNode); 11 | 12 | // ---Parent Element--- 13 | // Most of the time similar to parentNode 14 | console.log(itemList.parentElement); 15 | itemList.parentElement.style.backgroundColor = '#6f6f6f'; 16 | console.log(itemList.parentElement.parentElement); 17 | 18 | // ----------------------------------- 19 | 20 | // ---Child Nodes--- 21 | // text - line breaks 22 | console.log(itemList.childNodes); 23 | 24 | // ---Children--- 25 | console.log(itemList.children); 26 | console.log(itemList.children[2].textContent); 27 | itemList.children[2].style.backgroundColor = '#ebca14'; 28 | 29 | // ----------------------------------- 30 | 31 | // ---First Child--- 32 | // Work like childnodes 33 | console.log(itemList.firstChild); 34 | 35 | // ---First Element Child--- 36 | console.log(itemList.firstElementChild); 37 | itemList.firstElementChild.style.backgroundColor = '#ebca14'; 38 | 39 | // ---Last Child--- 40 | // Work like childnodes 41 | console.log(itemList.lastChild); 42 | 43 | // ---Last Element Child--- 44 | console.log(itemList.lastElementChild); 45 | itemList.lastElementChild.style.backgroundColor = '#ebca14'; 46 | 47 | // ----------------------------------- 48 | 49 | // ---Next Sibling--- 50 | // Work like childnodes 51 | console.log(itemList.nextSibling); 52 | 53 | // ---Next Element Sibling--- 54 | console.log(itemList.nextElementSibling); 55 | itemList.nextElementSibling.style.backgroundColor = '#ebca14'; 56 | 57 | // ---Previous Sibling--- 58 | // Work like childnodes 59 | console.log(itemList.previousSibling); 60 | 61 | // ---Previous Element Sibling--- 62 | console.log(itemList.previousElementSibling); 63 | itemList.previousElementSibling.style.backgroundColor = '#fff'; 64 | 65 | // ----------------------------------- 66 | 67 | // ---Create an Element--- 68 | 69 | // --Create an Input-- 70 | var input = document.createElement('input'); 71 | 72 | // Add a Class 73 | input.className = 'test'; 74 | 75 | // Add an ID 76 | input.id = 'last'; 77 | 78 | // Add an attribute 79 | input.setAttribute('type', 'text'); 80 | console.log(input); 81 | 82 | // --Create a Div-- 83 | var newDiv = document.createElement('div'); 84 | 85 | // Create text node 86 | var newText = document.createTextNode('How are you!'); 87 | 88 | // Add text to div 89 | newDiv.appendChild(newText); 90 | console.log(newDiv); 91 | 92 | // ---Insert created elements to the document--- 93 | var form = document.querySelector('.frm form'); 94 | var button = document.querySelector('.frm form button'); 95 | 96 | input.style.height = '50px'; 97 | 98 | form.insertBefore(input, button); 99 | -------------------------------------------------------------------------------- /2. Javascript Document Object Model (DOM)/scripts3.js: -------------------------------------------------------------------------------- 1 | // --------------------- 2 | // -------Events-------- 3 | // --------------------- 4 | 5 | /* 6 | An HTML event can be something the browser does, or something a user does. 7 | 8 | Here are some examples of HTML events: 9 | 1. An HTML web page has finished loading 10 | 2. An HTML input field was changed 11 | 3. An HTML button was clicked 12 | 13 | Often, when events happen, you may want to do something. 14 | JavaScript lets you execute code when events are detected. 15 | */ 16 | 17 | // ---Using Internal Events--- 18 | // HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. 19 | // 20 | function btnClick(x){ 21 | alert(x); 22 | } 23 | 24 | // ----------------------------------- 25 | 26 | // ---Using Event Listeners--- 27 | /* 28 | The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. 29 | 30 | You can add many event handlers to one element. 31 | 32 | You can add many event handlers of the same type to one element, i.e two "click" events. 33 | 34 | You can add event listeners to any DOM object not only HTML elements. i.e the window object. 35 | 36 | When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup. 37 | 38 | You can easily remove an event listener by using the removeEventListener() method. 39 | */ 40 | 41 | // --Intergrated Function-- 42 | var button1 = document.getElementById('c-btn').addEventListener('click', function(){ 43 | alert("Button clicked!"); 44 | }); 45 | 46 | // ----------------------------------- 47 | 48 | // --Named Function-- 49 | document.getElementById('c-btn').addEventListener('mouseout', txtChange); 50 | 51 | function txtChange(){ 52 | alert("Mouse out!"); 53 | document.getElementById('hdt').textContent = 'Mouse Out!'; 54 | } 55 | 56 | // ----------------------------------- 57 | 58 | // --Parameterized Function-- 59 | document.getElementById('i-btn').addEventListener('click', function(){ 60 | changeListBack("Hellooo"); 61 | }); 62 | 63 | function changeListBack(x){ 64 | document.getElementById('li-items').style.backgroundColor = '#ebca14'; 65 | document.getElementById('li-items').firstElementChild.textContent = x; 66 | } 67 | 68 | // ----------------------------------- 69 | 70 | // --Event Parameter-- 71 | var button2 = document.getElementById('e-btn').addEventListener('click', clickBtn); 72 | function clickBtn(e){ 73 | console.log(e); 74 | console.log(e.target); 75 | console.log(e.target.id); 76 | console.log(e.target.className); 77 | console.log(e.target.classList); 78 | console.log(e.target.type); 79 | console.log(e.type); 80 | 81 | // Output 82 | var output = document.getElementById('output'); 83 | output.innerHTML = '

Class name : '+e.target.classList[0]+'

'; 84 | 85 | // Clicking position 86 | console.log(e.clientX); 87 | console.log(e.clientY); 88 | 89 | console.log(e.offsetX); 90 | console.log(e.offsetY); 91 | 92 | // Check key press 93 | console.log(e.altKey); 94 | console.log(e.ctrlKey); 95 | console.log(e.shiftKey); 96 | } 97 | 98 | // ----------------------------------- 99 | 100 | // --Bubbling & Capturing-- 101 | /* 102 | Event propagation is a way of defining the element order when an event occurs. If you have a

element inside a

element, and the user clicks on the

element, which element's "click" event should be handled first? 103 | 104 | In bubbling the inner most element's event is handled first and then the outer: the

element's click event is handled first, then the

element's click event. 105 | 106 | In capturing the outer most element's event is handled first and then the inner: the
element's click event will be handled first, then the

element's click event. 107 | 108 | The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation. 109 | */ 110 | 111 | // Bubbling 112 | document.getElementById("myP1").addEventListener("click", function () { 113 | alert("You clicked the white element!"); 114 | }, false); 115 | 116 | document.getElementById("myDiv1").addEventListener("click", function () { 117 | alert("You clicked the orange element!"); 118 | }, false); 119 | 120 | // Capturing 121 | document.getElementById("myP2").addEventListener("click", function () { 122 | alert("You clicked the white element!"); 123 | }, true); 124 | 125 | document.getElementById("myDiv2").addEventListener("click", function () { 126 | alert("You clicked the orange element!"); 127 | }, true); 128 | 129 | // ----------------------------------- 130 | 131 | // --Remove event listeners-- 132 | function myFunc(){ 133 | alert("Button has clicked!"); 134 | } 135 | 136 | // Add 137 | document.getElementById('ev-btn').addEventListener('click', myFunc); 138 | 139 | // Remove 140 | document.getElementById('rm-btn').addEventListener('click', function(){ 141 | document.getElementById('ev-btn').removeEventListener('click', myFunc); 142 | console.log("Event has removed!"); 143 | }); 144 | 145 | // ----------------------------------- 146 | 147 | // --Different types of events for mouse-- 148 | 149 | var btn = document.getElementById('t-btn'); 150 | var box = document.getElementById('box'); 151 | 152 | btn.addEventListener('click', typeOfEvent1); 153 | btn.addEventListener('dblclick', typeOfEvent1); 154 | btn.addEventListener('mousedown', typeOfEvent1); 155 | btn.addEventListener('mouseup', typeOfEvent1); 156 | 157 | box.addEventListener('mouseenter', typeOfEvent1); 158 | box.addEventListener('mouseleave', typeOfEvent1); 159 | 160 | box.addEventListener('mouseover', typeOfEvent1); 161 | box.addEventListener('mouseout', typeOfEvent1); 162 | 163 | box.addEventListener('mousemove', typeOfEvent1); 164 | 165 | function typeOfEvent1(e){ 166 | console.log('Event type : '+e.type); 167 | 168 | document.querySelector('#box h2').textContent = 'Mouse X : '+e.offsetX+' | Mouse Y : '+e.offsetY; 169 | 170 | document.body.style.backgroundColor = 'rgb('+e.offsetY+','+e.offsetX+','+e.offsetX+')'; 171 | } 172 | 173 | // ----------------------------------- 174 | 175 | // --Different types of events for keyboard-- 176 | var keyInput = document.querySelector('input[type="text"]'); 177 | 178 | // keyInput.addEventListener('keydown', typeOfEvent2); 179 | // keyInput.addEventListener('keyup', typeOfEvent2); 180 | // keyInput.addEventListener('keypress', typeOfEvent2); 181 | 182 | // keyInput.addEventListener('focus', typeOfEvent2); 183 | // keyInput.addEventListener('blur', typeOfEvent2); 184 | 185 | // keyInput.addEventListener('copy', typeOfEvent2); 186 | // keyInput.addEventListener('cut', typeOfEvent2); 187 | // keyInput.addEventListener('paste', typeOfEvent2); 188 | 189 | keyInput.addEventListener('input', typeOfEvent2); 190 | 191 | function typeOfEvent2(e){ 192 | console.log('Event type : '+e.type); 193 | // console.log('Value : '+e.target.value); 194 | // document.getElementById('out').textContent = e.target.value; 195 | } 196 | 197 | // ----------------------------------- 198 | 199 | // --Other different types of events-- 200 | // Select 201 | var select = document.querySelector('select'); 202 | 203 | // select.addEventListener('change', typeOfEvent3); 204 | select.addEventListener('input', typeOfEvent3); 205 | 206 | function typeOfEvent3(e){ 207 | console.log('Event type : '+e.type); 208 | console.log('Value : '+e.target.value); 209 | } 210 | 211 | // Form 212 | var form = document.querySelector('form'); 213 | 214 | form.addEventListener('submit', typeOfEvent4); 215 | 216 | function typeOfEvent4(e){ 217 | e.preventDefault(); 218 | console.log('Event type : '+e.type); 219 | } --------------------------------------------------------------------------------