HTML Introduction - Ngee Ann Polytechnic PDF

Document Details

ThumbUpLime4921

Uploaded by ThumbUpLime4921

Ngee Ann Polytechnic

null

null

Tags

html web development website programming

Summary

These slides provide an introduction to HTML, covering fundamental concepts, elements and attributes. The slides are suitable for secondary school students .

Full Transcript

HTML Last update : 13/10/2024 What makes a website? HTML ○ HyperText Markup Language ○ Structure and content CSS ○ Cascading Style Sheets ○ Styles and colours JS ○ JavaScript ○ Logic and functionality What makes a website? HTML HTML/CSS HTML/CSS/JS Demonstratio...

HTML Last update : 13/10/2024 What makes a website? HTML ○ HyperText Markup Language ○ Structure and content CSS ○ Cascading Style Sheets ○ Styles and colours JS ○ JavaScript ○ Logic and functionality What makes a website? HTML HTML/CSS HTML/CSS/JS Demonstration Pure HTML document Minimal HTML document Hello world! My cat is very grumpy Minimal HTML document HTML document A HTML document is made up of elements ○ Hello world! ○ My cat is very grumpy Each element comprises of ○ opening tag ○ closing tag ○ Content HTML element: anatomy Rendering HTML documents Browser reads and renders HTML document from top to bottom Rendering elements Two roads diverged in a yellow wood, And sorry I could not travel both Rendering elements ***** is break | Goes to next And sorry I could not travel both Rendering elements Two roads diverged in a yellow wood, ***** is division And sorry I could not travel both Rendering elements Two roads diverged in a yellow wood, And sorry I could not travel both ***** is paragraph Common HTML elements ul, ol unordered list/ ordered list li list h1, h2, h3, h4, h5, h6 the different sizes of heading a achor >> creating links to other web pages or resources img display img input user input table display in rows and cols Lists Courses available If its the thing will not be a numbered list but bullet points Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology id and class attributes Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology Section heading Countries Asia Singapore Sunny island North America Mexico Tacos Text formatters Used to change how the text is displayed on the browser strong ○ Place emphasis on text ○ Browsers usually bold the text emphasis ○ Place emphasis on text ○ Browsers usually italicise the text Text formatters Two roads diverged in a yellow wood, And sorry I could not travel both Image Image Image alt >> The text will appear even if there’s no pic Image alt text Image External image AnchorHyperlink reference Ngee Ann Poly Homepage Ngee Ann Poly Homepage Code along Pair hands-on Void elements Consists of a single tag ○ Does not have a corresponding closing tag Comments This is a comment Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology (windows) - ctrl + / (macOS) - cmd + / Checkpoint How many HTML elements are there? Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology 5 elements. Opening n closing are counted as one. What are src, alt, href, and target? Ngee Ann Poly Homepage et >> used to specify where the linked document should open when a user clic >> cypher link reference Why does the image not load? End of slides Appendix Void elements HTML Last update : 13/10/2024 What makes a website? HTML ○ HyperText Markup Language ○ Structure and content CSS ○ Cascading Style Sheets ○ Styles and colours JS ○ JavaScript ○ Logic and functionality What makes a website? HTML HTML/CSS HTML/CSS/JS Demonstration Pure HTML document Minimal HTML document Hello world! My cat is very grumpy Minimal HTML document HTML document A HTML document is made up of elements ○ Hello world! ○ My cat is very grumpy Each element comprises of ○ opening tag ○ closing tag ○ Content HTML element: anatomy Rendering HTML documents Browser reads and renders HTML document from top to bottom Rendering elements Two roads diverged in a yellow wood, And sorry I could not travel both Rendering elements ***** is break | Goes to next And sorry I could not travel both Rendering elements Two roads diverged in a yellow wood, ***** is division And sorry I could not travel both Rendering elements Two roads diverged in a yellow wood, And sorry I could not travel both ***** is paragraph Common HTML elements ul, ol unordered list/ ordered list li list h1, h2, h3, h4, h5, h6 the different sizes of heading a achor >> creating links to other web pages or resources img display img input user input table display in rows and cols Lists Courses available If its the thing will not be a numbered list but bullet points Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology id and class attributes Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology Section heading Countries Asia Singapore Sunny island North America Mexico Tacos Text formatters Used to change how the text is displayed on the browser strong ○ Place emphasis on text ○ Browsers usually bold the text emphasis ○ Place emphasis on text ○ Browsers usually italicise the text Text formatters Two roads diverged in a yellow wood, And sorry I could not travel both Image Image Image alt >> The text will appear even if there’s no pic Image alt text Image External image AnchorHyperlink reference Ngee Ann Poly Homepage Ngee Ann Poly Homepage Code along Pair hands-on Void elements Consists of a single tag ○ Does not have a corresponding closing tag Comments This is a comment Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology (windows) - ctrl + / (macOS) - cmd + / Checkpoint How many HTML elements are there? Cybersecurity & Digital Forensics (CSF) Data Science Immersive Media Information Technology 5 elements. Opening n closing are counted as one. What are src, alt, href, and target? Ngee Ann Poly Homepage et >> used to specify where the linked document should open when a user clic >> cypher link reference Why does the image not load? End of slides Appendix Void elements JS (and the DOM) Last update : 27/10/2024 What is JS? JavaScript Add logic and functionality to HTML, allowing users to perform complex interactions JavaScript Scripting language ○ Run using an interpreter Dynamically typed ○ Variables can be reassigned to store any type Variables const >> var cannot change let >> var can change var (❌ avoid this) Variables: const Declares constant variables Cannot be reassigned const foo = "Happy"; foo = "Sad"; // TypeError: Assignment to constant variable. Declaring a variable Variables: let Can be reassigned let foo = "Happy"; foo = "Halloween"; console.log(foo); // Halloween Functions: anatomy function () { // function body } function squareNum(num) { return num * num; } querySelector Change the content of a paragraph (text cont Hello const myHeading = world! document.querySelector("h1"); myHeading.textContent = "Happy halloween!"; Element selectors getElementById getElementsByClassName getElementsByName getElementsByTagName getElementsByTagNameNS querySelector querySelector: anatomy document.querySelector() Select elements using a CSS selector string ○ type ○ class ○ id Most versatile selector querySelector: usage document.querySelector("button") ○ Select an element with the type from the document Important practice Always leave your browser console open when developing with JS Allows us to see error messages so we can fix our code Hands-on Activity 1 Document Object Model Browser has a internal representation of the HTML document Stores information about elements in an object ○ Known as the Document Object Model (DOM) We can modify the page via the DOM, using the API it provides DOM tree html Hello world! head body title section Hello world h1 p DOM tree document Hello world! html head body Hello world title section h1 p DOM tree Document is the root node document Search for elements from the root html head body title section h1 p DOM tree section world p \n style=color: world red; DOM tree Element node can contain section ○ Text node ○ Attribute node p \n style=color: world red; Adding HTML elements to the DOM 1. Create element 2. Append element to the DOM Add elements: anatomy document.createElement().appendChild() Add elements const newItem = document.createElement("li"); const textContent = document.createTextNode("New item"); newItem.appendChild(textContent); document.querySelector("#list").appendChild(newItem) ; Add elements document.createElement("li") Create an element Element is now an orphan, not a child of any element on the DOM document.querySelector("#list").appendChild(newIt em) Append the element to another existing element Element is no longer orphaned, it is the child of It now part of the DOM, with document as its ancestor Event listeners: adding interactions to the page Interactions are a 2 way thing ○ User performs an action to our page ○ Page provides some feedback to our user User actions on our page will generate events ○ Clicking ○ Mouse move ○ Typing Can tell the DOM element to listen to a specific event ○ Once the event happens, trigger a function to provide feedback Event listeners: clicking on a button btn.addEventListener("click", function () { // }) ○ Listen for a "click" event on the btn element ○ Run the function supplied Event listeners: anatomy.addEventListener(, ) Interaction: add element to page on button press function addItem() { Add list item const newItem = document.createElement("li"); const text = document.createTextNode("New item"); newItem.appendChild(text); document.querySelector("#list").appendChild(newItem Default ); item } Default item const btn = document.querySelector("#add"); btn.addEventListener("click", addItem); Where to put JS 1. Inside a script element 2. In a separate JS file Where to put JS within HTML Before the end of the body element Happy halloween Trick or treat alert("jumpscare"); End of slides Appendix Can we put JS in the head? Color change Can we put JS in the head? // color.js const btn = Change color Putting JS in the head HTML is parsed from top to bottom, the body has not been loaded into the DOM Since the script is loaded first in the head, it fails to reference the DOM However, we can fix this by telling JS to defer execution until the DOM has loaded DOMContentLoaded Event triggers when the browser has finished parsing everything on the page ○ All the elements will exist in the DOM at this point document.addEventListener("DOMContentLoaded", function () { const btn = document.querySelector("button"); }); Refer to color-change-external example More events Event Purpose Listener scroll Mouse scroll wheel used Element mouseover Cursor goes over element Element keydown Key has been pressed Element DOMContentLoade Page has finished loading Element d resize Attribute Window Delete elements const btn = document.querySelector("#btn"); Remove header btn.addEventListener("click", () => { const header = document.querySelector("#header"); header.remove(); }); Now you see me Delete elements 1. Select the element 2. Call its delete method Delete elements: anatomy.remove() Delete elements header.remove(); ○ Remove the selected element from the DOM Input element Last update : 27/10/2024 Input element Allows users to perform interactions which requires them to provide data ○ Text ○ Image ○ Color ○ Date Input element: example Name (4 to 8 characters): Obtaining input value Obtain the value of the input element using the.value property document.querySelector("#name").value End of slides Appendix Input validation JavaScript Last update : 03/11/2024 Today we are learning about the features in the JS programming language JavaScript Scripting language ○ Run using an interpreter Dynamically typed ○ Variables can be reassigned to store any type Console messages: console.log console.log("hello") Outputs a message to the web console Similar to the Python's print function Comments Denoted with // Can or for multiline comments // comment Primitives JS has 7 primitive data types null undefined boolean number string... Objects Denoted with curly braces {} Stores a collection of related data, known as properties Each property is stored as a key-value pair Similar to how dictionaries work in Python { : } Objects: accessing properties Dot notation ○. ○ car.make Bracket notation ○ [] ○ car["make"] Objects: accessing properties const car = { make: "Ford", model: "Mustang", year: 1969, }; console.log(car.make); // Dot notation console.log(car["make"]); // Bracket notation Objects: key restrictions Object keys can only be strings or numbers const obj = { foo: "foo", 0: "bar", "foo-bar-27": "baz", "27-foo-bar": "foobar", }; Objects: key as number Numerical keys are converted to strings ○ Can specify key in either numeric or string form console.log(obj); // "bar" console.log(obj["0"]); // "bar" Objects: key with symbols Can only use bracket notation if key has symbols ✔️console.log(obj["foo-bar-27"]); // "baz" ✔️console.log(obj["27-foo-bar"]); // "foobar" ❌ console.log(obj.foo-bar-27); // ReferenceError: bar is not defined ❌ console.log(obj.27-foo-bar); // SyntaxError: Unexpected number Arrays Denoted by square brackets [] ○ const xs = [1, 2, 3] Access values by indices ○ console.log(xs); // 2 ○ console.log(xs[xs.length - 1]); // 3, access last item Arrays: mutation Change element as position using indices const xs = [1, 2, 3]; xs = 27; // Set the element at index 1 as 27 console.log(xs); // [1, 27, 3] Arrays: mutation Append to the back with push const xs = [1, 2, 3]; xs.push(4); // adds an element at the back of the list console.log(xs); // [1, 2, 3, 4] Arrays: non-mutation concat allows us to merge arrays Does not mutate the existing array ○ Returns a new array const xs = [1, 2, 3]; console.log(xs.concat([4, 5, 6])); // [1, 2, 3, 4, 5, 6] console.log(xs); // [1, 2, 3] Arrays: non-mutation Can create new arrays with concat ○ Able to maintain original value of initial array const xs = [1, 2, 3]; const ys = xs.concat(4); console.log(xs); // [1, 2, 3] console.log(ys); // [1, 2, 3, 4] Strings Denoted with single ' or double inverted commas " ○ "Hello" ○ 'world' Can access characters with indices const st = "Hello world"; console.log(st); // e Strings: template literals Use backticks ` to create a template literal const st = `Hello world`; Include ${ } to evaluate JS expressions const product = "apples", quantity = 27; const st = `There are ${quantity * 2} ${product}`; console.log(st); // There are 54 apples Equality === (✔️use this) == (❌ avoid this) Equality === Also known as triple equals Used to check if primitives are equal ○ "foo" === "bar" // false ○ 27 + 7 === 34 // true ❌ Unable to check object equality ○ [1, 2, 3] === [1, 2, 3] // false ○ {"foo": "bar"} === {"foo": "bar"} // false ○ Checks referential equality Objects: values Object values can also be other objects, as well as functions const person = { name: "Billy Mays", // string products: ["OxiClean", "Orange Glo", "Kaboom", "Zorbeez"], // array catchphrase: function () { // function return "Hi, Billy Mays here with another fantastic product"; }, }; console.log(person.products); // "Orange Glo" console.log(person.catchphrase()); // "Hi, Billy Mays here with another fantastic product" Objects: nested values const report = { data: { id: "1337", type: "report", attributes: { title: "XSS in login form", state: "new", }, }, }; console.log(report.data.attributes.title); // "XSS in login form" Control flow if... else can be used to alter the flow of our code if (foo === 7) { console.log("foo is 7"); } else if (foo === 42) { console.log("foo is 42"); } else { console.log(`foo is ${foo}`); } Ternary operator Shorter form of if.. else statements Best used for conditions involving only if and else Ternary operator // classic if.. else const foo = 27; if (foo === 7) { console.log("foo is 7"); } else { console.log(`foo is ${foo}`); } // ternary const foo = 27; foo === 7 ? console.log("foo is 7") : console.log(`foo is ${foo}`); Ternary operator: complicated flows Can use for more complicated control flows ○ But risks becoming quite unreadable if (foo === 7) { foo === 7 console.log("foo is 7"); ? console.log("foo is 7") } else if (foo === 42) { : foo === 42 console.log("foo is 42"); ? console.log("foo is 42") } else { : console.log(`foo is $ console.log(`foo is ${foo}`); {foo}`); } Functions: anatomy 2 ways to declare functions, standard or ES6 function identity(x) { // standard way return x; } const identity = (x) => { // ES6 arrow function return x; }; End of slides Appendix Console messages console.info console.warn console.error console.debug First-class functions In JS, functions are first-class objects They can be passed as function arguments addEventListener("click", handleClick) ○ From our previous week's examples, the handleClick function is passed as an argument to the addEventListener function First-class functions Functions can also have a function as its return value function foo() { console.log("Hello foo"); } function bar() { return foo; } bar()(); // "Hello foo" // bar() returns the function foo // we then call the returned function foo using the additional () First-class functions Functions can also be assigned to variables function foo() { console.log("Hello foo"); } const bar = foo; bar(); // "Hello foo" Events Continued Last update : 03/11/2024 In this section, we learn more about how event listeners deal with events Event listeners: recap User actions on our page will generate events ○ Clicking ○ Mouse move ○ Typing Can tell the DOM element to listen to a specific event ○ Once the event happens, trigger a function to provide feedback Event listeners: recap We need to provide a function to addEventListener function handleClick() { alert("click"); } document.querySelector("#img").addEventListener("click", handleClick); Event listener functions: past example function logKey(event) { const keyPress = event.code; document.querySelector("#output").textContent = keyPress; } document.addEventListener("keydown", logKey); Event listener functions: receiving events When the event listener function is called, an event object is passed as an argument ○ Contains additional details about the event that happened function handleClick(event) { // display cursor coordinates document.querySelector("#x").textContent = event.offsetX; document.querySelector("#y").textContent = event.offsetY; } document.querySelector("#img").addEventListener("click", handleClick); Event listener functions The event function argument is optional ○ Only need to include if necessary ○ Do we need contextual details about how the event was triggered? What was the specific key pressed? Which part of the page was clicked? Event properties Each event will have different properties, check MDN docs Demo: input-event Can get the current value of the input field with the "input" event End of slides Appendix Keydown vs input event Use keydown to listen to specific keypresses ○ What was the key that was just pressed Use input to know what's the current value in the input element ○ What is the entire string in the input field MDN's list of possible events Further reading Event listeners is actually a pretty deep topic that's cool to explore, here's some recommended areas to read up on if you want to take it a step further Adding multiple listeners to the same element Removing event listeners Event bubbling Prevent default Flexbox Today we are learning about creating responsive layouts with flexbox Flexbox One-dimensional layout model Used to layout items along an axis ○ row (X axis, horizontal) or ○ column (Y axis, vertical) Before using flexbox Here, we have a section that contains 3 article elements After using flexbox By making the element a flexbox, this allows each to become a flex-item All the flex-items will be laid out along the same axis By default, the flex- direction will be row (X axis, line all the flex-items along the same row) Flex items If more elements are added, they will continue to get added on the same axis Each element will shrink so that the others can fit Flex direction: row Each flex-item is laid out in a row.container { display: flex; flex-direction: row; } Main axis Flex direction: column Each flex-item is laid out in a column.container { display: flex; flex-direction: column; } Main axis Flexbox properties Flexbox has a lot of properties you can explore to help you layout and align items flex-direction ○ Direction in which the flex-items are laid out flex-wrap ○ The flex-items exceeding the size of the container will go to a new line instead of shrinking justify-content ○ Distribute extra space between flex-items align-items ○ Align items according to the cross axis (perpendicular from the main axis) gap ○ Space between each flex-item etc... Flexbox model Flex-items can be aligned according to 2 axis Main axis - the direction which the flex-items are laid out in Cross axis - runs perpendicular to the main axis ○ Further allows us to align each flex-item within the container ○ Refer to CSS-Tricks cheat sheet in subsequent slide (optional) Watch a video on flexbox CSS Flexbox introduction (10 min) https://www.youtube.com/watch?v=GteJWhCikCk Flexbox: CSS-Tricks CSS-Tricks has a great cheat sheet with visual representations of flexbox properties Good reference for how to use each property Check out the link for the cheat sheet https://css-tricks.com/snippets/css/a-guid e-to-flexbox/#aa-flexbox-properties Activity: hands-on with Flexbox Froggy (20 min) Try out some hands-on exercises by playing Flexbox Froggy https://flexboxfroggy.com/ Activity: Flexbox froggy The game has 3 main elements 1. Pond 2. Frog 3. Lilypad Activity: Flexbox froggy The blue pond represents the flex container Activity: Flexbox froggy The frog represents the flex-item within the container Activity: Flexbox froggy The lilypad represents where the frog needs to be, after the flexbox property has been applied Activity: Flexbox froggy (20 min) (needs submission) Play flexbox froggy and complete at least the first 13 here Click levels to show list ○ Take a screenshot to indicate completed levels of completed levels Exercise (5 min) (needs submission) Align the boxes ○ Files required are in the "exercise" folder, called align-boxes ○ Align the boxes according to the screenshot below ○ Do not use margin to space out the boxes ○ You should rely solely on flexbox properties (view CSS-Tricks cheat sheet for more) Hints We need to center align the flex-items on the cross axis Each item needs to have a gap in between (how much space is up to you, just need separation) Submission 1. Create a folder with the following a. Screenshot of node installation b. Align-boxes exercise c. Screenshot of flexbox froggy score 2. Name the folder according to your tutorial number, student ID, and name 3. Zip up the folder 4. Submit the zip file Summary of tasks 1. Install Node.js a. Refer to Week 5.1 slide deck 2. Complete at least first 13 levels of Flexbox Froggy 3. Complete the exercise for align-boxes 4. Submit a screenshot for Node.js, flexbox froggy, and the HTML file for the bonus task a. Refer to previous slide for submission criteria End of slides Appendix Flexbox Froggy If you have time, complete the remainder of the levels Should only take 10 min or so There's also an intermediate mode you can enable in the settings, which disables hints Responsive web design: further concepts to explore Grid can be used to layout items on a 2D plane ○ Flexbox is more suited for layout on a 1D plane Multicol (column-count) is better suited to distribute text content into different columns ○ Grid and flexbox are more for aligning elements Media queries can be used to apply different CSS properties according to the current page size ○ Allows different styles to be applied when the screen is resized More useful resources Comprehensive flexbox guide https://css-tricks.com/snippets/css/a-guide-to-flexbox/ Comprehensive grid guide https://css-tricks.com/snippets/css/complete-guide-grid/ When to use flexbox VS when to use grid https://ishadeed.com/article/grid-layout-flexbox-components/ Multi-page websites Pages A website is usually split into multiple webpages ○ Home page ○ About us ○ Contact us Each page is split by its function ○ Don't want to overwhelm users by having everything on the same page ○ Group similar content within a single page ○ Page usually performs a single function Create a post Watch a video View list of products Pages - separate files Each separate page is usually a different file ○ Next week, we will explore React.js will allow us to build Single Page Applications (SPAs) ○ Websites are still overwhelmingly made up of multi-page files We will be using Next.js to build our React.js app, which will still create our app as multiple pages Web servers A web server is a program ○ It serves up different pages of a website ○ User requests for a particular page (HTML file), web server will send the file to user in the response if it exists Don't confuse it with the general term "server", which will refer to the machine itself ○ When we talk about server in the duration of this module, we are referring to server as a web server program Client-server Give me about.h tml Server u t. h tm l o Client Send ab index.h tml Browse Give me about.h r exam.ht tml m l robots.t xt d 404 n ot Sen found Popularity of JavaScript Allows us to dynamically create interfaces Enables us to build reusable components Reused components allow a consistent experience across the website Separation of page into logical components Border Navbar Sidebar Main content Modern web development No longer want to simply build websites page by page Want to break a page down into components Share components across the pages Modern web frameworks Designed to build page components ○ Components can then be put together to form a page Usually needs to be written in a special type of template file (e.g..jsx.svelte.vue) that is a superset of JavaScript ○ A transpiler will convert this into plain old JavaScript End of slides Appendix React.js internals If you to know how React.js works in detail and don't mind diving into the internals, check out the tutorial from Next.js (link below) ○ It is actually pretty rare for React developers to even understand how React works ○ Please note that this can be relatively painful and arduous if you do not already have experience using modern web frameworks In this module, we will not be covering how React.js works, mostly how to use the features React.js ○ We do not always need to know how it works to use something https://nextjs.org/learn/react-foundations Node.js and npm JS engine Each browser comes with a JS engine ○ Allows JS to be run on webpages Chrome has V8 JS engine Firefox has SpiderMonkey JS engine Node.js JS runtime that allows JS to be run outside of the browser Powered by the V8 JS engine Has no access to browser object since there is no DOM Comes with features unavailable in the browser ○ API to interface with network (HTTP), filesystem, etc Node Package Manager (NPM) Node.js comes bundled with a package manager called NPM Allows users to install JS libraries published by others ○ E.g. React.js, lodash, etc Similar to how Python is bundled with pip to install Python libraries

Use Quizgecko on...
Browser
Browser