Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

my css notes

Uploaded by

mejariarpit16
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

my css notes

Uploaded by

mejariarpit16
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

4 Mr question

1. Explain getter and setter properties in java script with suitable exam
Explain Getter and Setter Properties in JavaScript

In JavaScript, getter and setter properties are special methods that provide controlled access to an object's
properties. These methods allow encapsulation, enabling code to hide how values are internally stored and
retrieved.

Getter Property

Description: A getter method retrieves or "gets" the value of a property. It's defined using the get keyword
within an object or a class.
Use Case: Getters are used to access property values in a controlled way, especially when additional
computation or processing is needed before returning the value.
Example

const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};

console.log(person.fullName); // Output: "John Doe"


Setter Property
 Description: A setter method assigns or "sets" a value to a property. It is defined using the set keyword within an
object or a class.
 Use Case: Setters are helpful when you want to validate or transform the input before setting a property value.
 Example
const person = {
firstName: 'John',
lastName: 'Doe',
set fullName(name) {
const parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
};

person.fullName = "Jane Smith";


console.log(person.firstName); // Output: "Jane"
console.log(person.lastName); // Output: "Smith"

Summary: Getters and setters offer a way to manage property access with added logic, enhancing data
encapsulation and control within objects and classes in JavaScript.
Differentiate Between concat() and join() Methods of Array Object
In JavaScript, concat() and join() are methods used on arrays, but they serve different purposes. Here’s a
breakdown of each method and how they differ.
1. concat()
 Description: The concat() method is used to merge two or more arrays, returning a new array without modifying
the original ones.
 Syntax: array1.concat(array2, array3, ...)
 Use Case: concat() is helpful when you want to combine arrays without changing the original arrays.
 Example:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const result = array1.concat(array2);

console.log(result); // Output: [1, 2, 3, 4, 5, 6]


console.log(array1); // Output: [1, 2, 3] (remains unchanged)
console.log(array2); // Output: [4, 5, 6] (remains unchanged)

2. join()

 Description: The join() method combines all elements of an array into a single string, separated by a specified
delimiter. The original array remains unchanged.

 Syntax: array.join(separator)

 Use Case: join() is used when you need a string representation of an array, with elements separated by a specific
character (e.g., ,, -, or whitespace).

 Example

const array = ['apple', 'banana', 'cherry'];

const result = array.join(', ');

console.log(result); // Output: "apple, banana, cherry"

console.log(array); // Output: ["apple", "banana", "cherry"] (remains unchanged)


2) Explain open Method of Window Object
The open method of the Window object in JavaScript is used to open a new browser window or tab, allowing the user to
navigate to a specified URL. This method can also be used to create a new document in a specified context.

Syntax

window.open(URL, windowName, [windowFeatures]);

 URL (optional): A string representing the URL to be loaded in the new window or tab. If omitted, a blank page is
opened.

 windowName (optional): A string that names the new window. If a window with that name already exists, it will
load the URL in that window instead of opening a new one.

 windowFeatures (optional): A string specifying the features of the new window (like size, position, etc.). This is a
comma-separated list of settings.

Use Case

The open method is commonly used in web applications to open external links, create pop-up windows for additional
information, or to display advertisements.

Example

Here’s a simple example of how to use the open method:

// Function to open a new window

function openNewWindow() {

const url = "https://www.example.com"; // URL to open

const windowName = "ExampleWindow"; // Name of the new window

const windowFeatures = "width=800,height=600,resizable=yes"; // Window features

// Open the new window

const newWindow = window.open(url, windowName, windowFeatures);

// Check if the window was blocked by a pop-up blocker

if (!newWindow) {

alert("Popup blocked! Please allow popups for this website.");

// Call the function to open the new window

openNewWindow();

Explanation of the Example

 When the openNewWindow function is called, it attempts to open a new window pointing to
https://www.example.com.

 The new window is named ExampleWindow, and its features specify a width of 800px, a height of 600px, and that
it is resizable.

 If the new window cannot be opened (e.g., due to a pop-up blocker), an alert is displayed to the user.

Describe regular expression


3) Regular Expressions in JavaScript

#### What is a Regular Expression?

A **regular expression** (regex or regexp) is a sequence of characters that defines a search pattern. It is
commonly used for pattern matching within strings, such as finding specific text, validating input formats, or
extracting portions of a string. In JavaScript, regular expressions are represented by the `RegExp` object.

#### Syntax for Regular Expressions

Regular expressions can be created in two ways:

1. Using a literal notation: `/pattern/flags`

2. Using the `RegExp` constructor: `new RegExp("pattern", "flags")`

**Flags** modify how the regular expression behaves:

- `g`: Global search (find all matches)

- `i`: Case-insensitive search

- `m`: Multi-line search

#### Example of a Regular Expression

```javascript

let regex = /hello/i; // Pattern to match "hello" in a case-insensitive manner

```

---

### `search()` Method in JavaScript

The **`search()`** method is used to search a string for a specified pattern (often a regular expression). It returns
the index (position) of the first match it finds, or `-1` if the pattern is not found.

#### Syntax

```javascript

string.search(regexp);

```

- **`string`**: The string to search within.

- **`regexp`**: A regular expression that defines the search pattern.


#### Example of `search()` Method

Let's look at an example where we search for a word within a sentence:

```javascript

let sentence = "JavaScript is amazing!";

let index = sentence.search(/amazing/i);

console.log(index); // Outputs: 15

```

In this example:

- The `search()` method finds the word "amazing" in `sentence`.

- It returns `15`, which is the index where the match starts.

- The `/amazing/i` pattern is a regular expression that looks for "amazing" in a case-insensitive way.

#### Example with `search()` Not Finding a Match

If the word is not in the string, `search()` returns `-1`.

```javascript

let sentence = "JavaScript is amazing!";

let index = sentence.search(/awesome/i);

console.log(index); // Outputs: -1

```

In this case:

- The word "awesome" is not found in `sentence`.

- `search()` returns `-1`, indicating no match.

#### Important Notes

- The `search()` method always returns the first match index, even if the global (`g`) flag is set.

- For more advanced pattern matching, consider using the `match()` or `matchAll()` methods with regular
expressions.

4) Text Rollover
A **text rollover** is an interactive effect on a webpage where text changes appearance (such as color, font size,
or decoration) when a user hovers over it with their mouse. This technique is often used in navigation menus,
links, or buttons to make them more engaging and visually responsive.

### How to Implement Text Rollover in HTML and CSS

You can achieve text rollover effects using CSS by targeting the `:hover` pseudo-class on an element. The `:hover`
pseudo-class applies styling when the user hovers over the element.

#### Example of Text Rollover

Here’s an example of a simple text rollover effect using CSS.

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Text Rollover Example</title>

<style>

/* Basic style for the link */

.rollover-text {

color: black;

font-size: 18px;

text-decoration: none;

transition: color 0.3s, font-size 0.3s;

/* Text style on hover */

.rollover-text:hover {

color: blue;

font-size: 20px;

text-decoration: underline;

</style>
</head>

<body>

<a href="#" class="rollover-text">Hover over this text</a>

</body>

</html>

```

#### Explanation

- **HTML**: The `<a>` tag represents the text element that will have the rollover effect. It has the class `rollover-
text` applied to it.

- **CSS**:

- The `.rollover-text` class defines the default style for the text (black color, 18px font size).

- The `.rollover-text:hover` class changes the text color to blue, increases the font size to 20px, and underlines
the text when the user hovers over it.

- The `transition` property smoothly animates the change in color and font size over 0.3 seconds, creating a
subtle visual effect.

### Advanced Text Rollover Effect (Color Transition)

You can also add more complex rollover effects, like background-color transitions or text-shadow, to create a
more dynamic interaction.

```css

/* Text style on hover with background color */

.rollover-text:hover {

color: white;

background-color: blue;

padding: 5px 10px;

border-radius: 5px;

```

This example adds a background color and padding, giving the text a "button-like" effect on hover. Text rollover
effects like these make your web elements visually appealing and guide user interaction.

5) `charCodeAt()`
#### Purpose

The `charCodeAt()` method is used to retrieve the Unicode value (character code) of a character at a specified
index in a string. This method is useful when you need to work with the numeric representation of characters.

#### Syntax

```javascript

string.charCodeAt(index);

```

- **Parameters**:

- `index`: An integer representing the position of the character within the string. The first character is at index
`0`.

#### Example

```javascript

let str = "Hello";

let charCode = str.charCodeAt(0); // Get the character code of the first character

console.log(charCode); // Outputs: 72

```

In this example, `charCodeAt(0)` retrieves the Unicode value of the character "H," which is `72`.

### 2. `fromCharCode()`

#### Purpose

The `String.fromCharCode()` method is a static method that creates a string from a sequence of Unicode values. It
is useful for converting numeric Unicode values back into characters.

#### Syntax

```javascript

String.fromCharCode(num1, num2, ..., numN);

```

- **Parameters**:

- `num1`, `num2`, ..., `numN`: One or more integers representing the Unicode values of the characters you want
to create.
#### Example

```javascript

let char1 = String.fromCharCode(72); // Convert Unicode value 72 to character

let char2 = String.fromCharCode(101); // Convert Unicode value 101 to character

let char3 = String.fromCharCode(108); // Convert Unicode value 108 to character

let char4 = String.fromCharCode(108); // Convert Unicode value 108 to character

let char5 = String.fromCharCode(111); // Convert Unicode value 111 to character

let str = char1 + char2 + char3 + char4 + char5; // "Hello"

console.log(str); // Outputs: Hello

```

In this example, `fromCharCode(72, 101, 108, 108, 111)` constructs the string "Hello" from its character codes.

### Summary

- `charCodeAt()`: Retrieves the Unicode value of a character at a specific index in a string.

- `fromCharCode()`: Creates a string from one or more Unicode values.

6) `navigator` Object Properties


The `navigator` object in JavaScript provides information about the browser and the device on which it is being
used. It’s part of the `window` object and contains several properties and methods that give details like the
browser name, version, language, and whether cookies are enabled.

Some commonly used properties of the `navigator` object are:

- **appName**: Returns the name of the browser.

- **appVersion**: Returns the version of the browser as a string.

- **userAgent**: Returns the user-agent string for the browser, which includes information about the browser,
version, and operating system.

- **language**: Returns the browser's language (e.g., "en-US").

- **platform**: Returns the platform (operating system) the browser is running on.

- **cookieEnabled**: Returns a boolean value indicating whether cookies are enabled in the browser.

### Method of `navigator` Object to Display Browser Name and Version

To display the browser name and version, you can use the **`navigator.userAgent`** or
**`navigator.appVersion`** property:

- **`navigator.userAgent`**: This property provides a detailed string containing information about the browser, its
version, and the operating system.

Example:

```javascript

console.log(navigator.userAgent);

```

- **`navigator.appVersion`**: This returns a simpler string with the browser version and platform.

Example:

```javascript

console.log(navigator.appVersion);

```

### Example Code

Here's a snippet to retrieve and display the browser name and version using the `navigator` object:
```javascript

let browserInfo = `Browser Name: ${navigator.appName}, Version: ${navigator.appVersion}`;

console.log(browserInfo);

```

### Summary Table

| Property | Description |

|---------------------|-------------------------------------------|

| `navigator.appName` | Returns the name of the browser |

| `navigator.appVersion` | Returns the browser version and platform |

| `navigator.userAgent` | Returns a detailed user-agent string with information on the browser, version, and OS |

This should help in identifying the browser and its version using JavaScript's `navigator` object!
7) In JavaScript, the `substring()` and `substr()` methods are used to extract
portions of a string, but they differ in terms of parameters and functionality.

### `substring()` Method

- **Syntax**: `string.substring(start, end)`

- **Description**: Extracts characters from a string, starting at the specified `start` index and up to (but not
including) the `end` index.

- **Parameters**:

- `start`: The index to start extraction.

- `end` (optional): The index before which to end extraction. If `end` is omitted, `substring()` extracts to the end
of the string.

- **Key Points**:

- If `start` is greater than `end`, `substring()` swaps the arguments.

- If a negative index or NaN is passed, `substring()` treats it as 0.

**Example**:

```javascript

let str = "JavaScript";

console.log(str.substring(0, 4)); // Output: "Java"

console.log(str.substring(4)); // Output: "Script"

```

### `substr()` Method

- **Syntax**: `string.substr(start, length)`

- **Description**: Extracts characters from a string, starting at the specified `start` index and continuing for a
specified `length` of characters.

- **Parameters**:

- `start`: The index to start extraction. If negative, it counts from the end of the string.

- `length` (optional): The number of characters to extract. If omitted, extracts to the end of the string.

- **Key Points**:

- Negative `start` values count backward from the end of the string.

- Unlike `substring()`, `substr()` does not swap the arguments if `start` is greater than `length`.

Example**:

```javascript

let str = "JavaScript";

console.log(str.substr(4, 6)); // Output: "Script"

console.log(str.substr(-6, 6)); // Output: "Script" (starts from 6th last character)


8) Properties of the `window` Object

The `window` object in JavaScript represents an open window in the browser and provides properties, methods,
and events that help interact with the browser environment.

1. **innerWidth**: Returns the inner width of the browser window's content area (in pixels).

2. **innerHeight**: Returns the inner height of the browser window's content area (in pixels).

3. **outerWidth**: Returns the outer width of the browser window, including any sidebar.

4. **outerHeight**: Returns the outer height of the browser window, including any toolbar.

5. **location**: Returns a `Location` object with information about the URL of the current document.

6. **history**: Returns a `History` object, allowing navigation between the pages in the session history.

7. **navigator**: Returns a `Navigator` object that provides information about the browser.

8. **document**: Returns the `Document` object for the window, which represents the content of the
document.

### JavaScript Code to Open Popup Windows

Here's the JavaScript code to display two pop-up windows with different messages when the page loads.

```javascript

// Function to display popup windows on page load

window.onload = function() {

// Open a new window with the first message

let popup1 = window.open("", "", "width=300,height=200");

popup1.document.write("<h3>WELCOME TO SCRIPTING</h3>");

// Open another new window with the second message

let popup2 = window.open("", "", "width=300,height=200");

popup2.document.write("<h3>FUN WITH SCRIPT</h3>");

};

```

### Explanation

1. **window.onload**: This event fires when the page finishes loading, and it triggers the function to open pop-
up windows.

2. **window.open**: This method creates a new browser window or tab. Here, it opens two pop-ups with
specific dimensions.

3. **document.write**: This method writes the HTML content (in this case, a message) to the pop-up window's
document.
9) Why Hide JavaScript Code?
Hiding JavaScript code is a technique primarily used for backward compatibility with very old browsers that do
not support JavaScript. In such cases, JavaScript code is hidden within HTML comments to prevent the browser
from rendering the code as plain text on the page.

1. **Backward Compatibility**: Some older browsers, particularly before the mid-1990s, did not recognize
JavaScript code, so they would display it as plain text on the page. Hiding JavaScript in comments ensures that
such browsers ignore the JavaScript code.

2. **Graceful Degradation**: For older or non-JavaScript browsers, hiding JavaScript code prevents users from
seeing unstyled, confusing code on their screen.

Today, this technique is mostly obsolete since modern browsers fully support JavaScript.

### Steps to Hide JavaScript Code

1. **Use HTML Comment Tags**: Wrap JavaScript code within HTML comment tags.

2. **Add Opening Comment Tag**: At the beginning of your JavaScript code, include the comment tag `<!--`.

3. **Add Closing Comment Tag**: After the JavaScript code, use the comment closing tag `// -->` to end the
hiding.

### Example of Hiding JavaScript Code

Here's an example of how JavaScript can be hidden in HTML comments:

```html

<script type="text/javascript">

<!--

// JavaScript code starts here

alert("JavaScript is enabled!");

// End of JavaScript code

// -->

</script>

```

### Explanation of the Process

1. **Opening Comment Tag (`<!--`)**: This tag is added right after the `<script>` tag to start the hidden JavaScript
section.

2. **JavaScript Code**: Write your JavaScript code as usual within this commented section.

3. **Closing Comment Tag (`// -->`)**: This tag marks the end of the comment and ensures that any browser
supporting JavaScript will still run the code correctly, as it interprets `//` as a comment in JavaScript.

### Important Note

Modern browsers fully support JavaScript, and this hiding method is rarely needed today. Most browsers simply
ignore HTML comments inside `<script>` tags, so the JavaScript code will still run even if the comments are
present
10) Six Common Form Events

Form events in JavaScript are triggered when users interact with form elements, such as entering text, submitting
the form, or changing a selection. These events can help validate input, enhance user experience, or dynamically
update the interface.

1. **onfocus**

- **Description**: Triggered when an input field, text area, or other form element gains focus (usually when the
user clicks on it or tabs into it).

- **Use Case**: Often used to highlight the focused field or display help text.

- **Example**:

```javascript

<input type="text" onfocus="this.style.backgroundColor='yellow';">

```

2. **onblur**

- **Description**: Triggered when an input field loses focus, such as when the user clicks away or tabs out of it.

- **Use Case**: Commonly used to validate the field’s content or hide helper text.

- **Example**:

```javascript

<input type="text" onblur="this.style.backgroundColor='';">

```

3. **onchange**

- **Description**: Triggered when the value of an input, select, or text area changes, and the user clicks outside
the field.

- **Use Case**: Useful for validating inputs in real-time or dynamically updating content based on user input.

- **Example**:

```javascript

<select onchange="alert('Selection changed!')">

<option>Option 1</option>

<option>Option 2</option>

</select>

```

4. **oninput**

- **Description**: Triggered every time the value of an `<input>` or `<textarea>` changes, even while the user is
typing.

- **Use Case**: Ideal for real-time validation, character counters, or live feedback.

- **Example**:

```javascript
<input type="text" oninput="console.log(this.value)">

```

5. **onsubmit**

- **Description**: Triggered when a form is submitted, usually by clicking a submit button.

- **Use Case**: Typically used to validate the form data before submission or prevent submission based on
certain conditions.

- **Example**:

```javascript

<form onsubmit="return validateForm()">

<input type="text" required>

<input type="submit" value="Submit">

</form>

<script>

function validateForm() {

// Perform validation

return confirm("Are you sure you want to submit?");

</script>

```

6. **onreset**

- **Description**: Triggered when a form is reset, typically by clicking a reset button.

- **Use Case**: Often used to confirm before clearing all form fields, or to handle actions when resetting.

- **Example**:

```javascript

<form onreset="return confirm('Are you sure you want to reset?')">

<input type="text">

<input type="reset" value="Reset">

</form>

```
11) `lastIndex`
In JavaScript, the Regular Expression (RegExp) object is used for pattern matching and searching within strings.
Here are three commonly used properties of the `RegExp` object:

- **Description**: Holds the index at which to start the next match when using a regular expression with the `g`
(global) flag. This property is automatically updated as the `exec()` or `test()` method is called on the regular
expression in a loop.

- **Use**: Primarily used for iterative searches within a string, allowing continuous matching without restarting
from the beginning of the string.

- **Example**:

```javascript

let regex = /hello/g;

let str = "hello world hello universe";

while (regex.test(str)) {

console.log("Match found at index:", regex.lastIndex);

```

### 2. `source`

- **Description**: Returns the text of the regular expression pattern without the delimiters and flags.

- **Use**: Useful for debugging or dynamically checking the pattern of a regular expression.

- **Example**:

```javascript

let regex = /hello/i;

console.log(regex.source); // Output: "hello"

```

### 3. `flags`

- **Description**: Returns a string containing the flags of the regular expression, such as `g` for global, `i` for
case-insensitive, and `m` for multiline.

- **Use**: Helpful for determining the behavior of a regular expression dynamically, especially if the flags are not
immediately visible or need to be checked during runtime.

- **Example**:

```javascript

let regex = /hello/gi;

console.log(regex.flags); // Output: "gi"

```
12)
13) Key Concepts of Regular Expressions
A **regular expression** (often abbreviated as "regex" or "regexp") is a sequence of characters that forms a
search pattern. It is used to match, search, and manipulate strings based on specific patterns. Regular expressions
are commonly used for tasks like validating input, searching within text, replacing text patterns, and extracting
specific parts of strings.

1. **Pattern Matching**: Regular expressions define patterns for strings, making it possible to identify specific
sequences of characters.

2. **Special Characters**: Characters like `.` (dot), `*` (asterisk), `+` (plus), and `?` (question mark) have special
meanings in regular expressions.

3. **Character Classes**: Sets of characters like `[a-z]` (any lowercase letter) or `\d` (any digit) that represent
ranges or specific types of characters.

### Example Regular Expression and Explanation

Suppose we want to create a regular expression to match any valid email address. A simple regex pattern for an
email might look like this:

```javascript

let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

```

Here’s a breakdown of this pattern:

- **`^`**: Asserts the start of the string.

- **`[a-zA-Z0-9._%+-]+`**: Matches one or more characters that are letters (uppercase or lowercase), digits, dots
(`.`), underscores (`_`), percent signs (`%`), plus signs (`+`), or hyphens (`-`). This part matches the "username" part
of an email.

- **`@`**: Matches the `@` symbol in the email.

- **`[a-zA-Z0-9.-]+`**: Matches the domain part of the email, allowing letters, digits, dots (`.`), and hyphens (`-`).

- **`\.`**: Matches a literal dot (`.`), which separates the domain and top-level domain (e.g., `.com`).

- **`[a-zA-Z]{2,}`**: Matches the top-level domain with at least two letters (e.g., "com" or "org").

- **`$`**: Asserts the end of the string.

### Using the Regular Expression in JavaScript

Here’s an example of how to use this regex to validate an email address in JavaScript:

```javascript

let email = "example@example.com";

let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

if (emailPattern.test(email)) {

console.log("Valid email address!");

} else {

console.log("Invalid email address.");}


14)
The Questions
1) Explain getter and setter properties in JS script with sutable example
2) Explain prompt() and confirm() method of JS with syntax and example
3) Differentiate between concat() and join() methods of arry object
4) Explain open() method of window object with syntax and example
5) Describe regular expression explain search () method usend in regular expression
with suitable example
6) List ways of protecting your web pageand describe any with sutable example
7) State the use of following methods
a. CharCodeAt()
b. fromCharCode()
8) Describe the “navigator ”object of javascript Describe the methods of navigator
object witch is used to display browser name and version
9) Differentiate between substring() and substr() method of a string class give sutable
example
10) Sate wha is a cookie ? explain its need state characterstics of persistent cookies
11) List and state various properties of a windo object
12) State the use of hiding the javascript explain the steps needed to accomplish it and
describe the process
13) List and explain any six form events
14) List any three prorperties of regular expression bject and state their use
15) Differentiate between concat() and join() methods of arry object
16) Differentate between for-loop and for-in loop

You might also like