Assignment 1 โ Introduction to JavaScript
6 Questions ยท CO1
Definition
JavaScript (JS) is a lightweight, interpreted, object-based scripting language used to make web pages interactive and dynamic. Created by Brendan Eich in 1995, it is one of the three core web technologies alongside HTML and CSS. JS runs in the browser (client-side) without needing server interaction.
Main Features of JavaScript
- Interpreted Language โ Code is executed line-by-line at runtime; no compilation required.
- Object-Based โ Supports objects (without full class-based OOP like Java).
- Client-Side Scripting โ Runs in the browser, reducing load on the server.
- Dynamic Typing โ Variable types are resolved at runtime (no need to declare types).
- Event-Driven โ Responds to user actions: clicks, key presses, mouse moves, etc.
- Platform Independent โ Works on any browser/OS without modification.
- Case Sensitive โ
Varandvarare treated differently. - Loosely Typed โ Variables can hold any type; no strict declaration needed.
- Prototype-Based Inheritance โ Objects inherit from other objects via prototype chain.
- DOM Manipulation โ Can access and modify HTML/CSS elements dynamically.
- Supports Closures & First-Class Functions โ Functions are treated as values.
// Simple JS example showing features
let name = "Adii"; // Dynamic typing
let age = 21;
console.log(`Hello, ${name}! Age: ${age}`);
// Object-based
let student = { name: "Adii", branch: "ENTC" };
console.log(student.branch); // ENTC
// Event-driven
document.getElementById("btn").onclick = function() {
alert("Button clicked!");
};
Definition
Event handlers are JavaScript functions or code that execute automatically when a specific event occurs on an HTML element. They make web pages interactive by responding to user or browser actions.
How to Assign Event Handlers
- Inline HTML attribute:
<button onclick="doSomething()"> - DOM property:
element.onclick = function() {...} - addEventListener():
element.addEventListener("click", fn)
Common Event Handler Categories
| Category | Handlers |
|---|---|
| Mouse Events | onclick, ondblclick, onmouseover, onmouseout, onmousedown, onmouseup |
| Keyboard Events | onkeydown, onkeyup, onkeypress |
| Form Events | onsubmit, onreset, onchange, onfocus, onblur, oninput |
| Window Events | onload, onunload, onresize, onscroll |
// Method 1: Inline
// <button onclick="alert('Hi!')">Click</button>
// Method 2: DOM property
let btn = document.getElementById("myBtn");
btn.onclick = function() { alert("Clicked!"); };
// Method 3: addEventListener (recommended)
btn.addEventListener("click", function() {
console.log("Event fired!");
});
Types of Event Handlers in JavaScript
- Mouse Event Handlers
onclickโ single mouse clickondblclickโ double clickonmouseoverโ mouse enters elementonmouseoutโ mouse leaves elementonmousemoveโ mouse moves over elementonmousedown/onmouseupโ mouse button pressed/released
- Keyboard Event Handlers
onkeydownโ key is pressed downonkeyupโ key is releasedonkeypressโ key is pressed and character produced (deprecated)
- Form Event Handlers
onsubmitโ form submittedonresetโ form resetonchangeโ value changes and focus lostonfocusโ element gains focusonblurโ element loses focusoninputโ value changes instantly (each keystroke)
- Window/Document Event Handlers
onloadโ page/image fully loadedonunloadโ page is being closedonresizeโ browser window resizedonscrollโ page is scrolled
- Clipboard Event Handlers:
oncopy,oncut,onpaste - Drag Event Handlers:
ondrag,ondrop,ondragstart,ondragend
// Examples of different event types
document.onkeydown = function(e) {
console.log("Key pressed: " + e.key);
};
document.getElementById("myInput").onfocus = function() {
console.log("Input focused!");
};
window.onload = function() {
console.log("Page fully loaded");
};
Definition
A Regular Expression (RegEx) is a sequence of characters that forms a search pattern. In JavaScript, RegEx is used to match, search, replace, or validate strings. It is defined using /pattern/flags or new RegExp('pattern').
Common Symbols
| Symbol | Meaning | Example |
|---|---|---|
. | Any single character | /h.t/ โ "hat", "hot" |
* | Zero or more occurrences | /ab*/ โ "a", "ab", "abb" |
+ | One or more occurrences | /ab+/ โ "ab", "abb" |
? | Zero or one occurrence | /colou?r/ โ "color"/"colour" |
^ | Start of string | /^Hello/ |
$ | End of string | /World$/ |
\d | Any digit [0-9] | /\d+/ โ "123" |
\w | Word character [a-zA-Z0-9_] | /\w+/ |
[] | Character class | /[aeiou]/ |
Flags
iโ case insensitivegโ global (find all matches)mโ multiline
// Creating RegEx
let p1 = /hello/i; // literal syntax
let p2 = new RegExp("hello", "i"); // constructor
// test() โ returns true/false
console.log(p1.test("Hello World")); // true
console.log(p1.test("Hi World")); // false
// match() โ find matches
let str = "I love JavaScript and Java";
let result = str.match(/Java\w*/g);
console.log(result); // ["JavaScript", "Java"]
// replace()
let s = "cat bat sat";
console.log(s.replace(/[bcs]at/g, "dog")); // "dog dog dog"
// Email validation example
let emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailReg.test("adii@sppu.edu.in")); // true
Input Methods in JavaScript
- prompt() โ Shows dialog box; user types input. Returns string.
let name = prompt("Enter your name:", "Default"); console.log("Hello, " + name); - HTML Form Inputs โ User enters data via input elements.
// <input type="text" id="uname"> let name = document.getElementById("uname").value; - confirm() โ Returns
true(OK) orfalse(Cancel).let ans = confirm("Do you want to continue?"); if (ans) { alert("Continuing..."); }
Output Methods in JavaScript
- document.write() โ Writes directly into HTML page.
document.write("<h2>Hello World</h2>"); // Use with caution - alert() โ Popup message box.
alert("This is an alert message!"); - console.log() โ Writes to browser developer console.
console.log("Debug:", 42); console.error("Error occurred"); console.warn("Warning!"); - innerHTML / textContent โ Updates content of an HTML element.
document.getElementById("result").innerHTML = "<b>Output Here</b>"; document.getElementById("result").textContent = "Plain Text Only";
innerHTML / textContent for DOM output. Use console.log() for debugging. Avoid document.write() after page load.Definition
The onmouseover event handler fires when the user moves the mouse pointer onto an HTML element (or any of its children). It is widely used to create hover effects, tooltips, image swapping, and menu highlighting.
Its counterpart onmouseout fires when the mouse leaves the element.
Syntax
<!-- Method 1: HTML Attribute -->
<p onmouseover="this.style.color='red'">Hover me!</p>
// Method 2: JavaScript
let box = document.getElementById("box");
box.onmouseover = function() {
box.style.backgroundColor = "#7c6ff7";
box.textContent = "Mouse is OVER!";
};
box.onmouseout = function() {
box.style.backgroundColor = "";
box.textContent = "Hover over me";
};
// Method 3: addEventListener
box.addEventListener("mouseover", function() {
console.log("Mouse entered the element!");
});
Practical Use: Image Swap
<img id="myImg" src="normal.jpg"
onmouseover="this.src='hover.jpg'"
onmouseout="this.src='normal.jpg'">