BCA 4th Semester Scripting Language Note - Client Side Scripting Javascript
Client Side Scripting
- In web development, 'client side' refers to everything in a web application that is displayed or takes place on the client (end user device).
- This includes what the user sees, such as text, images, and the rest of the UI, along with any actions that an application performs within the user's browser.
- Markup languages like HTML and CSS are interpreted by the browser on the client side.
- Client-side processes are almost always written in JavaScript.
JavaScript
- JavaScript (js) is a light-weight object-oriented programming language which is used by several websites for scripting the webpages.
- It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document.
- It was introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator browser.
- Since then, it has been adopted by all other graphical web browsers.
- With JavaScript, users can build modern web applications to interact directly without reloading the page every time.
- The traditional website uses js to provide several forms of interactivity and simplicity.
Features of JavaScript
- All popular web browsers support JavaScript as they provide built-in execution environments.
- JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming language.
- JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
- JavaScript is an object-oriented programming language that uses prototypes rather than using classes for inheritance.
- It is a light-weighted and interpreted language.
- It is a case-sensitive language.
- JavaScript is supportable in several operating systems including Windows, macOS, etc.
- It provides good control to the users over the web browsers.
Application of JavaScript
- JavaScript is used to create interactive websites. It is mainly used for:
- Client-side validation
- Dynamic drop-down menus
- Displaying date and time
- Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box, and prompt dialog box)
- Displaying clocks, etc.
Implementing JavaScript
- JavaScript provides 3 places to put the JavaScript code:
- Within the body tag
- Within the head tag
- External JavaScript file
- Example:
html
<script type="text/javascript">
document.write("JavaScript is a simple language.");
</script>
- The script tag specifies that we are using JavaScript.
- The `text/javascript` is the content type that provides information to the browser about the data.
- The `document.write()` function is used to display dynamic content through JavaScript.
External JavaScript
- We can create an external JavaScript file and embed it in many HTML pages.
- It provides code reusability because a single JavaScript file can be used in several HTML pages.
- An external JavaScript file must be saved with a `.js` extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the webpage.
- Example: (message.js)
javascript
function msg(){
alert("Hello, welcome to javascript");
}
- Including JavaScript file in `.html` page:
html
<script type="text/javascript" src="message.js"></script>
Advantages of External JavaScript
- It helps in the reusability of code in more than one HTML file.
- It allows easy code readability.
- It is time-efficient as web browsers cache the external JS files, which further reduces the page loading time.
- It enables both web designers and coders to work with HTML and JS files parallelly and separately, i.e., without facing any code conflicts.
- The length of the code reduces as only the location of the JS file needs to be specified.
Disadvantages of External JavaScript
- There are the following disadvantages of external files:
- The stealer may download the coder's code using the URL of the JS file.
- If two JS files are dependent on one another, then a failure in one file may affect the execution of the other dependent file.
- The web browser needs to make an additional HTTP request to get the JS code.
- A tiny to a large change in the JS code may cause unexpected results in all its dependent files.
- We need to check each file that depends on the commonly created external JavaScript file.
- If it is a few lines of code, then it is better to implement the internal JavaScript code.
HTML `<noscript>` Tag
- The `<noscript>` tag defines alternate content to be displayed to users that have disabled scripts in their browser or have a browser that doesn't support script.
- The `<noscript>` element can be used in both `<head>` and `<body>`. When used inside `<head>`, the `<noscript>` element could only contain `<link>`, `<style>`, and `<meta>` elements.
- Example:
html
<script type="text/javascript">
document.write("Hello World!")
</script>
<noscript>Your browser does not support JavaScript!</noscript>
Coding Conventions
- Coding conventions are style guidelines for programming. They typically cover:
- Naming and declaration rules for variables and functions.
- Rules for the use of white space, indentation, and comments.
- Programming practices and principles.
- Conventions:
- Use camelCase for identifier names (variables and functions).
- Global variables written in UPPERCASE (though not always followed).
- Constants (like PI) written in UPPERCASE.
- All names should start with a letter.
- Always put spaces around operators (`=`, `+`, `-`, ``, `/`), and after commas.
- Always use 2 spaces for indentation of code blocks.
- Always end a simple statement with a semicolon.
- General rules for complex (compound) statements:
- Put the opening bracket at the end of the first line.
- Use one space before the opening bracket.
- Put the closing bracket on a new line, without leading spaces.
- Do not end a complex statement with a semicolon.
Comments in JavaScript
- JavaScript comments are a meaningful way to deliver messages to fellow programmers.
- They are used to add information about the code, warnings, or suggestions so that end users can easily interpret the code.
- The JavaScript comment is ignored by the JavaScript engine, i.e., embedded in the browser.
Advantages of JavaScript Comments
- To make code easy to understand: It can be used to elaborate on the code so that end users can easily understand it.
- To avoid unnecessary code: It can also be used to disable code execution. Sometimes, code is added to perform certain actions, but later it may need to be disabled. In such cases, comments are useful.
- There are two types of comments in JavaScript:
- Single-line Comment: `// This is a single-line comment`
- Multi-line Comment:
javascript
/ This is a multi-line comment.
It will not be displayed /
Variables
- A JavaScript variable is simply a name of a storage location.
- There are two types of variables in JavaScript:
- Local variable
- Global variable
- Rules for declaring a JavaScript variable (also known as identifiers):
- Name must start with a letter (a to z or A to Z), underscore (`_`), or dollar (`$`) sign.
- After the first letter, digits (0 to 9) can be used, for example, `value1`.
- JavaScript variables are case-sensitive, e.g., `x` and `X` are different variables.
- Example:
html
<script type="text/javascript">
var x = 10;
var y = 20;
var z = x + y;
document.write(z);
</script>
- There are two types of variables:
- Local Variable
- Global Variable
JavaScript Local Variable
- A JavaScript local variable is declared inside a block or function. It is accessible within the function or block only.
- Example:
html
<script>
function abc(){
var x = 10; // local variable
}
</script>
JavaScript Global Variable
- A JavaScript global variable is accessible from any function. A variable declared outside the function or declared with the `window` object is known as a global variable.
- Example:
html
<script>
var data = 200; // global variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a(); // calling JavaScript function
b();
</script>
JavaScript Functions
- JavaScript functions are used to perform operations. Functions can be called multiple times to reuse code.
Advantages of JavaScript Functions
- Code reusability: A function can be called several times, making it a block of reusable code.
- Less coding: It makes the program compact, as we don’t need to write many lines of code each time to perform a common task.
JavaScript Functions Syntax
javascript
function functionName([arg1, arg2, ...argN]){
// code to be executed
}
- Example:
html
<script>
function msg(){
alert("hello! this is a message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments
- Functions can be called by passing arguments. Function arguments are the values upon which the function performs processing.
- Example:
html
<script>
function getcube(number){
alert(number number number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
JavaScript Function with Return Value
- Functions can return a value that can be used in the program. Return values are generally the result after some processing in the function.
- Example:
html
<script>
function add(num1, num2) {
return num1 + num2;
}
document.writeln(add(2, 5));
</script>
JavaScript Events
- The change in the state of an object is known as an Event.
- In HTML, there are various events representing activities performed by the user or browser.
- JavaScript code reacts to these events and allows execution. This process of reacting to events is called Event Handling. JavaScript handles HTML events via Event Handlers.
- For example, when a user clicks over the browser, JavaScript code will execute the task to be performed on the event.
Mouse Events
| Event Performed | Event Handler | Description |
|-----------------|---------------|-------------|
| click | onclick | When mouse click on an element |
| mouseover | onmouseover | When the cursor of the mouse comes over the element |
| mouseout | onmouseout | When the cursor of the mouse leaves an element |
| mousedown | onmousedown | When the mouse button is pressed over the element |
| mouseup | onmouseup | When the mouse button is released over the element |
| mousemove | onmousemove | When the mouse movement takes place |
Keyboard Events
| Event Performed | Event Handler | Description |
|-----------------|---------------|-------------|
| Keydown & Keyup | onkeydown & onkeyup | When the user presses and then releases the key |
Form Events
| Event Performed | Event Handler | Description |
|-----------------|---------------|-------------|
| focus | onfocus | When the user focuses on an element |
| submit | onsubmit | When the user submits the form |
| blur | onblur | When the focus is away from a form element |
| change | onchange | When the user modifies or changes the value of a form element |
Windows Events
| Event Performed | Event Handler | Description |
|-----------------|---------------|-------------|
| load | onload | When the browser finishes the loading of the page |
| unload | onunload | When the visitor leaves the current webpage, the browser unloads it |
| resize | onresize | When the visitor resizes the browser window |
JavaScript Events Example
html
<html>
<head> JavaScript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent() {
document.write("This is an event");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
JavaScript `addEventListener`
- The `addEventListener()` method is used to attach an event handler to a particular element.
- It does not override the existing event handlers.
- A web page responds according to the event that occurred.
- Events can be user-generated or generated by APIs.
- An event listener is a JavaScript procedure that waits for the occurrence of an event.
- The `addEventListener()` method is an inbuilt function of JavaScript.
- We can add multiple event handlers to a particular element without overwriting the existing event handlers.
Syntax:
javascript
element.addEventListener(event, function, useCapture);
- Although `addEventListener` has three parameters, the parameters `event` and `function` are widely used.
- The third parameter is optional to define.
- `event`: It is a required parameter. It can be defined as a string that specifies the event's name.
- `function`: It is also a required parameter. It is a JavaScript function that responds to the event that occurs.
- `useCapture`: It is an optional parameter.
- It is a Boolean type value that specifies whether the event is executed in the bubbling or capturing phase.
- Its possible values are `true` and `false`.
- When set to `true`, the event handler executes in the capturing phase.
- When set to `false`, the handler executes in the bubbling phase. Its default value is `false`.
JavaScript `addEventListener` Example
html
<html>
<body>
<p> Example of the addEventListener() method. </p>
<p> Click the following button to see the effect. </p>
<button id="btn"> Click me </button>
<p id="para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome to javaTpoint.com";
}
</script>
</body>
</html>
JavaScript Operators
- Operators are symbols used to perform operations on operands.
- There are the following types of operators in JavaScript:
- Arithmetic Operators (`+`, `-`, ``, `/`, `%`, `++`, `--`)
- Comparison (Relational) Operators (`==`, `!=`, `>`, `<`, `>=`, `<=`)
- Bitwise Operators (`&`, `|`, `~`, `^`, `<<`, `>>`)
- Logical Operators (`&&`, `||`, `!`)
- Assignment Operators (`=`, `+=`, `-=`, `=`, `%=` , `/=`)
JavaScript Control Structures
- Normally, JavaScript is executed top-down. However, sometimes we need to repeat or select which statement(s) to execute based on conditions.
- The JavaScript `if-else` statement is used to execute code based on whether a condition is true or false. There are three forms of `if` statements in JavaScript:
- If Statement
- If-Else Statement
- If-Else-If Statement
JavaScript If Condition
javascript
if(expression) {
// content to be evaluated
}
JavaScript If-Else Condition
javascript
if(expression) {
// content to be evaluated if condition is true
} else {
// content to be evaluated if condition is false
}
JavaScript If-Else-If Condition
javascript
if(expression1) {
// content to be evaluated if expression1 is true
} else if(expression2) {
// content to be evaluated if expression2 is true
} else if(expression3) {
// content to be evaluated if expression3 is true
} else {
// content to be evaluated if no expression is true
}
---
Scripting Language
Semester: BCA II/IV
Teacher: Neelu Malakar
Contact No: 9851053192
---
Client Side Scripting
JavaScript `addEventListener`
- The `addEventListener()` method is used to attach an event handler to a particular element.
- It does not override the existing event handlers.
- A web page responds according to the event that occurred.
- Events can be user-generated or generated by APIs.
- An event listener is a JavaScript procedure that waits for the occurrence of an event.
- The `addEventListener()` method is an inbuilt function of JavaScript.
- We can add multiple event handlers to a particular element without overwriting the existing event handlers.
Syntax:
javascript
element.addEventListener(event, function, useCapture);
- Although `addEventListener` has three parameters, the parameters `event` and `function` are widely used.
- The third parameter is optional to define.
- event: It is a required parameter. It can be defined as a string that specifies the event's name.
- function: It is also a required parameter. It is a JavaScript function that responds to the event that occurs.
- useCapture: It is an optional parameter.
- It is a Boolean type value that specifies whether the event is executed in the bubbling or capturing phase.
- Its possible values are `true` and `false`.
- When set to `true`, the event handler executes in the capturing phase.
- When set to `false`, the handler executes in the bubbling phase. Its default value is `false`.
JavaScript `addEventListener` Example
html
<html>
<body>
<p> Example of the addEventListener() method. </p>
<p> Click the following button to see the effect. </p>
<button id="btn"> Click me </button>
<p id="para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome to javaTpoint.com";
}
</script>
</body>
</html>
JavaScript Displaying Messages
- JavaScript can display data in different ways:
- Writing into the HTML output using `document.write()`.
- Prints the given message in the document.
- It is generally used to generate dynamic content but using `document.write()` after an HTML document is loaded will delete all existing HTML.
- Due to this reason, the `document.write()` method should only be used for testing or during the learning or debugging process.
- Using `innerHTML`
- The `innerHTML` property defines the HTML content of an element.
- To access an HTML element, JavaScript can use the `document.getElementById(id)` method.
- The `id` attribute defines the HTML element.
- JavaScript Popup Boxes
- Alert box: An alert box is often used to inform the user with a message.
- When an alert box pops up, the user will have to click "OK" to proceed.
- Confirm Box: A confirm box is often used if you want the user to verify or accept something.
- When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
- If the user clicks "OK", the box returns `true`. If the user clicks "Cancel", the box returns `false`.
- Prompt Box: A prompt box is often used if you want the user to input a value before proceeding.
- When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
- If the user clicks "OK", the box returns the input value. If the user clicks "Cancel", the box returns `null`.
- To display line breaks inside a popup box, use a back-slash followed by the character `n`.
- `console.log()`: For debugging purposes, we can call the `console.log()` method in the browser to display data.
- To access the console, right-click on the browser and select "Inspect".
- On Windows, we can press `Ctrl + Shift + J`.
JavaScript Operators
- Operators are symbols used to perform operations on operands.
- There are the following types of operators in JavaScript:
- Arithmetic Operators: (`+`, `-`, ``, `/`, `%`, `++`, `--`)
- Comparison (Relational) Operators: (`==`, `!=`, `>`, `<`, `>=`, `<=`)
- Bitwise Operators: (`&`, `|`, `~`, `^`, `<<`, `>>`)
- Logical Operators: (`&&`, `||`, `!`)
- Assignment Operators: (`=`, `+=`, `-=`, `=`, `%=` , `/=`)
JavaScript Control Structures
- Normally, JavaScript is executed top-down. However, sometimes we need to repeat or select which statement(s) to execute based on conditions.
- The JavaScript `if-else` statement is used to execute code based on whether a condition is true or false. There are three forms of `if` statements in JavaScript:
- If Statement
- If-Else Statement
- If-Else-If Statement
- JavaScript `if` Condition
javascript
if(expression) {
// content to be evaluated
}
- JavaScript `if…else` Condition
javascript
if(expression) {
// content to be evaluated if condition is true
} else {
// content to be evaluated if condition is false
}
- JavaScript `if…else if` Condition
javascript
if(expression1) {
// content to be evaluated if expression1 is true
} else if(expression2) {
// content to be evaluated if expression2 is true
} else if(expression3) {
// content to be evaluated if expression3 is true
} else {
// content to be evaluated if no expression is true
}
JavaScript Explicit Data Conversion
- Converting Strings to Numbers
- The global method `Number()` converts a variable (or a value) into a number.
- Example: `Number("2224") => 2224`; `Number("") => 0`; `Number("ram") => NaN` (Not a Number)
- Besides `Number()`, `parseInt()` and `parseFloat()` can be used to convert the string to integer or float type data.
- Example: `parseInt("22") => 22`; `parseInt("33.5") => 33`; `parseFloat("22.34") => 22.34`
- Converting Numbers to Strings
- `String()` can convert numbers to strings.
- The `Number` method `toString()` does the same.
- Example: `String(232)`; `232.toString()`; will convert number to string.
JavaScript Exercises
- Write a JavaScript program to read two numbers and display the respective result when clicking on sum, difference, and product buttons.
- Write a JavaScript program to read two numbers and display the larger number.
- Write a JavaScript program to read a number and display whether it is odd or even.
- Write a JavaScript program to read the length and breadth of a room and calculate the area. Display the following message depending upon the area:
- “Auditorium” if `area > 2500`
- “Hall” if `500 < area <= 2500`
- “Big room” if `150 < area <= 500`
- “Small room” if `area <= 150`
Scripting Language
Semester: BCA II/IV
Teacher: Neelu Malakar
Contact No: 9851053192
---
Client Side Scripting
JavaScript Switch Statement
- The JavaScript `switch` statement is used to execute one block of code from multiple expressions.
- It is similar to the `if-else-if` statement but is more convenient when dealing with multiple values for a single variable.
- It can be used with numbers, characters, etc.
Syntax:
javascript
switch(expression) {
case value1:
// code to be executed;
break;
case value2:
// code to be executed;
break;
// more cases...
default:
// code to be executed if no cases match;
}
JavaScript Switch Statement Example
html
<script type="text/javascript">
var grade = 'B';
var result;
switch(grade) {
case 'A':
result = "A Grade";
break;
case 'B':
result = "B Grade";
break;
case 'C':
result = "C Grade";
break;
default:
result = "Fail";
}
document.write(result);
</script>
JavaScript Loops
- JavaScript loops are used to iterate through a block of code multiple times. They help to make the code compact and are commonly used with arrays.
- There are four types of loops in JavaScript:
- for loop
- while loop
- do-while loop
- for-in loop
JavaScript For Loop
- The `for` loop is used when the number of iterations is known beforehand.
Syntax:
javascript
for (initialization; condition; increment) {
// code to be executed
}
Example:
html
<script>
for (i = 1; i <= 5; i++) {
document.write(i + "<br/>");
}
</script>
JavaScript While Loop
- The `while` loop is used when the number of iterations is not known and may potentially run indefinitely.
Syntax:
javascript
while (condition) {
// code to be executed
}
Example:
html
<script>
var i = 11;
while (i <= 15) {
document.write(i + "<br/>");
i++;
}
</script>
JavaScript Do While Loop
- The `do-while` loop is similar to the `while` loop but guarantees that the code block will be executed at least once, regardless of the condition.
Syntax:
javascript
do {
// code to be executed
} while (condition);
Example:
html
<script>
var i = 21;
do {
document.write(i + "<br/>");
i++;
} while (i <= 25);
</script>
Exercise
- Sort Three Numbers: Write a JavaScript conditional statement to sort three numbers and display the results in an alert box.
- Find Largest of Five Numbers: Write a JavaScript conditional statement to find the largest of five numbers and display the result in an alert box.
- Odd or Even Numbers: Write a JavaScript `for` loop that iterates from 0 to 15. For each iteration, check if the current number is odd or even and display a message on the screen.
- Sum of Multiples: Write a JavaScript program to sum multiples of 3 and 5 that are under 1000.
Scripting Language
Semester: BCA II/IV
Teacher: Neelu Malakar
Contact No: 9851053192
---
Client Side Scripting
JavaScript Array
- A JavaScript array is an object used to store a collection of similar types of elements.
- There are three ways to construct an array in JavaScript:
- By using array literal
- By creating an instance of `Array` directly (using the `new` keyword)
- By using an `Array` constructor (using the `new` keyword)
JavaScript Array Literal
- Syntax:
javascript
var arrayName = [value1, value2, ..., valueN];
- Example:
javascript
var emp = ["Rita", "Sita", "Gita"];
JavaScript Array Directly (Using `new` Keyword)
- Syntax:
javascript
var arrayName = new Array();
- Example:
javascript
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "Mohan";
for (i = 0; i < emp.length; i++) {
document.write(emp[i] + "<br>");
}
JavaScript Array Constructor (Using `new` Keyword)
- Syntax:
javascript
var arrayName = new Array(value1, value2, ..., valueN);
- Example:
html
<script>
var emp = new Array("Ram", "Shyam", "Hari");
for (i = 0; i < emp.length; i++) {
document.write(emp[i] + "<br>");
}
</script>
JavaScript Array Methods
- concat(): Combines two or more arrays and returns a new array. The original arrays remain unchanged.
javascript
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var combinedArray = array1.concat(array2);
- reverse(): Reverses the order of the elements in an array and modifies the original array.
javascript
var array = [1, 2, 3];
array.reverse();
- sort(): Sorts the elements of an array as strings in alphabetical and ascending order. It modifies the original array.
javascript
var array = [3, 1, 2];
array.sort();
JavaScript Array Methods (Continued)
- push(): Adds new items to the end of an array and returns the new length.
javascript
var array = [1, 2];
array.push(3);
- pop(): Removes the last element of an array and returns it. Modifies the original array.
javascript
var array = [1, 2, 3];
var lastElement = array.pop();
- shift(): Removes the first item of an array and returns it. Modifies the original array.
javascript
var array = [1, 2, 3];
var firstElement = array.shift();
JavaScript Array Exercises
- Display Array Elements: Write a JavaScript program to read elements in an array and display them.
- Sort Array Items: Write a JavaScript program to sort the items of an array.
- Find Most Frequent Item: Write a JavaScript program to find the most frequent item in an array.
- Remove Duplicate Items: Write a JavaScript program to remove duplicate items from an array.
- Find Duplicate Values: Write a JavaScript program to find duplicate values in a JavaScript array.
Scripting Language
Semester: BCA II/IV
Teacher: Neelu Malakar
Contact No: 9851053192
---
Client Side Scripting
HTML Document Object Model (DOM)
- The `document` object represents the whole HTML document.
- When an HTML document is loaded in the browser, it becomes a `document` object.
- It is the root element that represents the HTML document and has properties and methods.
- The `document` object can be used to add dynamic content to the web page.
- It is a part of the `window` object, so `window.document` and `document` are synonymous.
- It is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
The DOM Programming Interface
- The HTML DOM can be accessed with JavaScript.
- In the DOM, all HTML elements are defined as objects.
- The programming interface consists of the properties and methods of these objects.
- DOM methods are actions that can be performed on HTML elements.
- DOM properties are values of HTML elements that can be set or changed at any time.
HTML DOM Document Object
- The `document` object represents a web page.
- To access any element in an HTML page, the `document` object should be accessed first.
- To access other elements in the document, you can assign an `id` or a `name` to each element using respective parameters within HTML tags.
Methods of Document Object
| Method | Description |
|------------------------|--------------------------------------------------------------------|
| `write("string")` | Writes the given string to the document. |
| `writeln("string")` | Writes the given string to the document with a newline character. |
| `getElementById(id)` | Returns the element with the given id value. |
| `getElementsByName(name)` | Returns all elements with the given name value. |
| `getElementsByTagName(tagName)` | Returns all elements with the given tag name. |
| `getElementsByClassName(className)` | Returns all elements with the given class name. |
Finding HTML Elements
- By ID:
javascript
const obj = document.getElementById("id1");
- By Tag Name:
javascript
const pgs = document.getElementsByTagName("p");
- By Class Name:
javascript
const x = document.getElementsByClassName("tds");
- By CSS Selectors:
javascript
const x = document.querySelectorAll("p.bluep");
Gets all paragraphs with the class `bluep`.
- By HTML Object Collections:
javascript
const x = document.forms["frm1"];
Gets the form named `frm1` with all its elements.
HTML DOM Image Object
- The `Image` object represents an HTML `<img>` element.
- Access the `<img>` element by using `getElementById()`:
html
<img id="img1" src="myimage.jpg">
javascript
var img1 = document.getElementById("img1");
- Image Object Properties:
- `height`
- `width`
- `src`
- `naturalHeight`
- `naturalWidth`
Exercises
1. Write a JavaScript program to change the content (text) of a paragraph on mouseover and mouseout events.
2. Write a JavaScript program to toggle the `innerHTML` of a paragraph when you click on it.
3. Write a JavaScript program to swap the image `src` on mouseover and mouseout events.
4. Write a JavaScript program to swap the image height and width when you click on the buttons “50%”, “25%”, “75%”, “100%” or fixed given size. Allow the user to specify if they want to change height and width relatively or fix them as per the given value if not checked in the Relative option.
HTML Changing CSS
- The HTML DOM allows JavaScript to change the style of HTML elements.
- To change the style of an HTML element, use the following syntax:
javascript
document.getElementById(id).style.property = newStyle;
- Example:
html
<html>
<head>
<script>
function changeToBlue() {
document.getElementById("p2").style.color = "blue";
}
</script>
</head>
<body>
<p id="p2" onclick="changeToBlue()">This is a paragraph.</p>
</body>
</html>
CSS Properties Used in JavaScript
| JavaScript Property | CSS Property |
|-----------------------|------------------------|
| `fontWeight` | `font-weight` |
| `fontVariant` | `font-variant` |
| `fontSize` | `font-size` |
| `fontFamily` | `font-family` |
| `marginTop` | `margin-top` |
| `marginRight` | `margin-right` |
| `marginLeft` | `margin-left` |
| `marginBottom` | `margin-bottom` |
| `margin` | `margin` |
| `color` | `color` |
| `backgroundColor` | `background-color` |
| `borderTop` | `border-top` |
| `borderRight` | `border-right` |
| `borderLeft` | `border-left` |
| `borderColor` | `border-color` |
| `borderBottom` | `border-bottom` |
| `display` | `display` |
| `visibility` | `visibility` |
Exercises
1. Write a JavaScript program to change the background color of the document body when the user selects from a dropdown list.
2. Write a JavaScript program to show or hide a `<div>` when the user clicks on a button.
3. Write a JavaScript program to change the border style of an image on mouseover.
Some Exercise with Solutions
1. What is a Scripting Language? Differentiate between Scripting Language and Programming Language.
A scripting language is a type of programming language that is used to automate tasks within another software environment, such as a web browser or a server. Unlike traditional programming languages, scripting languages are typically interpreted rather than compiled. They are often used for small-scale tasks like automating repetitive processes, adding dynamic content to web pages, or interacting with databases in web applications.
| Aspect | Scripting Language | Programming Language |
|-------------------------|---------------------------------------------|---------------------------------------------|
| Compilation | Interpreted (run line by line) | Can be compiled or interpreted |
| Primary Usage | Used for automating tasks, usually within another application (e.g., browsers or servers) | Used for building full applications |
| Complexity | Easier to learn and often dynamically typed | Can be more complex and statically typed |
| Performance | Slower due to interpretation | Typically faster as compiled languages |
| Examples | JavaScript, Python (in some contexts), PHP | C++, Java, Python (compiled), C |
---
2. Describe How a Web Application Works
A web application typically follows a client-server model:
1. Client Request: The user interacts with the web browser and sends a request (HTTP/HTTPS) to the web server. This request could be for viewing a page, submitting a form, or retrieving data.
2. Web Server: The web server (e.g., Apache, Nginx) processes the incoming request. Depending on the request, it might fetch data from the database, execute server-side scripts (like PHP or Node.js), or retrieve static files (HTML, CSS, JavaScript).
3. Database Interaction (if required): If the web application requires data (e.g., retrieving user information), the server interacts with a database (like MySQL, MongoDB).
4. Server Response: Once the request is processed, the server responds with an appropriate output, usually in the form of HTML, CSS, and JavaScript. This response could be a new web page or data in JSON format (for single-page applications).
5. Rendering by Browser: The web browser receives the response and renders the HTML page, applying the CSS for styling and executing the JavaScript for dynamic behavior.
---
3. Why Do We Need Scripting Language? Describe and Differentiate Between Different Types of Scripting Languages.
Need for Scripting Languages: Scripting languages are essential for making websites and applications dynamic and interactive. They help automate tasks, manipulate content dynamically, manage user inputs, and reduce repetitive tasks, improving development speed.
| Type | Description | Examples |
|--------------------------|--------------------------------------------|------------------------------------------|
| Client-side Scripting | Runs in the user’s browser, responsible for enhancing the user experience without server interaction. | JavaScript, TypeScript |
| Server-side Scripting | Runs on the server, manages the backend, database interactions, and dynamic content generation. | PHP, Python (Django, Flask), Node.js |
| Shell Scripting | Used to automate tasks in an operating system (Linux, Unix). | Bash, PowerShell, Perl |
| Game Scripting | Scripts used to control behavior in video games. | Lua, Python (for scripting game logic) |
---
4. JavaScript: Features and Limitations
JavaScript is the most widely-used client-side scripting language that runs in the browser, allowing developers to create interactive and dynamic web pages.
Key Features:
- Lightweight: JavaScript is a lightweight, interpreted language.
- Cross-platform: Runs on all major browsers and platforms without requiring special plugins.
- Client-side Execution: Executes in the browser, reducing the load on the server.
- Dynamic Typing: Variables in JavaScript can change types dynamically, making it flexible.
- Asynchronous Programming: Supports asynchronous operations using promises, callbacks, and `async/await`.
- DOM Manipulation: Can directly manipulate the Document Object Model (DOM) of a web page to dynamically change the content and structure.
- Event Handling: Responds to user input, like clicks and key presses, in real-time.
Limitations:
- No Native Multithreading: JavaScript doesn’t have built-in support for multithreading (although Web Workers provide limited support).
- Browser Differences: Different browsers may implement JavaScript engines differently, leading to compatibility issues.
- Security Risks: JavaScript can introduce security vulnerabilities (like cross-site scripting) if not handled carefully.
- Limited Server-side Features: On its own, JavaScript is not well-suited for heavy server-side tasks (though Node.js addresses this limitation).
---
5. Variable in JavaScript: var vs let
In JavaScript, a variable is a container that holds data values. Variables can be declared using `var`, `let`, or `const`.
| Aspect | var | let |
|--------------------------|-------------------------------------------|-------------------------------------------|
| Scope | Function-scoped (accessible within the function they are declared in) | Block-scoped (accessible within the nearest set of curly braces `{}`) |
| Re-declaration | Can be re-declared in the same scope | Cannot be re-declared in the same scope |
| Hoisting | Hoisted to the top with the value `undefined` | Hoisted but not initialized |
| Use Case | Used in older JavaScript code (ES5 and earlier) | Preferred for modern JavaScript code due to block-scoping |
Example:
function example() {
var x = 10;
let y = 20;
if (true) {
var x = 30; // Affects the outer x
let y = 40; // Only exists within this block
}
console.log(x); // 30
console.log(y); // 20
}
`
---
6. Embedding JavaScript in HTML
There are three main ways to embed JavaScript in HTML:
1. Internal Script: Embed JavaScript directly within an HTML file, inside `<script>` tags.
`html
<script>
console.log("This is an internal script");
</script>
`
2. External Script: Place JavaScript in a separate `.js` file and link it using the `<script src="filename.js"></script>` tag. This method is useful for separating JavaScript logic from the HTML structure.
`html
<script src="script.js"></script>
`
3. Inline Script: Embed JavaScript directly into an HTML element’s attributes (e.g., using `onclick`, `onload`, etc.).
`html
<button onclick="alert('Button clicked!')">Click Me</button>
`
---
7. JavaScript Loops, continue, and break
Loops allow you to execute a block of code multiple times based on a condition.
1. for loop: Repeats a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
`
2. while loop: Repeats a block of code as long as a specified condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
`
3. do...while loop: Similar to a `while` loop, but it guarantees that the code block will run at least once.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
`
4. for...in loop: Iterates over the properties of an object.
let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key, obj[key]);
}
`
5. for...of loop: Iterates over the values of an iterable (like arrays or strings).
let arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
`
break: Exits the loop entirely.
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Loop stops when i is 5
console.log(i);
}
`
continue: Skips the current iteration and moves to the next iteration of the loop.
for (let i = 0; i < 10; i++) {
if (i === 5) continue; // Skips the rest of the code for i === 5
console.log(i);
}
`
---
8. Data Types in JavaScript and Operators
JavaScript supports a variety of data types. These are divided into two categories: primitive and reference types.
Primitive Data Types:
- String: Represents text (e.g., `"hello"`).
- Number: Represents numbers (both
integers and floating-point values).
- Boolean: Represents true or false values.
- Undefined: A variable that has been declared but not assigned a value.
- Null: Represents the intentional absence of any object value.
- Symbol: A unique and immutable value, often used as object property keys.
- BigInt: Used for representing large integers that are beyond the safe range of the `Number` type.
Reference Data Types:
- Object: Used to store collections of data and more complex entities (e.g., arrays, functions, objects).
Operators:
- Arithmetic Operators: `+`, `-`, , `/`, `%` (modulus).
- Comparison Operators: `==`, `===`, `!=`, `!==`, `>`, `<`, `>=`, `<=`.
- Logical Operators: `&&` (AND), `||` (OR), `!` (NOT).
- Assignment Operators: `=`, `+=`, `-=`, `=`, `/=`.
- Bitwise Operators: `&`, `|`, `^`, `~`, `<<`, `>>`, `>>>`.
---
9. What is a Loop? Describe the Different Types of Loops in JavaScript
A loop in programming is a control flow structure that allows you to repeat a block of code multiple times. JavaScript supports several types of loops:
1. for Loop: Runs a block of code a specific number of times.
for (let i = 0; i < 10; i++) {
console.log(i);
}
`
2. while Loop: Executes a block of code as long as a condition is true.
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
`
3. do...while Loop: Similar to the `while` loop, but the condition is checked after the loop’s body, ensuring it runs at least once.
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
`
4. for...in Loop: Iterates over the properties of an object.
let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key, obj[key]);
}
`
5. for...of Loop: Iterates over iterable objects like arrays or strings.
let arr = [1, 2, 3];
for (let value of arr) {
console.log(value);
}
`
---
10. Array Creation and Traversal in JavaScript
An array in JavaScript is a special type of object that allows you to store multiple values in a single variable.
Creating an Array:
let arr = [1, 2, 3, 4, 5];
`
Accessing Elements:
console.log(arr[0]); // 1
console.log(arr[2]); // 3
`
Traversing an Array:
- Using a for loop:
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
`
- Using forEach method:
arr.forEach(function(value) {
console.log(value);
});
`
- Using for...of loop:
for (let value of arr) {
console.log(value);
}
`
Array Methods:
- `push()`: Adds an element to the end of the array.
- `pop()`: Removes the last element from the array.
- `shift()`: Removes the first element from the array.
- `unshift()`: Adds an element to the beginning of the array.
- `map()`: Creates a new array by applying a function to each element.
- `filter()`: Creates a new array with all elements that pass a test.
- `reduce()`: Reduces the array to a single value.
---
11. What Are Conditional Statements? Different Conditional Statements in JavaScript
Conditional statements are used to perform different actions based on different conditions.
1. if statement: Executes a block of code if a specified condition is true.
if (x > 10) {
console.log("x is greater than 10");
}
`
2. if...else statement: Executes one block of code if the condition is true, and another block if it is false.
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is less than or equal to 10");
}
`
3. else if statement: Specifies a new condition if the first condition is false.
if (x > 10) {
console.log("x is greater than 10");
} else if (x === 10) {
console.log("x is equal to 10");
} else {
console.log("x is less than 10");
}
`
4. switch statement: Allows you to test a variable against multiple values.
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
}
`
---
12. What Are Functions? Explain the Different Ways to Create a Function in JavaScript
A function is a block of reusable code designed to perform a particular task. Functions allow you to structure and modularize code, making it easier to debug, maintain, and reuse.
Ways to Create a Function in JavaScript:
1. Function Declaration: Defines a function using the `function` keyword.
function greet() {
return "Hello, world!";
}
`
2. Function Expression: Assigns a function to a variable.
const greet = function() {
return "Hello, world!";
};
`
3. Arrow Function: A shorter syntax for writing function expressions (introduced in ES6).
const greet = () => "Hello, world!";
`
Example Usage:
function add(a, b) {
return a + b;
}
const result = add(2, 3);
console.log(result); // 5
`
---
13. Recursive Function and Arrow Functions in JavaScript
- Recursive Function: A function that calls itself to solve smaller instances of the same problem. This is useful for tasks like calculating factorials, traversing tree structures, etc.
Example:
function factorial(n) {
if (n === 0) return 1;
return n factorial(n - 1);
}
`
- Arrow Function: Arrow functions are a more concise way to write function expressions. They also handle the `this` context differently than traditional functions, which is useful in situations like object methods or callbacks.
Example:
const greet = () => "Hello, world!";
`
Significance:
- Shorter Syntax: Arrow functions reduce the amount of code needed.
- No Binding of `this`: In regular functions, `this` refers to the object that called the function. In arrow functions, `this` is lexically bound, meaning it refers to the enclosing context.
---
14. What is a Higher-Order Function? Explain Different Types of Higher-Order Functions You Are Familiar With
A higher-order function is a function that either takes one or more functions as arguments or returns a function as a result. These are powerful tools in functional programming, allowing for abstract operations like `map`, `filter`, and `reduce`.
1. map(): Creates a new array by applying a function to every element in the original array.
let numbers = [1, 2, 3];
let doubled = numbers.map(n => n 2); // [2, 4, 6]
`
2. filter(): Creates a new array with all elements that pass a test (provided by a function).
let numbers = [1, 2, 3, 4, 5];
let even = numbers.filter(n => n % 2 === 0); // [2, 4]
`
3. reduce(): Reduces the array to a single value, based on the logic provided in a function.
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((total, n) => total + n, 0); // 10
`
---
15. What is a forEach Loop? Example
`forEach` is an array method that executes a provided function once for each array element.
Example:
let numbers = [1, 2, 3];
numbers.forEach((number) => {
console.log(number); // Logs 1, 2, and 3
});
`
Unlike `map()`, `
forEach()` doesn’t return a new array; it is primarily used for executing side effects like logging or manipulating DOM elements.
---
16. Properties and Methods of JavaScript Objects
JavaScript has various built-in objects with their own properties and methods. Below are the key properties and methods for some of them:
| Object | Properties | Methods |
|----------------|-----------------------------------------|-------------------------------------------|
| Array | `length` | `push()`, `pop()`, `shift()`, `unshift()`, `map()`, `filter()`, `reduce()` |
| Boolean | `constructor`, `toString()` | `valueOf()`, `toString()` |
| String | `length` | `charAt()`, `indexOf()`, `slice()`, `toUpperCase()`, `toLowerCase()` |
| Math | `PI`, `E` | `round()`, `sqrt()`, `random()`, `floor()`, `ceil()` |
| Window | `innerWidth`, `innerHeight` | `alert()`, `confirm()`, `prompt()`, `open()`, `close()` |
| Location | `href`, `protocol`, `hostname` | `reload()`, `assign()`, `replace()` |
| Screen | `width`, `height`, `availWidth` | N/A |
| History | `length` | `back()`, `forward()`, `go()` |
| Navigator | `appName`, `userAgent`, `platform` | `javaEnabled()`, `online` |
| RegExp | `source`, `flags` | `test()`, `exec()` |
| Number | `MAX_VALUE`, `MIN_VALUE` | `toFixed()`, `toString()`, `toExponential()` |
---
17. What is DOM? Explain its Properties and Methods
The DOM (Document Object Model) is a programming interface for web documents. It represents the structure of a webpage as a tree of objects, allowing JavaScript to manipulate the content, structure, and style of the page dynamically.
Properties:
- `document.body`: Represents the body of the document.
- `document.title`: Represents the title of the document.
- `document.URL`: The URL of the document.
Methods:
- `getElementById()`: Returns an element by its ID.
- `getElementsByClassName()`: Returns all elements with the specified class name.
- `createElement()`: Creates a new HTML element.
- `appendChild()`: Adds a new child element to an existing element.
---
18. Differentiate Between Event and Event Handler
| Aspect | Event | Event Handler |
|-------------------|-----------------------------------------------|-------------------------------------------------|
| Definition | An event is an action or occurrence detected by the browser (e.g., click, mouse hover, keypress). | A function or block of code that runs in response to an event. |
| Example | `click`, `keydown`, `load`, `mouseover` | `element.onclick = function() { ... };` |
| Purpose | To indicate that something has occurred in the browser. | To specify the response when the event occurs. |
---
19. What are Regular Expressions? Quantifiers and Meta Characters
Regular Expressions (RegExp) are patterns used to match character combinations in strings. They are used for searching, matching, and replacing patterns in text.
Quantifiers:
- (0 or more times)
- `+` (1 or more times)
- `?` (0 or 1 time)
- `{n}` (exactly n times)
- `{n,}` (n or more times)
- `{n,m}` (between n and m times)
Meta Characters:
- `.`: Matches any single character except newline.
- `^`: Matches the start of a string.
- `$`: Matches the end of a string.
- `\d`: Matches any digit.
- `\w`: Matches any word character (letters, digits, and underscore).
Example:
let regex = /\d+/; // Matches one or more digits
let str = "Age: 25";
let result = str.match(regex); // ["25"]
`
---
20. Client-Side Validation Using JavaScript
Client-side validation checks user input in the browser before sending it to the server, improving performance and user experience.
Example:
`html
<form onsubmit="return validateForm()">
<input type="text" id="username" />
<input type="submit" value="Submit" />
</form>
<script>
function validateForm() {
let username = document.getElementById("username").value;
if (username === "") {
alert("Username must be filled out");
return false;
}
return true;
}
</script>
`
---
21. Accessing HTML Objects Using JavaScript
You can access HTML elements (also known as DOM objects) using various methods in JavaScript.
Example:
`html
<p id="myParagraph">Hello, World!</p>
<script>
let paragraph = document.getElementById("myParagraph");
paragraph.textContent = "Hello, JavaScript!";
</script>
`
You can also use:
- `document.querySelector()` for selecting elements using CSS selectors.
- `document.getElementsByClassName()` for selecting elements by class name.
- `document.getElementsByTagName()` for selecting elements by tag name.
These methods provide a way to interact and manipulate HTML elements dynamically.
0 Comments