π Lecture 46 β CSS Class, Image Gallery, Navigation Menu, Image Opacity, Image Sprites
π Overview: This lecture covers CSS class selectors and their syntax, then explores practical applications including image galleries, navigation bars, image opacity/transparency effects, and image sprites for optimizing web performance. These concepts are fundamental for creating visually appealing and efficient websites.
ποΈ Topics Covered
The lecture covers CSS class selectors and how to apply them to specific HTML elements, creating CSS image galleries, building vertical and horizontal navigation bars using HTML lists, implementing image transparency with opacity properties and hover effects, and using CSS image sprites to reduce server requests by combining multiple images into one.
π Lecture Summary
46- CSS Class
In CSS, a class is a type of selector. The .class selector styles all elements with the specified class attribute value. Class names can use alphanumeric characters but must NOT start with a number.
π Definition β CSS Class: A selector that targets all HTML elements containing a specific class attribute value, allowing for reusable styling across multiple elements.
π Formula: .className { css-declarations } β Applies the specified styles to all elements with that class
π Example:
.imp {color:blue; font-size:14px}
<div class="imp"> ... </div>
<span class="imp"> ... </span>
<a class="imp"> ... </a>
All three elements (div, span, a) with class="imp" will display blue text at 14px size.
You can also specify that only specific HTML elements should be affected by a class using element.class selector:
p.imp {color:blue; font-size:14px}
Now only <p> elements with class="imp" will be styled - the <div> and <span> with class="imp" will NOT be affected.
47- CSS Image Gallery
CSS can be used to create an image gallery. This allows displaying multiple images in an organized grid layout with borders, captions, and hover effects using CSS properties.
π‘ Why this matters: Image galleries are essential for portfolio sites, e-commerce product displays, and photo albums.
48- CSS Navigation Menu
Navigation bars transform boring HTML menus into good-looking navigation bars. A navigation bar is essentially a list of links, so using <ul> and <li> elements is the standard approach.
π Definition β Navigation Bar: A list of links styled with CSS to provide easy-to-use website navigation, built from standard HTML unordered lists.
Base HTML structure:
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
Standard code for all navigation bars:
ul { list-style-type: none; margin: 0; padding: 0;}
list-style-type: none- Removes the bulletsmargin: 0; padding: 0- Removes browser default settings
Vertical Navigation Bar:
a {display: block; width: 60px;}
display: block- Makes the whole link area clickable (not just the text)width: 60px- Specifies the width of block elements
Horizontal Navigation Bar - Inline method:
li {display: inline; }
display: inline- Removes line breaks before/after each list item, displaying them on one line
Horizontal Navigation Bar - Floating method (for equal-width links):
li {float: left; }
a { display: block; width: 60px; }
width: 60px- Block elements take full width by default, so specifying width allows them to float next to each otherfloat: left- Gets block elements to slide next to each otherdisplay: block- Makes the whole link area clickable
π‘ Why this matters: The floating method ensures all links have equal width, while inline method has varying widths based on text length.
48- CSS Image Opacity
The CSS opacity property creates transparent images. It's part of the CSS3 recommendation. The opacity property takes a value from 0.0 - 1.0, where lower values make elements more transparent.
π Definition β CSS Opacity: A property that controls the transparency level of an element, ranging from 0.0 (completely transparent) to 1.0 (completely opaque).
Creating a transparent image:
img {opacity: 0.4; filter: alpha(opacity=40); /* For IE8 and earlier */ }
- IE9, Firefox, Chrome, Opera, Safari: use
opacityproperty (0.0 - 1.0) - IE8 and earlier: use
filter:alpha(opacity=x)where x ranges from 0 to 100
Image Transparency with Hover Effect:
img { opacity: 0.4; filter: alpha(opacity=40); }
img:hover { opacity: 1.0; filter: alpha(opacity=100); }
The image is semi-transparent by default but becomes fully opaque when hovered.
Text in Transparent Box:
Create a <div> (class="background") with background image and border, then another <div> (class="transbox") inside it with background color and border - the inner div is transparent, containing text inside a <p> element.
49- CSS Image Sprites
An image sprite is a collection of images put into a single image. Using image sprites reduces the number of server requests and saves bandwidth when a web page has many images.
π Definition β Image Sprite: A single composite image containing multiple smaller images, used with CSS background positioning to display only the required portion.
Basic sprite example:
#home {width: 46px; height: 44px; background: url(img_navsprites.gif) 0 0;}
<img id="home" src="img_trans.gif">- Uses a small transparent image since src cannot be emptywidth: 46px; height: 44px- Defines the portion of the sprite image to displaybackground: url(img_navsprites.gif) 0 0- Sets background image and position (left 0px, top 0px)
Creating a Navigation List with Sprites:
#navlist {position:relative;}
#navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;}
#navlist li, #navlist a {height:44px;display:block;}
position:relative- Allows absolute positioning inside- List items are absolutely positioned with no margins, padding, or bullets
Positioning specific sprite parts:
#home {left:0px;width:46px; background:url(img_navsprites.gif) 0 0;}
#prev {left:63px;width:43px; background:url('img_navsprites.gif') -47px 0;}
#home: Positioned left, width 46px, background at 0,0#prev: Positioned 63px right (46px home width + spacing), width 43px, background shifted -47px right (46px + 1px divider)
β Key Takeaways
CSS classes use the .class selector to style multiple elements with the same class attribute, and the element.class syntax restricts styling to specific HTML elements. Navigation bars are built from unordered lists with bullets removed, where vertical bars use block display on links, and horizontal bars use either inline list items or floating with specified widths for equal sizing. Image opacity ranges from 0.0 to 1.0 in modern browsers, with separate filter syntax for older IE versions, and can include hover effects for interactive transparency changes. Image sprites combine multiple images into one file to reduce server requests, using CSS background positioning with precise width and height values to display only the needed portion. The sprite technique is particularly useful for navigation menus where different states of buttons need to be displayed from a single image source.
π§ Quick Revision Questions
- What is the correct CSS syntax to style only
<p>elements that have the class "highlight"? - What are the two methods for creating a horizontal navigation bar, and which one ensures all links have equal width?
- What CSS property creates transparency in modern browsers, and what is its value range?
- How would you display the second image in a sprite when the first image is 46px wide with a 1px divider?
- Why is
display: blockimportant when creating navigation bars from anchor elements?
π Lecture 51 β CSS Attribute Selectors
π Overview: This lecture covers CSS Attribute Selectors, a powerful way to style HTML elements based on their attributes or attribute values. It explains how to target elements with specific attributes, exact values, partial matches, and how to apply these selectors for practical tasks like styling forms without needing classes or IDs.
ποΈ Topics Covered
This lecture introduces the concept of styling HTML elements with specific attributes, then systematically covers seven CSS attribute selectors: [attribute], [attribute=value], [attribute~=value], [attribute|=value], [attribute^=value], [attribute$=value], and [attribute*=value]. Each selector is explained with its syntax, purpose, and a code example. The lecture concludes with a practical application of attribute selectors for styling forms.
π Lecture Summary
Style HTML Elements with Specific Attributes
It is possible to style HTML elements that have specific attributes or attribute values. This approach allows for precise targeting without relying on classes or IDs.
CSS [attribute] Selector
The [attribute] selector is used to select elements with a specified attribute. The following example selects all <a> elements with a target attribute:
a[target] {
background-color: yellow;
}
π Definition β [attribute] Selector: Selects all elements that have the specified attribute, regardless of its value.
CSS [attribute=value] Selector
The [attribute=value] selector is used to select elements with a specified attribute and value. The example below selects all <a> elements with a target="_blank" attribute:
a[target="_blank"] { background-color: yellow; }
π Definition β [attribute=value] Selector: Selects all elements that have the specified attribute exactly equal to the specified value.
CSS [attribute~=value] Selector
The [attribute~=value] selector is used to select elements with an attribute value containing a specified word. The example below selects all elements with a title attribute that contains a space-separated list of words, one of which is "flower":
[title~="flower"] { border: 5px solid yellow; }
π Definition β [attribute~=value] Selector: Selects elements where the attribute value is a space-separated list of words, and one of those words is exactly the specified value.
CSS [attribute|=value] Selector
The [attribute|=value] selector is used to select elements with the specified attribute starting with the specified value. The following example selects all elements with a class attribute value that begins with "top":
[class|="top"] { background: yellow; }
Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen(-), like class="top-text"!
π Definition β [attribute|=value] Selector: Selects elements where the attribute value is exactly the specified value or starts with the specified value followed by a hyphen (-).
CSS [attribute^=value] Selector
The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value. The following example selects all elements with a class attribute value that begins with "top":
[class^="top"] {background: yellow; }
π Definition β [attribute^=value] Selector: Selects elements where the attribute value starts with the specified value. This is a "begins with" match, similar to a prefix search.
CSS [attribute$=value] Selector
The [attribute$=value] selector is used to select elements whose attribute value ends with a specified value. The following example selects all elements with a class attribute value that ends with "test":
[class$="test"] { background: yellow; }
π Definition β [attribute$=value] Selector: Selects elements where the attribute value ends with the specified value. This is an "ends with" match, similar to a suffix search.
CSS [attribute*=value] Selector
The [attribute*=value] selector is used to select elements whose attribute value contains a specified value. The following example selects all elements with a class attribute value that contains "te":
[class*="te"] { background: yellow; }
π Definition β [attribute=value] Selector*: Selects elements where the attribute value contains the specified value anywhere within it. This is a "contains" match, similar to a substring search.
Styling Forms
The attribute selectors can be useful for styling forms without class or ID. This example demonstrates styling form elements based on their type attribute, such as text inputs and buttons:
input[type="text"] {width: 150px; display: block; margin-bottom: 10px; background-color: yellow; }
input[type="button"] { width: 120px; margin-left: 35px; display: block;}
π‘ Why this matters: This technique reduces the need for adding extra classes or IDs to form elements, keeping the HTML cleaner and making the CSS more efficient for targeting specific input types.
β Key Takeaways
The key to mastering CSS Attribute Selectors is understanding the subtle differences between the partial matching operators: ~= for whole words in a space-separated list, |= for exact or hyphen-prefixed values, ^= for any beginning match, $= for any ending match, and *= for any substring match. The exact match selector [attribute=value] is the strictest, while [attribute] is the broadest. Remember that attribute selectors are incredibly useful for styling forms by targeting input[type="text"] or input[type="button"] without needing extra HTML markup. Crucially, for the |= selector, the value must be a whole word or followed by a hyphen, not just any prefix. Mastering these selectors allows for cleaner, more semantic HTML and more precise, efficient CSS styling.
π§ Quick Revision Questions
- Which CSS attribute selector would you use to style all
<input>elements that have atypeattribute, regardless of its value? - What is the difference between the
[attribute^=value]selector and the[attribute|=value]selector, especially regarding what "starts with" means? - You want to select all elements with a
classattribute that contains the word "box" in a space-separated list. Which selector do you use? - Explain the practical benefit of using
input[type="text"]instead of a class selector like.text-inputfor styling text fields in a form. - For the
[attribute$=value]selector, will[class$="er"]match an element withclass="container"? Why or why not?
π Lecture 54-59 β JavaScript Statements, Comments, Variables, Operators, Functions, Objects & Scope
π Overview: This lecture covers fundamental JavaScript concepts including statements, comments, variables, operators, functions, objects, and scope. These building blocks are essential for writing any JavaScript program and understanding how the language executes code, stores data, and manages variable accessibility.
ποΈ Topics Covered
This lecture covers JavaScript statements with semicolons and code blocks, single-line and multi-line comments for code explanation and testing, JavaScript variables with identifiers and data types (numbers and strings), operators including arithmetic and string operators, JavaScript functions with syntax and invocation methods, JavaScript objects as containers for properties and methods, and JavaScript scope differentiating local and global variables.
π Lecture Summary
54- JavaScript Statements
A JavaScript statement tells the browser what to do. Statements are executed one by one in the same order as written. Most JavaScript programs contain many statements. Example: document.getElementById("demo").innerHTML = "Hi, Everyone."; This tells the browser to write "Hello Everyone." inside an HTML element with id="demo".
Semicolons (;) separate JavaScript statements. Add a semicolon at the end of each executable statement. When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b;
JavaScript White Space: JavaScript ignores multiple spaces. You can add white space to make your script more readable.
JavaScript Line Length and Line Breaks: For best readability, programmers often avoid code lines longer than 80 characters. If a statement doesn't fit, break it after an operator:
document.getElementById("demo").innerHTML =
"Hello Dolly.";
JavaScript Code Blocks: Statements can be grouped together in code blocks inside curly brackets {...}. The purpose is to define statements to be executed together.
55- JavaScript Comments
JavaScript comments explain JavaScript code and make it more readable. You can also use comments to prevent execution when testing alternative code.
- Single Line Comments: Start with
//. Any text between//and the end of the line will be ignored by JavaScript. - Multi-line Comments: Start with
/*and end with*/. Any text between/*and*/will be ignored by JavaScript.
Using Comments to Prevent Execution: Adding // in front of a code line changes it from an executable line to a comment. This is suitable for code testing.
56a- JavaScript Variables & Operators
JavaScript Variables: Containers for storing data values. In the example, x, y, and z are variables:
var x = 5;
var y = 6;
var z = x + y;
- x stores the value 5
- y stores the value 6
- z stores the value 11
JavaScript Identifiers: All JavaScript variables must be identified with unique names called identifiers. General rules:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter
- Names can also begin with $ and _
- Names are case sensitive (y and Y are different variables)
- Reserved words (like JavaScript keywords) cannot be used as names
The Assignment Operator: In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
JavaScript Data Types: Variables can hold numbers like 100 and text values like "John Doe". Text values are called text strings. Strings are written inside double or single quotes. Numbers are written without quotes.
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
var anum = '3.14';
Declaring (Creating) JavaScript Variables: Creating a variable is called "declaring" a variable. Use the var keyword:
var carName;
After declaration, the variable is empty (has no value). To assign a value: carName = "Volvo";
One Statement, Many Variables: You can declare many variables in one statement:
var person = "John Doe", carName = "Volvo", price = 200;
Value = undefined: A variable declared without a value will have the value undefined. If you re-declare a variable, it will not lose its value.
56b- JavaScript Variables & Operators
JavaScript Operators: You can do arithmetic with variables using operators like = and +:
var x = 5 + 2 + 3;
var x = 5; // assign the value 5 to x
var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z
JavaScript String Operators: The + operator can also add (concatenate) strings:
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2; // "John Doe"
The += assignment operator can also concatenate strings:
txt1 = "What a very ";
txt1 += "nice day"; // "What a very nice day"
Adding Strings and Numbers: Adding two numbers returns the sum. Adding a number and a string returns a string:
x = 5 + 5; // 10 (number)
y = "5" + 5; // "55" (string)
z = "Hello" + 5; // "Hello5" (string)
57- JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task. The function is executed when "something" invokes (calls) it.
Function Syntax: Defined with the function keyword, followed by a name, followed by parentheses ():
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition. Function arguments are the real values received when invoked.
Function Invocation: The code executes when "something" invokes the function:
- When an event occurs (user clicks a button)
- When invoked (called) from JavaScript code
- Automatically (self invoked)
Function Return: When JavaScript reaches a return statement, the function stops executing. JavaScript will "return" to execute the code after the invoking statement.
Why Functions? You can reuse code: Define the code once and use it many times with different arguments to produce different results:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(32);
The () Operator Invokes the Function: toCelsius refers to the function object, and toCelsius() refers to the function result. Accessing a function without () returns the function definition.
Functions Used as Variables: You can use functions the same way as variables:
var text = "The temperature is " + toCelsius(32) + " Centigrade";
58- JavaScript Objects
Object properties can be primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.
59- JavaScript Scope
Scope is the set of variables, objects, and functions you have access to. JavaScript has function scope: The scope changes inside functions.
Local JavaScript Variables: Variables declared within a function become LOCAL to the function. They can only be accessed within the function. Local variables are created when a function starts and deleted when the function completes:
// code here cannot use variable userName
function myFunction() {
var userName = "Tariq";
// code here can use variable userName
}
Global JavaScript Variables: A variable declared outside a function becomes GLOBAL. All scripts and functions on a web page can access it. The global scope is the complete JavaScript environment.
Automatically Global: If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
The Lifetime of JavaScript Variables:
- Local variables are deleted when the function is completed
- Global variables are deleted when you close the page
- Function arguments (parameters) work as local variables inside functions
- In HTML, the global scope is the window object: All global variables belong to the window object
π‘ Why this matters: Understanding scope prevents variable naming conflicts and ensures variables are accessible only where needed, which is crucial for writing secure, maintainable JavaScript code.
β Key Takeaways
The most critical concepts from this lecture are: JavaScript statements must end with semicolons and can be grouped in code blocks; variables are declared with var and can hold numbers or strings, with strings requiring quotes; the + operator concatenates strings but adding a number and string produces a string; functions are defined with the function keyword, can take parameters, and use return to output values; and scope determines variable accessibility β local variables exist only within functions while global variables exist throughout the page. Understanding these fundamentals is essential for writing any JavaScript program.
π§ Quick Revision Questions
- What is the purpose of semicolons in JavaScript statements?
- How do you declare a JavaScript variable, and what value does an undeclared variable hold?
- What happens when you add a number and a string together in JavaScript?
- What is the difference between a function parameter and a function argument?
- What is the difference between a local variable and a global variable in JavaScript, and when is each one deleted?
π Lecture 60 β JavaScript Events
π Overview: This lecture introduces JavaScript's event-driven interaction with HTML, explaining how events triggered by users or the browser can execute JavaScript code. It covers fundamental event handling, string manipulation, number properties/methods, the Math object, Date object, and JavaScript arrays, providing essential building blocks for dynamic web development.
ποΈ Topics Covered
The lecture covers JavaScript Events and HTML event handling, JavaScript Strings including length property and special characters, JavaScript Numbers with 64-bit floating point storage, precision, hexadecimal and Infinity/NaN values, Number Methods for conversion, the Math object with rounding functions and constants, Date object creation, formats, get/set methods and comparison, and JavaScript Arrays including creation, properties, methods, and associative arrays.
π Lecture Summary
JavaScript Events
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. An HTML event can be something the browser does (like a page finishing loading) or something a user does (like clicking a button or changing an input field). HTML allows event handler attributes with JavaScript code to be added to HTML elements.
π Definition β Event Handler Attribute: An HTML attribute that specifies JavaScript code to execute when a particular event occurs on an element.
Syntax:
- With single quotes:
<some-HTML-element some-event='some JavaScript'> - With double quotes:
<some-HTML-element some-event="some JavaScript">
π Example 1: Using onclick to display the current date in another element:
<button onclick="getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
π Example 2: Using onclick to change its own element's content:
<button onclick="this.innerHTML=Date()">The time is?</button>
π‘ Why this matters: Event handling is the foundation of interactive web pages, allowing dynamic responses to user actions without page reloads.
JavaScript Strings
A JavaScript string simply stores a series of characters. A string can be any text inside quotes, using single or double quotes.
π Definition β String: A sequence of characters enclosed in single or double quotes.
π Example: var carname = "Volvo XC60"; or var carname = 'Volvo XC60';
String Length: The length of a string is found in the built-in property length.
π Example:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length; // returns 26
Special Characters: The backslash escape character (\) turns special characters into string characters, preventing JavaScript from misinterpreting quotes.
π Example:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north.";
Breaking Long Code Lines: For readability, break code lines after an operator. Use a backslash to break a text string, or use string addition.
π Example with backslash: document.getElementById("demo").innerHTML = "hi \ How are you?";
π Example with string addition: document.getElementById("demo").innerHTML = "Hi," + "How are you?";
β οΈ You cannot break a code line with a backslash at the beginning of a line.
Strings Can be Objects: Normally strings are primitive values, but can also be defined as objects with the new keyword.
π Example:
var x = "Mike";
var y = new String("Mike");
// typeof x returns string
// typeof y returns object
When using == (equality operator), equal strings look equal. When using === (strict equality operator), equal strings are not equal because it expects equality in both type and value.
π‘ Why this matters: Understanding the difference between primitive strings and String objects is crucial for avoiding bugs when comparing values.
JavaScript Numbers
JavaScript numbers can be written with or without decimals, and extra large or small numbers can be written with scientific notation.
π Definition β JavaScript Number: A 64-bit double precision floating point number following the IEEE 754 standard, stored in 64 bits (fraction in bits 0-51, exponent in bits 52-62, sign in bit 63).
π Example: var x = 123e5; // 12300000, var y = 123e-5; // 0.00123
Precision: Integers are accurate up to 15 digits. The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate.
π Example of precision issue:
var x = 0.2 + 0.1; // returns 0.30000000000000004
To solve: var x = (0.2 * 10 + 0.1 * 10) / 10; // returns 0.3
Hexadecimal: JavaScript interprets numeric constants as hexadecimal if preceded by 0x.
π Example: var x = 0xFF; // returns 255
Infinity: Infinity (or -Infinity) is returned when calculating a number outside the largest possible number or dividing by zero. typeof Infinity returns "number".
π Example: var x = 2 / 0; // x will be Infinity
NaN - Not a Number: NaN is a reserved word indicating a value is not a number. Use the global function isNaN() to check.
π Example: isNaN(100 / "Apple"); // returns true
Numbers Can be Objects: Like strings, numbers can be primitive values or objects created with new Number().
π Example:
var x = 500;
var y = new Number(500);
// x == y is true (equal values)
// x === y is false (different types)
// Objects cannot be compared: new Number(500) == new Number(500) is false
π‘ Why this matters: Understanding number precision and object comparison prevents common arithmetic and logic errors.
JavaScript Number Methods
Number methods return a new value and do not change the original variable.
Table of Number Methods:
| Method | Description |
|---|---|
| toString() | Returns a number as a string |
| toExponential() | Returns a string with number rounded and written using exponential notation |
| toFixed() | Returns a string with number rounded and written with specified decimals |
| toPrecision() | Returns a string with number written with specified length |
| valueOf() | Returns a number as a number |
Converting Variables to Numbers (Global JavaScript Methods):
π Number(): Converts JavaScript variables to numbers.
π Examples:
Number(true)β 1Number(false)β 0Number("10")β 10Number("10 20")β NaN
π parseInt(): Parses a string and returns a whole number. Only the first number is returned; spaces are allowed.
π Examples:
parseInt("10.33")β 10parseInt("10 years")β 10parseInt("years 10")β NaN
π parseFloat(): Parses a string and returns a number (including decimals). Only the first number is returned.
π Examples:
parseFloat("10.33")β 10.33parseFloat("10 years")β 10parseFloat("years 10")β NaN
JavaScript Math
The Math object allows you to perform mathematical tasks.
π Key Math Methods:
- Math.random(): Returns a random number between 0 (inclusive) and 1 (exclusive)
- Math.round(): Rounds to the nearest integer
Math.round(4.7)β 5Math.round(4.4)β 4
- Math.ceil(): Rounds up to the nearest integer
Math.ceil(4.4)β 5
- Math.floor(): Rounds down to the nearest integer
Math.floor(4.7)β 4
- Math.min(): Returns the lowest value in a list of arguments
Math.min(0, 150, 30, 20, -8)β -8
- Math.max(): Returns the highest value in a list of arguments
Math Constants (8 mathematical constants):
| Constant | Returns |
|---|---|
| Math.E | Euler's number |
| Math.PI | PI |
| Math.SQRT2 | Square root of 2 |
| Math.SQRT1_2 | Square root of 1/2 |
| Math.LN2 | Natural logarithm of 2 |
| Math.LN10 | Natural logarithm of 10 |
| Math.LOG2E | Base 2 logarithm of E |
| Math.LOG10E | Base 10 logarithm of E |
JavaScript Date
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds).
Date Formats: JavaScript dates can be written as strings or numbers (milliseconds since January 1, 1970, 00:00:00).
Creating Date Objects: Date objects are created with the new Date() constructor.
π Ways to create dates:
new Date()β current date and timenew Date(milliseconds)β zero time plus millisecondsnew Date(dateString)β e.g.,new Date("October 13, 2014 11:13:00")new Date(year, month, day, hours, minutes, seconds, milliseconds)β 7 numbers
π Example: var d = new Date(86400000); // creates date for January 2, 1970
Date Methods:
- toString() β converts date to string automatically
- toUTCString() β converts to UTC string
- toDateString() β converts to more readable format
Date Formats:
- ISO Format: YYYY-MM-DD (preferred) β
new Date("2015-03-25") - Long Format: MMM DD YYYY β
new Date("Mar 25 2015") - Short Format: MM/DD/YYYY β
new Date("03/25/2015")
Date Get Methods: Used for getting a part of a date (e.g., getDate(), getDay(), getFullYear(), getHours(), getMinutes()).
Date Set Methods: Used for setting a part of a date (e.g., setDate(), setFullYear(), setHours()).
π Example (adding 4 days to current date):
var d = new Date();
d.setDate(d.getDate() + 4);
String to Date: Use Date.parse() to convert a valid date string to milliseconds.
π Example: var msec = Date.parse("March 21, 2012");
Date Comparison: Date objects can be compared using standard comparison operators.
π Example:
var today = new Date();
var anotherday = new Date("03/25/2016");
if (anotherday > today) {
result = "Today is before March 25, 2016.";
}
JavaScript Arrays
An array is a special variable that can hold more than one value at a time.
π Definition β Array: A data structure that stores multiple values under a single name, accessed by index numbers.
Creating an Array:
- Using array literal:
var cars = ["Toyota", "Honda", "BMW"]; - Using
newkeyword:var cars = new Array("Toyota", "Honda", "BMW");
Accessing Elements: By index number (starting at 0)
cars[0]β accesses first elementcars[0] = "Audi"β modifies first element
Arrays are Objects: Arrays are special types of objects. The typeof operator returns "object" for arrays.
π Difference:
- Arrays use numbered indexes:
person[0]returns "Adil" - Objects use named indexes:
person.firstNamereturns "Adil"
Array Properties and Methods:
- length β returns the number of array elements
- sort() β sorts the array
Adding Array Elements: Use the length property
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds Lemon
Looping Array Elements: Use a for loop
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
}
Associative Arrays: JavaScript does NOT support arrays with named indexes. Arrays use numbered indexes; objects use named indexes.
β οΈ Avoid new Array(): Use [] instead of new Array(). The new keyword complicates code and produces side effects.
π Example: var points = []; // Good vs var points = new Array(); // Bad
How to Recognize an Array: Since typeof returns "object", create an isArray() function:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
π‘ Why this matters: Arrays are fundamental for storing and manipulating collections of data, essential for building dynamic web applications.
β Key Takeaways
The lecture covers six core JavaScript topics essential for web development. Events enable interactive user experiences through HTML event handler attributes. Strings require careful handling of quotes using escape characters, and their primitive vs. object nature affects equality comparisons. Numbers follow IEEE 754 64-bit standard with important precision limitations, and methods like parseInt()/parseFloat() are crucial for type conversion. The Math object provides essential mathematical operations like rounding and constants. The Date object is versatile with multiple creation methods and formats, supporting get/set operations and comparisons. Arrays store multiple values efficiently, use numbered indexes, and the length property is the safest way to add elementsβalways prefer array literals over new Array().
π§ Quick Revision Questions
- What is the difference between
==and===when comparing a string primitive to a String object? - Why does
0.2 + 0.1return0.30000000000000004in JavaScript and how can this be fixed? - What is the difference between
parseInt()andparseFloat()when converting "10.33 years"? - How would you create a Date object for March 25, 2015, and then add 7 days to it?
- Why should you avoid using
new Array()to create arrays, and what is the correct alternative?