Lect02 Css Js1
Lect02 Css Js1
Lecture 2
Web Layouts
Introduction to JavaScript (JS)
List of topics
How could we distribute boxes across box container evenly (equal space between each
box)?.
The display property specifies the display behavior (the type of rendering box) of an element.
The four values you most often will see are:
● inline: Displays an element as an inline element, spanning the width/height of its
content. Any height and width properties will have no effect.
● block: Displays an element as a block element. It starts on a new line, and takes up the
width of the parent container.
● initial: Initial or default display value.
● none: The element is completely removed.
● flex: Displays an element as a block-level flex container.
● grid: Displays elements in a 2-dimensional grid.
Flexbox
display: flex;
● makes an element a "flex container", items inside automatically become "items" -
by default, starts as a row
justify-content: flex-end; (flex-start, space-around,...)
● indicates how to space the items inside the container along the main axis
align-items: flex-end; (flex-start, center, baseline,...)
● indicates how to space the items inside the container along the cross axis
flex-direction: row; (column)
● indicates whether the container flows horizontally or vertically (default row)
flex-wrap: wrap; (no-wrap, ...)
● indicates whether the container's children should wrap on new lines
Basic properties for flex items
There are also cases when you will need to add flex properties to flex items rather than the
flex container
flex-grow: <number>
● Defines a proportional value to determine whether a flex items can grow (what amount
of the available space inside the container it should take up).
flex-basis: 20%; (3em, 50px,...)
● indicates the default size of an element before the extra space is distributed among the
items
align-self: flex-end; (flex-start, center, stretch,...)
● indicates where to place this specific item along the cross axis
positioning Elements
position: static
● Default value. Elements render in order, as they appear in the document flow
position: fixed
● Puts an element at an exact position within the browser window
position: absolute
● Puts an element at an absolute position based on the location of the element's parent container
position: relative
● Makes children positioned relative to the parent container
● Handy for sticking a footer to the bottom of a page, for example
position: sticky
● A "hybrid" - toggles between relative and fixed depending on scroll position
Responsive Web Design (RWD) is an approach to web design that ensures a website looks good and
functions well on all devices, from desktops to smartphones.
Layouts that use relative Images, videos, and other media CSS media queries allow
units (like percentages) are designed to scale designers to apply specific
rather than fixed units (like proportionally, maintaining their styles based on device
pixels) to ensure content visual integrity as the layout adapts characteristics, such as
adapts to different screen to varying screen dimensions. screen size, resolution, and
sizes. orientation, ensuring the
website's visual presentation
is optimized for each user's
environment.
Benefits of Responsive Design
Media queries are a CSS technique used to apply styles based on the characteristics of the device
or viewport.
To create responsive designs that adapt to different screen sizes and orientations, improving user
experience on various devices.
Basic Syntax
@media (max-width: 600px) {
@media (condition) {
body {
/* CSS rules */ background-color: lightblue;
} }
}
Types of Media Queries
Media Features:
Client-side script:
Code that runs on
the user's computer
and does not need a
server to run (just a
web browser!).
Client-side JavaScript runs as part of the browser's process to load HTML and
CSS (e.g., from a server response). This JavaScript usually manipulates the
page or responds to user actions through "event handlers."
Why JavaScript and not another language?
Popularity.
The early web browsers supported it as a lightweight and flexible way to add
interactivity to pages.
Microsoft created their own version, called JScript, but the open source browsers
(notably Firefox and Chromium) and Adobe (via Flash and ActionScript) put all
their effort into JavaScript and standardized it as ECMAScript.
Note: If you want to run anything other than JavaScript in the browser… it's Very
Hard™. There's a long list of languages that people have "transpilers" for --
basically converting one language to JavaScript. These are often error-prone, and
have potential performance problems.
JS: Adding Behavior to HTML/CSS
HTML can embed JavaScript files into the web page via the <script>
tag.
<!DOCTYPE html>
<html>
<head>
<title>WPR</title>
<link rel="stylesheet" href="style.css" />
<script src="filename.js"></script>
</head>
<body>
... contents of the page...
</body>
</html>
Today: Following Along
As an interpreted programming language, JS is great to interact with a line at a time
(similar to Python, but very different from Java). Where do you start?
The easiest way to dive in is with the Chrome browser's Console tab in the same
inspector tool you've used to inspect your HTML/CSS.
Until we learn how to interact with the HTML DOM with JS, we recommend
experimenting with the following code examples using this console to get comfortable
with the basic syntax and behavior.
Our First JavaScript Statement: console.log
Used to output values to the browser console, most often used to debug JS
programs. You can think of this as System.out.println in Java or print in
Python.
console.log("message");
A JS function that pops up a dialog box with a message - not ideal in practice, but
sometimes a recommended debugging tool when first learning JS.
alert("message");
// single-line comment
/**
* multi-line
* comment
*/
// template
let name = expression;
// examples
let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";
Variables are declared with the let keyword (case-sensitive). You may also
see var used instead of let - this is an older convention with weaker scope
-> DO NOT USE var anywhere
Code Quality Tips: Use camelCasing for variable (and function) names
“Types” in JavaScript
● Integers and real numbers are the same type (no int vs. double).
All numbers in JS are floating point numbers.
● Same operators: + - * / % ++ -- = += -= *= /= %= and
similar precedence to Java.
● Many operators auto-convert types: "2" * 3 is 6
● NaN ("Not a Number") is a return value from operations that have an
undefined numerical result (e.g. dividing a String by a Number).
String type
While Strings in JS are fairly similar to those you'd use in Java, there are a few
special cases that you should be aware of.
Practice: Write a function named repeat that accepts a string and a number of
repetitions as parameters and returns the String concatenated that many times.
For example, the call of repeat("echo...", 3) returns
"echo...echo...echo...". If the number of repetitions is 0 or less, return an
empty string.
Special Values: null and undefined.
let foo = null;
let bar = 9;
let baz;
Note: This takes some time to get used to, and remember this slide if you get
confused later.
Arrays
Why is this important to be aware of? You'll be writing programs which use variables
and conditional logic. Knowing what is considered truthy/false and how types are
evaluated (at a high level) can make you a much happier JS developer.
// example
function myFunction() {
console.log("Hello!");
alert("Your browser says hi!");
}
The above could be the contents of basics.js linked to our HTML page
Statements placed into functions can be evaluated in response to user events
JS Function vs. Java Method
function repeat(str, n) {
let result = str;
for (let i = 1; i < n; i++) {
result += str;
}
return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
// template
<script src="filename"></script>
// example
<script src="example.js"></script>
JavaScript code used in the page should be stored in a separate .js file
JS code can be placed directly in the HTML file's body or head (like CSS),
but this is only for small projects. In more serious projects, you
should separate content, presentation, and behavior (“separation of
concerns” rule).
Event-driven programming
Name Description
For starters, the HTML attributes. This HTML above is a DOM object (let's call it
puppyImg) with these two properties:
● puppyImg.src -- set by the browser to images/puppy.png
● puppyImg.alt -- set by the browser to "A fantastic puppy photo"
When are elements accessible?
window.onload = function() {
// access DOM elements here
}
// or (BETTER)
window.addEventListener('load', (event) => {
// access DOM elements here
});
DOM elements are available when page is loaded. Listen to the load event of
the window object.
Another possible way is to put JS code at the end of <body> but it’s not the
best practice. (still being done by many programmers)
The <button>
<button id="my-btn">Go!</button>
function handleFunction() {
// event handler code
}
function openBox() {
// 1. Get the box image
let box = document.getElementById("mystery-box");
// 2. Change the box image's src attribute
box.src = "star.png";
}
Common Types of JavaScript Events
Name Description
click A pointing device (e.g. mouse) has been pressed and released on
an element
addEventListener("click", openBox);
addEventListener("click", openBox());
Event handler syntax
addEventListener("click", openBox);
addEventListener("click", openBox());
Answer: openBox() will execute right away (not waiting for the event to fire)