JavaScript Introduction Joan Boone jpboone@email.unc.edu Slide 1 - - PowerPoint PPT Presentation

javascript introduction
SMART_READER_LITE
LIVE PREVIEW

JavaScript Introduction Joan Boone jpboone@email.unc.edu Slide 1 - - PowerPoint PPT Presentation

INLS 572 Web Development JavaScript Introduction Joan Boone jpboone@email.unc.edu Slide 1 Topics Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See


slide-1
SLIDE 1

Slide 1

JavaScript Introduction

Joan Boone

jpboone@email.unc.edu

INLS 572

Web Development

slide-2
SLIDE 2

Slide 2

Topics

Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See more/less) Part 6: Expand/Collapse Content (Accordion pattern)

slide-3
SLIDE 3

Slide 3

What is JavaScript and how is it used?

  • Slideshows: Suzie Wolf Photography, Art Wolfe
  • Form validation: awwwards Contact Us
  • Calculators: Google calculator, PX to EM conversion
  • Graphs: COVID-19 US Cases, Financial Times Markets Data
  • Google Maps

JavaScript is a scripting language for building interactive and complex experiences on the web, such as responding to user interactions and updating dynamic content on a page. Anything involving how a web page should behave when an event

  • ccurs is what JavaScript is used for. Some examples....
slide-4
SLIDE 4

Slide 4

JavaScript Runs in the Browser

JavaScript is a client-side scripting language

  • Scripts are embedded/referenced in a web page, and executed

when a page is loaded, or in response to a user action

  • It is NOT the same as the Java programming language
  • Java is compiled (and much faster); JavaScript is interpreted
  • TIOBE Programming Index

client-side

slide-5
SLIDE 5

Slide 5

JavaScript – Getting Started

Tutorials

  • w3schools: JavaScript Tutorial
  • MDN web docs: JavaScript
  • Codecademy, Coursera

Programming References (intermediate)

  • Robust Client-Side JavaScript: A Developer's Guide
  • Eloquent JavaScript
  • JavaScript for Web Designers

Plenty of free JavaScript available, but...

  • Need to understand the free stuff before you can use it
  • Free JavaScript is not necessarily good JavaScript
  • Check the dates on the web sites, demos, and examples

ECMAScript is a standard that forms the basis of JavaScript

slide-6
SLIDE 6

Slide 6

Topics

Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See more/less) Part 6: Expand/Collapse Content (Accordion pattern)

slide-7
SLIDE 7

Slide 7

JavaScript supports interaction by manipulating the Document Object Model (DOM)

  • Every HTML document has an underlying representation

called the Document Object Model

  • The DOM is a hierarchical tree structure where everything

in your HTML document is represented as a node

  • entire document
  • each element, and each attribute of an element
  • text in an element
  • The DOM is a W3C standard that defines a way to access

and change every element in an HTML document

  • “...allow programs and scripts to dynamically access and

update the content, structure and style of documents.”

slide-8
SLIDE 8

Slide 8

Document Object Model (DOM)

<html> <head> <title>My title</title> </head> <body> <a href="http://mylink.com”>My link</a> <h1>My header</h1> </body> </html>

HTML Document w3schools: HTML DOM Tree

slide-9
SLIDE 9

Slide 9

Viewing the DOM for a web page

Open the Inspector, and select the Elements tab (default view)

slide-10
SLIDE 10

Slide 10

How browsers process a web page

Your browser is an application that performs many tasks

  • Creates a model of a page (DOM and CSSOM)
  • Uses a rendering engine to render and lay out your web page based
  • n the HTML document and CSS style rules
  • Interprets and runs your JavaScript

You have to tell the browser where the JavaScript is located using <script> tags

  • Tags tell the browser that there is some JavaScript code to run, which

it then hands over to the JavaScript interpreter.

  • When the interpreter is done, control returns back to the render task

Google Web Fundamentals: Constructing the Object Model

slide-11
SLIDE 11

Slide 11

How to include JavaScript in a web page

Two ways

  • Embed JavaScript code within your page by delimiting with

<script></script> tags. Similar to embedding CSS with <style></style> tags.

  • Put JavaScript in a separate file
  • Use <script> tags with a src attribute that specifies the file
  • Example: <script src="myJavaScript.js"></script>

Where to place your <script></script> tags?

  • Recommendation: at the end of your web page, before </body> tag
  • Reduces rendering delays and may improve performance
slide-12
SLIDE 12

Slide 12

Topics

Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See more/less) Part 6: Expand/Collapse Content (Accordion pattern)

slide-13
SLIDE 13

Slide 13

JavaScript Language Concepts

  • Objects, variables, and data types
  • Object often represent elements in the Document Object Model (DOM)
  • Variables act a containers for values
  • Values have a data type: number, string, booleans, DOM element
  • Statements: separated by semi-colon (recommended, not required)
  • Operators
  • Arithmetic: +, -, *, /, ++, –, %
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: AND (&&), OR (||), and NOT (!)
  • Conditionals: if/else statements to evaluate true/false conditions
  • Iteration: repeatedly executing statements in a loop
  • Functions: built-in or user-defined
  • Events: actions that can be detected with JavaScript
  • Clicking buttons, mouse hover, input changes, page loading
slide-14
SLIDE 14

Slide 14

JavaScript Objects and Variables

Every programming language uses variables to manage and manipulate data; many languages also represent information as objects.

  • Variables are used to contain information that your script uses , e.g., numbers, text,

results of a calculation, or a reference to a DOM element

  • The browser stores the values of your variables
  • Variables are often declared using the let keyword
  • Objects are often used to represent more complex kinds of information. They have

properties (attributes) and methods (functions) to manage them.

let todaysDate = "Monday, September 14, 2020"; let dateElement = document.querySelector("#todays-date");

DOM object that represents an HTML document (your web page). Method that finds the first HTML element that has an ID selector equal to todays-date DOM object that represents the

<p> element

<p id="todays-date">date will go here</p>

HTML: Java Script:

Simple variable that contains a text string

slide-15
SLIDE 15

Slide 15 ... <p id="todays-date">date will go here</p> <script> let todaysDate = "Monday, September 14, 2020"; let dateElement = document.querySelector("#todays-date"); dateElement.textContent = todaysDate; </script> </body>

JavaScript Variables and Modifying Content

  • todaysDate is a string variable that contains the

value of the current date

  • querySelector is a DOM method that returns

an element with the specified selector

  • dateElement is a variable that references the

<p> element with the ID selector, “todays-date”

  • textContent is a property that represents the

content of an HTML element (in this case, <p>)

  • By assigning todaysDate to textContent, the

<p> contents are modified <p id="todays-date">Monday, September 14, 2020</p>

After script runs Before script runs

nc-national-parks-date.html

slide-16
SLIDE 16

Slide 16 ... <p id="todays-date"></p> <script> let todaysDate = new Date(); let dateElement = document.querySelector("#todays-date"); dateElement.textContent = todaysDate; </script> </body>

JavaScript Built-in Functions

  • JavaScript has many built-in functions to perform frequently needed tasks, so that

you do not have to write the code yourself

  • You can 'call' these functions and they will 'return' a value that you can assign to a

variable in your script

  • JavaScript Date object has many methods to retrieve and format dates
  • w3schools: JavaScript Date Objects

A new Date object is created that returns a string (or text) representation of the current date and time

nc-national-parks-date-function.html

slide-17
SLIDE 17

Slide 17

Formatting Dates

Instead of

Thu Sep 10 2020 18:14:10 GMT-0400 (Eastern Daylight Time)

Use toDateString() function

dateElement.textContent = todaysDate.toDateString(); Output: Thu Sep 10 2020

Or use month, day, year functions dateElement.textContent = todaysDate.getFullYear() + "." +

(todaysDate.getMonth()+1) + "." + todaysDate.getDate();

Output: 2020.9.10

w3schools: JavaScript Date Formats

slide-18
SLIDE 18

Slide 18

Using JavaScript to Modify Content and Style

Common scenarios

  • Provide error messages

for invalid form inputs

  • Provide user feedback
  • n long running tasks
slide-19
SLIDE 19

Slide 19

Accessing DOM to Modify Style

How to change the style of HTML elements

Change the specified CSS property for dateElement w3schools: HTML DOM Style Object <p id="todays-date"></p> <script> let todaysDate = new Date().toDateString(); let dateElement = document.querySelector("#todays-date"); dateElement.textContent = todaysDate; dateElement.style.color="whitesmoke"; dateElement.style.fontStyle="italic"; dateElement.style.fontSize="smaller"; </script>

slide-20
SLIDE 20

Slide 20

Quick exercise:

  • Add today's date

to one of your web pages

  • Modify some of

the style rules for the date

slide-21
SLIDE 21

Slide 21

JavaScript methods that do the same thing

So far, the examples have used the querySelector method to obtain a reference to an HTML DOM element, and then saved it in a variable so that it can be modified.

<p id="todays-date">date will go here</p>

<script> let todaysDate = new Date(); let dateElement = document.querySelector("#todays-date"); dateElement.textContent = todaysDate; </script>

There is another JavaScript method, getDocumentElementById, that does the same thing, and you will often see this method used in examples and documentation.

<p id="todays-date">date will go here</p>

<script> let todaysDate = new Date(); let dateElement = document.getDocumentElementById("todays-date"); dateElement.textContent = todaysDate; </script> Reference: w3Schools HTML DOM querySelector() method

slide-22
SLIDE 22

Slide 22

Finding and Fixing JavaScript Problems

Open the Inspector, and select the Console tab

Problem: no date displayed, just the placeholder text

nc-national-parks-JS-debug.html

slide-23
SLIDE 23

Slide 23

Topics

Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See more/less) Part 6: Expand/Collapse Content (Accordion pattern)

slide-24
SLIDE 24

Slide 24

HTML DOM Events

  • DOM events allow users to interact with your web page.
  • A JavaScript function can be executed when an event occurs
  • Button is clicked
  • Cursor over an element
  • Form input field is changed
  • Web page is loaded
  • Events are typically “bound” to a JavaScript function: browser

'listens' for an event, and when it occurs, a function is called to handle the event

  • w3schools: JavaScript HTML DOM EventListener
  • Complete list of HTML DOM Events
  • Different types: mouse, keyboard, frame, form, media, touch
slide-25
SLIDE 25

Slide 25

DOM Click Event to Change Image Properties

let logo = document.querySelector('img'); logo.addEventListener('click', changeLogo); function changeLogo() { logo.style.filter = "invert(100%)"; logo.style.clipPath = "ellipse(50% 45% at 50% 50%)" logo.style.transform = "scale(1.2)"; }

nc-national-parks-click-event.html

<img src=".../landscape.png" alt="NC Landscape">

HTML JavaScript

Find the first img element and assign it to logo variable Add a 'click' event listener to the logo When the logo is clicked, call the

changeLogo function

The changeLogo function changes the style properties of the logo

Click event

slide-26
SLIDE 26

Slide 26

Use Click Event to 'Toggle' Image Properties

let logo = document.querySelector('img'); logo.addEventListener('click', changeLogo); function changeLogo() { if (logo.style.filter == "invert(100%)") { logo.style.filter = "none"; logo.style.clipPath = "none"; logo.style.transform = "scale(1.0)"; } else { logo.style.filter = "invert(100%)"; logo.style.clipPath = "ellipse(50% 45% at 50% 50%)" logo.style.transform = "scale(1.2)"; } }

nc-national-parks-toggle-click-event.html If the current value of the logo filter is set to

"invert(100%)", then

reset the filter, clipPath and transform If the current value of the logo filter is “none”, then change the filter, clipPath, and transform

Click event

slide-27
SLIDE 27

Slide 27

Toggle Pattern

Toggle pattern behaves like a light switch: the switch is either on or off, and its state changes when you flip the switch up or down. Applying the toggle pattern to an HTML element on your web page allows you to change how the element is displayed when the user clicks it. Very generally, the steps include:

  • Identify the element whose attributes are toggled when clicked
  • Identify the attributes that will change when the user clicks the element.

Initially the attributes are in state A, and after the click, the attributes are in state B.

  • Associate a click event with the element, and specify a function to be called

when the element is clicked.

  • If the user clicks the element while it is in state A, change it to state B
  • If the user clicks the element while it is in state B, change it to state A

In the previous example, we saw how to change the style attributes of an image. A more common application of the toggle pattern is to show and hide content when an element is clicked.

slide-28
SLIDE 28

Slide 28

Topics

Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See more/less) Part 6: Expand/Collapse Content (Accordion pattern)

slide-29
SLIDE 29

Slide 29

Show/Hide Content

Toggle pattern allows you to show or hide content based

  • n a user action
  • Collapsible side panels: Google maps
  • Product descriptions: Amazon book summary
  • Show/Hide Wiki Table of Contents
  • Show/Hide The Guardian Topics
  • FAQs: US Patent Office FAQs
  • How it's done: use JavaScript to set the display property

someElement.style.display = “none” (hides the element) someElement.style.display = “block” (shows the element)

  • Hiding an element, which is better?

display:none or visibility:hidden

slide-30
SLIDE 30

Slide 30

See More/Less Example

see-more-less.html, see-more-less.js

slide-31
SLIDE 31

Slide 31

See More/Less Example

<div class="card1"> <img src=".../strawberries.jpg" alt="Strawberries" /> <p class="intro">Useful info about ...</p> <p id="details1">Lorem ipsum dolor sit amet, ... </p> <p id="moreLess1">See more</p> </div> let moreLess = document.querySelector('#moreLess1'); moreLess.addEventListener('click', toggleContent); function toggleContent() { let details = document.querySelector('#details1'); if (moreLess.textContent == "See more") { details.style.display = 'block'; moreLess.textContent = "See less"; } else { details.style.display = 'none'; moreLess.textContent = "See more"; } }

JavaScript

When the user clicks on See less, the

toggleContent function is called

In this scenario, the function will hide the details paragraph and change the clickable text to See more.

see-more-less.html, see-more-less.js

HTML

slide-32
SLIDE 32

Slide 32

See More/Less with Multiple Cards

see-more-less-multiple.html see-more-less-multiple.js

slide-33
SLIDE 33

Slide 33

Topics

Part 1: JavaScript Overview Part 2: Document Object Model (DOM) Part 3: Language Concepts Part 4: DOM Events Part 5: Show/Hide Content (See more/less) Part 6: Expand/Collapse Content (Accordion pattern)

slide-34
SLIDE 34

Slide 34

Accordion Pattern to Expand/Collapse Content

An accordion is a user interface pattern that displays a list of headings that can show or hide additional content when selected. Because an accordion is a collection of headings that can be in show/hide states, this behavior is

  • ften referred to as expand and collapse, similar to

the musical instrument. Important benefits

  • On mobile devices, it saves screen real estate by

collapsing content

  • On desktop, it can reduce visual complexity,

especially with complex applications

References

  • NN/g: Accordion Icons: Which Signifiers Work Best?
  • Smashing: Designing the Perfect Accordion
slide-35
SLIDE 35

Slide 35

Expand/Collapse Content Example

expand-collapse.html expand-collapse.js

slide-36
SLIDE 36

Slide 36

Expand/Collapse Example

<section id="topic3"> <header id="hdr3"> <i id="icon3" class="fas fa-plus"></i> <span>Publications</span> </header> <section id="details3"> <p>Lorem ipsum dolor ...</p> </section> </section>

expand-collapse.html, expand-collapse.js

... document.querySelector('#hdr3').addEventListener('click', toggleContent); function toggleContent(){ let icon, details; ... if (this.id == "hdr3") { icon = document.querySelector('#icon3'); details = document.querySelector('#details3'); } // Toggle display of details section and up/down caret icon if (details.style.display == 'block'){ // Is the details section showing? details.style.display = 'none'; // If yes, then hide it icon.className = 'far fa-angle-down'; // Change icon to down-caret } else { // The details section is hidden details.style.display = 'block'; // Show the details section icon.className = 'far fa-angle-up'; // Change icon to up-caret } }

HTML JavaScript

slide-37
SLIDE 37

Slide 37

Adding icons with Font Awesome

  • Font Awesome provides Scalable vector graphic (SVG) icons

that can be customized with CSS

  • Get started
  • Use Font Awesome's Free CDN (need to set up an account)
  • Search for icons -- select one, then select “Start using this icon”
  • Basic use -- how to add it in your markup
  • How used in Expand/Collapse example
  • Add icon

<i id="icon1" class="far fa-angle-down fa-lg"></i>

  • Use CSS to style color and size

i {color: magenta; font-size: 0.8em; }

  • Change icon in JavaScript from plus to minus when clicked

icon.className = "far fa-angle-up fa-lg";

slide-38
SLIDE 38

Slide 38

Exercise: Add another topic to Expand/Collapse Example