0% found this document useful (0 votes)
51 views12 pages

BCA 4th Sem

The document provides an overview of JavaScript concepts including objects, regular expressions, type conversion, event handling, the Document Object Model (DOM), the Browser Object Model (BOM), cookies, form handling, and an introduction to jQuery. It covers how to create and manipulate objects, use regular expressions for text manipulation, handle events, and interact with the browser. Additionally, it introduces jQuery as a library that simplifies DOM manipulation and event handling.

Uploaded by

ramanpanchal64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views12 pages

BCA 4th Sem

The document provides an overview of JavaScript concepts including objects, regular expressions, type conversion, event handling, the Document Object Model (DOM), the Browser Object Model (BOM), cookies, form handling, and an introduction to jQuery. It covers how to create and manipulate objects, use regular expressions for text manipulation, handle events, and interact with the browser. Additionally, it introduces jQuery as a library that simplifies DOM manipulation and event handling.

Uploaded by

ramanpanchal64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

BCA 4th Sem - JAVA SCRIPT

Objects in JavaScript

An object is a collection of key-value pairs, where values can be properties (data) or


methods (functions).

Types of Objects in JavaScript

1. Native Objects – Built-in objects like Array, String, Number, Date, etc.

2. User-Defined Objects – Objects created by the user using object literals,


constructors, or classes.

Creating Objects

1. Object Literal

2. let person = { name: "John", age: 30 };

3. Using new Object()

4. let obj = new Object();

5. obj.name = "John";

6. Using Constructor Function

7. function Person(name, age) {

8. this.name = name;

9. this.age = age;

10. }

11. let p1 = new Person("John", 30);

12. Using Class Syntax (ES6)

13. class Person {

14. constructor(name, age) {

15. this.name = name;

16. this.age = age;

17. }

18. }

19. let p2 = new Person("Jane", 25);

Object Methods

Methods are functions stored in an object.

let person = {
name: "John",

greet: function() {

return `Hello, ${this.name}`;

};

console.log(person.greet()); // Hello, John

Prototype in JavaScript

Every JavaScript object has a hidden [[Prototype]] property that links to another object.

function Person(name) {

this.name = name;

Person.prototype.greet = function() {

return `Hello, ${this.name}`;

};

let p = new Person("Alice");

console.log(p.greet()); // Hello, Alice

Inheritance using Prototype Chain

Objects inherit properties and methods from their prototype.

function Animal(name) {

this.name = name;

Animal.prototype.speak = function() {

return `${this.name} makes a noise.`;

};

function Dog(name) {

Animal.call(this, name);

Dog.prototype = Object.create(Animal.prototype);

Dog.prototype.bark = function() {

return `${this.name} barks.`;

};
let d = new Dog("Buddy");

console.log(d.speak()); // Buddy makes a noise.

console.log(d.bark()); // Buddy barks.

Regular Expressions in JavaScript

A Regular Expression (RegExp) is a pattern for searching and manipulating text.

Creating a Regular Expression

1. Using RegExp Constructor

2. let regex = new RegExp("hello");

3. Using Literal Notation

4. let regex = /hello/;

Modifiers

• g – Global search

• i – Case-insensitive search

• m – Multi-line search

let regex = /hello/gi;

RegExp Patterns

• ^ – Start of a string

• $ – End of a string

• \d – Digits (0-9)

• \w – Word character (a-z, A-Z, 0-9, _)

• \s – Whitespace

• . – Any character except newline

• * – 0 or more occurrences

• + – 1 or more occurrences

• {n} – Exactly n occurrences

RegExp Methods

• test() – Returns true if match is found

• let regex = /hello/i;

• console.log(regex.test("Hello World")); // true

• exec() – Returns first match


• let match = /hello/.exec("hello world");

• console.log(match[0]); // "hello"

String Methods for RegExp

• match() – Finds matches

• let str = "hello world";

• console.log(str.match(/hello/)); // ["hello"]

• replace() – Replaces matched text

• let str = "hello world";

• console.log(str.replace(/hello/, "hi")); // "hi world"

• split() – Splits string using regex

• let str = "one,two,three";

• console.log(str.split(/,/)); // ["one", "two", "three"]

Type Conversion in JavaScript

JavaScript allows implicit and explicit type conversion.

Implicit Conversion (Type Coercion)

console.log(5 + "10"); // "510" (number + string → string)

console.log("5" * 2); // 10 (string * number → number)

console.log(true + 1); // 2 (boolean → number)

Explicit Conversion

• String Conversion

• let num = 123;

• console.log(String(num)); // "123"

• console.log(num.toString()); // "123"

• Number Conversion

• console.log(Number("123")); // 123

• console.log(parseInt("123px")); // 123

• console.log(parseFloat("12.3px")); // 12.3

• Boolean Conversion

• console.log(Boolean(0)); // false

• console.log(Boolean(1)); // true
• console.log(Boolean("hello")); // true

This provides a solid introduction to JavaScript Objects, Regular Expressions, and Type
Conversion. Let me know if you need further details!

Event Handling in JavaScript

JavaScript events allow you to detect user interactions like clicks, keystrokes, or mouse
movements.

JavaScript Events

Events are triggered by user actions (e.g., clicking a button) or system actions (e.g., page
loading).

Event Handler

A function that executes when an event occurs.

function showMessage() {

alert("Button clicked!");

document.getElementById("btn").onclick = showMessage;

Event Flow

Determines the order in which event handlers execute in nested elements.

1. Event Bubbling – Inner to outer element (default behavior).

2. Event Capturing – Outer to inner element.

document.getElementById("child").addEventListener("click", () => alert("Child clicked"), false);


// Bubbling

document.getElementById("parent").addEventListener("click", () => alert("Parent clicked"),


true); // Capturing

Event Listeners

More flexible than onclick, allowing multiple handlers.

document.getElementById("btn").addEventListener("click", function() {

alert("Button clicked!");

});

Event Types

• Mouse Events – click, dblclick, mouseover, mouseout, mousemove

• Keyboard Events – keydown, keyup


• Form Events – submit, focus, blur

• Window Events – load, resize, scroll

Document Object Model (DOM)

The DOM represents a web page as a tree structure where elements are nodes.

Types of DOM

1. Core DOM – Standard model for any document type.

2. HTML DOM – Represents HTML elements as objects.

3. XML DOM – Represents XML documents.

DOM Standards and Methods

Common methods to select and manipulate elements:

document.getElementById("demo").innerHTML = "Hello!";

document.getElementsByClassName("myClass")[0].style.color = "red";

document.querySelector("p").style.fontSize = "20px";

Manipulating Documents Using DOM

• Changing Content

• document.getElementById("title").innerText = "New Title";

• Changing Attributes

• document.getElementById("image").src = "new-image.jpg";

• Adding/Removing Elements

• let newEl = document.createElement("p");

• newEl.textContent = "New Paragraph";

• document.body.appendChild(newEl);

Handling Images

document.getElementById("img").src = "new-pic.jpg";

Table Manipulation

let table = document.getElementById("myTable");

let row = table.insertRow(0);

let cell = row.insertCell(0);

cell.innerHTML = "New Cell";

Animation (CSS + JavaScript)


let box = document.getElementById("box");

box.style.transition = "transform 1s";

box.style.transform = "translateX(100px)";

Node and Node-List Handling

• Nodes – Elements, attributes, text

• NodeList – Collection of nodes (like querySelectorAll)

let nodes = document.querySelectorAll("p");

nodes.forEach(node => node.style.color = "blue");

This provides a strong foundation for event handling and DOM manipulation in JavaScript. Let
me know if you need more details!

Browser Object Model (BOM)

The BOM allows JavaScript to interact with the browser (e.g., manipulating the window, history,
location, etc.).

DOM vs BOM Differences

Feature DOM BOM

Represents the document structure as Represents the browser and its


Definition
objects components

Browser functionalities (window, location,


Focus HTML elements
history)

Methods getElementById(), querySelector() alert(), navigator.userAgent, setTimeout()

Window Object & Methods

The window object is the global object in browsers.

Common Methods

alert("Hello!"); // Displays an alert

confirm("Are you sure?"); // Shows confirmation dialog

let name = prompt("Enter your name"); // Takes user input

console.log(innerWidth, innerHeight); // Viewport size

BOM Components
BOM Navigator (Browser Info)

console.log(navigator.userAgent); // Browser details

console.log(navigator.language); // Browser language

BOM History (Back & Forward Navigation)

history.back(); // Go to previous page

history.forward(); // Go to next page

BOM Location (URL Manipulation)

console.log(location.href); // Current URL

location.href = "https://example.com"; // Redirect to a new page

console.log(location.hostname); // Hostname of the URL

BOM Timer (setTimeout & setInterval)

setTimeout(() => alert("Hello after 3 seconds"), 3000); // Runs once

let interval = setInterval(() => console.log("Repeating"), 2000); // Runs every 2 seconds

clearInterval(interval); // Stops interval

Cookies in JavaScript

Cookies store small amounts of data in the browser.

Session vs Persistent Cookies

Type Description

Session Cookies Stored temporarily, deleted when the browser closes.

Persistent Cookies Stored with an expiration date, remain after browser restarts.

Managing Cookies

document.cookie = "username=John; expires=Fri, 31 Dec 2025 12:00:00 UTC";

console.log(document.cookie); // Retrieve cookies

Form Handling in JavaScript

Accessing Form Data

let name = document.forms["myForm"]["username"].value;

console.log(name);

Form Validation
function validateForm() {

let x = document.forms["myForm"]["username"].value;

if (x == "") {

alert("Name must be filled out");

return false;

Validation APIs

let input = document.getElementById("email");

console.log(input.validity.valid); // Check if input is valid

This provides an overview of BOM, cookies, and form handling in JavaScript. Let me know if you
need further explanations!

Introduction to jQuery

jQuery is a fast, lightweight JavaScript library that simplifies HTML DOM manipulation, event
handling, animations, and AJAX interactions.

jQuery Syntax

Basic syntax:

$(selector).action();

Example:

$(document).ready(function() {

$("p").css("color", "blue");

});

or

$(function() {

$("p").css("color", "blue");

});

jQuery Selectors

Used to select and manipulate HTML elements.


Selector Description Example

$("p") Selects all <p> elements $("p").hide();

$(".class") Selects all elements with class $(".box").fadeIn();

$("#id") Selects element with ID $("#title").text("New Title");

$("ul li:first") First <li> inside <ul> $("ul li:first").css("color", "red");

jQuery Events

Handles user interactions.

$("#btn").click(function() {

alert("Button clicked!");

});

Common events:

• click()

• dblclick()

• hover()

• keydown(), keyup()

• focus(), blur()

jQuery Effects

Predefined animations.

$("#box").fadeOut(); // Fades out an element

$("#box").slideUp(); // Slides up an element

$("#box").toggle(); // Toggles visibility

Custom animations:

$("#box").animate({left: "100px", opacity: "0.5"}, 1000);

jQuery HTML Manipulation

Change content and attributes.

$("#title").text("New Text"); // Change text

$("#box").html("<b>Bold Text</b>"); // Change HTML content


$("#input").val("Hello"); // Set input value

$("#link").attr("href", "https://example.com"); // Change attribute

jQuery Traversing

Navigate DOM elements.

$("p").parent(); // Get parent

$("p").children(); // Get child elements

$("div").find("span"); // Find inside elements

$("p").next(); // Get next sibling

$("p").prev(); // Get previous sibling

jQuery AJAX

Used to load data asynchronously.

$.get("data.txt", function(data) {

$("#content").text(data);

});

$.ajax({

url: "data.json",

method: "GET",

success: function(response) {

console.log(response);

});

jQuery Miscellaneous

• each() – Loops through elements

• $("li").each(function() {

• console.log($(this).text());

• });

• addClass() / removeClass() – Manipulates CSS classes

• $("#box").addClass("highlight");
• $("#box").removeClass("highlight");

• noConflict() – Avoids conflicts with other libraries

• var $jq = jQuery.noConflict();

• $jq("p").hide();

This gives a quick overview of jQuery. Let me know if you need more details!

You might also like