front end

Calvin (Deutschbein)

Async

Cloud

Announcements

  • Out-of-sequence lecture on web technologies.
  • The cloud is used for, pretty much
    • Big Data
    • The Internet
  • Before we get into the 2nd use, we'll talk a bit about webpages

Today was going to be Flask, but better to do HTML/CSS/JS first.

Big Idea

  • Big Idea: browsers and servers
    • Browsers (clients) [front end]:
      • HTML
      • CSS
      • JavaScript
    • Servers [back end]:
      • Python (Flask/Django)
      • C (NGINX/HTTPD)
      • SQL

Today

  • Big Idea: browsers and servers
    • Front end:
      • HTML
      • CSS
      • JavaScript
    • Back end:
      • Python (Flask/Django)
      • C (NGINX/HTTPD)
      • SQL

HTML

Calvin (Deutschbein)

Async

Cloud

HTML5

  • The most basic and foundational component of the web is "HTML".
  • HTML stands for "HyperText Markup Language"
    • Hyper - contains linkages
    • Text - based in text standards like utf-8 and ascii, primarily displays text
    • Markup - contains formatting
    • Language - has a grammar, which is based on "elements".

The current, and last, version is HTML5.

WHATWG

  • The HTML standard is maintained by
    • WHATWG (Web Hypertext Application Technology Working Group), and
    • W3C (World Wide Web Consortium).
  • The standard is available here.
  • It is dense reading and not totally necessary. In practice:
    • Mozilla, Google, Microsoft, and a little bit Apple try to agree
    • WHATWG/W3C try to mediate disputes
    • Anyone trying to host a webpage tries to get along with all browsers
    • The standard is 30+ years old with a lot of baggage.
  • Takeaway - the way to tell if your HTML is correct is to view it in a browser.

Try it:

  • Create a file named "index.html"
    • index here is similar to main in some languages
  • Place some text in the file, I'll do: Hello, world!
  • Open that file in a browser.
  • For comparison, you can also create a .txt file and open that in browser.

This isn't well-formed HTML, but most browsers handle it just fine.

Elements

  • Text is not itself HTML, but is a component of HTML.
  • The atomic unit of HTML is an element.
  • Reads WHATWG: Each element is denoted in the source by a start tag, such as "<body>", and an end tag, such as "</body>".
  • I use the term "content" to refer to the inside of an element, the part between the tags, so.
  • An HTML element can be decomposed into three constituent components:
    • Start tag, denoted with '<', some element name, and '>', such as '<body>'
    • Content, which text which may contain HTML,
    • End tag, denoted with '<', a forward slash '/' some element name, and '>', such as '</body>'
  • The content is either text, another element, or some combinations of text and other elements.

Let's see an example.

Try it:

  • Go to file named "index.html"
  • We'll now place text inside a bold element, denoted with 'b' <b>Hello, world!</b>
  • Open that file in a browser.
  • For comparison, you can also create a .txt file and open that in browser.

This isn't a well-formed HTML webpage, but it is well-formed HTML.

  • I am highly confident many of you will omit the slash in the end tag. Don't do that.

Void Elements

Some HTML elements with no content will only contain a free-standing tag.

  • These have multiple names, I will call them "void elements".
    • C: void main(int argc, const char * argv[])
    • Java: public static void main(String[] args)

The most common void elements I use are 'img' for images, and 'br' for line breaks.

Indentation

  • I rarely see students write well-formed HTML, and
  • I have never seen a student write ill-formed HTML who used indentation.
  • Use indentation
  • VS Code will automatically indent HTML, and you can also use my style guide:
    • Start tags and end tags get their own lines
    • The start tag and end tag are equally indented
    • Content is indented one further level than it's containing tag.
    • If there are multiple elements within another element, the elements are equally indented.

Let's see an example.

Try it:

  • Go to file named "index.html"
  • We'll now properly indent our HTML: <b> Hello, world! </b>
  • I use double space for indentation, you may use whatever works in your editor.
  • Suppose we wish to additional italicize 'world!', how would we do that.
  • The 'em' element is most commonly used to italicize, but you can try 'i' too.

I am highly confident many of you will omit the slash in the end tag. Don't do that.

Try it 2:

  • This is a bit excessive on a two word phrase, but good practice... <b> Hello, <i> world! </i> </b>
  • Note that newlines in HTML do not necessarily correspond to new lines in a webpage.
  • How would you create the following:
    Hello,
    world!
  • Try out some elements, like 'p' and 'br'.
  • Should you use void or contentful elements?

Webpages

  • An HTML webpage has a bit more to it than just tags. <!DOCTYPE html> <html lang="en"> <head> <title>Sample page</title> </head> <body> <h1>Sample page</h1> <p>This is a <a href="demo.html">simple</a> sample.</p> <!-- this is a comment --> </body> </html>

    This is directly from the living standard and uses identation except on inline links.

Webpages

  • A well-formed HTML webpage additional contains:
    • A file header, like the one we needed in our .tsv files, which is a void tag: <!DOCTYPE html>
    • An outermost "html" element, which optionally specifies the page language: <html lang="en">
      • A "head" element, which contains descriptors of the entire webpage, such as the title that should display on the browser window/tab for the page. <head>
      • A "body" element, which contains the content of the page, formatted in HTML elements. <body>
  • This is the structure <!DOCTYPE html> <html lang="en"> <head> </head> <body> </body> </html>

Comments

  • HTML also supports comments: <!-- this is a comment -->
  • Here is an example I saw recently: <!DOCTYPE html> <!-- DON'T USE THIS PAGE FOR SCRAPING. Seriously. You'll only get your IP blocked. Read https://www.gutenberg.org/feeds/ to learn how to download Project Gutenberg metadata much faster than by scraping. --><html lang="en">
  • In general, students write too few comments. Here's a comment to remind head vs body. <!DOCTYPE html> <html lang="en"> <head> <!-- Anything here is about the webpage. --> </head> <body> <!-- Anything here is the contents of the webpage. --> </body> </html>
    • A header, like the one we needed in our .tsv files, which is a void tag: <!DOCTYPE html>
    • An outermost "html" element, which optionally specifies the page language: <html lang="en">
      • A "head" element, which contains descriptors of the entire webpage, such as the title that should display on the browser window/tab for the page. <head>
      • A "body" element, which contains the content of the page, formatted in HTML elements. <body>
  • This is the structure <!DOCTYPE html> <html lang="en"> <head> </head> <body> </body> </html>

Try it:

  • Create a webpage:
    • Named "Hello World Page"
    • With a content header "A Webpage"
    • With paragraph containing the text "Hello, World!"
    • With at least one comment.
    • Properly indented.

Once this is working, experiment more. You probably know some HTML from somewhere.

Attributes

  • An HTML element may option contain any number of "attributes" within a start or void tag.
  • Attributes make tagging much more expressive.
  • We saw our first example of an attribute with the 'html' outermost start tag. <html lang="en">
  • And of a hyperlink. <a href="demo.html">simple</a>
  • Attribute are how the 'img' element's void tag determines which image to display. <img src="imgs/01.png">
  • Which also provides an example of a multiple attribute element. <img src="imgs/01.png" width="50%">
  • Because of irregularities with how tags like 'b' and 'strong' or 'i' and 'em' work in different browsers, attributes are the preferred way to style text, usually with a span. <span style="font-weight:bold">Hello, World!"</span>

Let's see an example.

    def main():
    print("hi")

    <span style='color:#800000; font-weight:bold; '> def </span> main <span style='color:#808030; '> (): </span> <span style='color:#800000; font-weight:bold; '> print </span> <span style='color:#808030; '> ( <span style='color:#800000; '> " <span style='color:#0000e6; '>hi</span> " </span> ) </span> <!--Created using ToHTML.com on 2024-06-18 01:21:39 UTC -->

Try it:

  • Create a webpage:
    • Named "Hello World Page"
    • With a content header "A Webpage"
    • With paragraph containing the text "Hello World!" split over two lines
    • With at least one comment.
    • Properly indented.
    • Use attributes:
      • Bold the "Hello World!" text.
      • Make the header red, blue, or green.
      • Italicize the "World!" text.

Once this is working, experiment more. Try an image or hyperlink.

Grammar:

  • Element
    • Start Tag
      • Attributes
        • Attribute name
        • Attribute value
    • Content
      • Text, or
      • Element(s)
    • End Tag
  • Element
    • Void Tag
      • Attributes
        • ...

Webpage:

  • HTML
    • Head
      • Elements
    • Body
      • Elements

HTML

    HTML is a mark-up language. It was meant to:

    • Hold content
    • Describe relationships between content

    It was not meant to:

    • Define the appearance of content
    • Describe a webpage, rather than webpage contents

    Consider the following HTML snippet

    Are <p> and <strong> the same kind of thing?

Style and Atomicity

    Conflating holding content with styling content became confusing.

    Content-holding elements Style-denoting elements
    1. <p>
    2. <h1>
    3. <ul>
    4. <li>
    5. <tr>
    1. paragraphs
    2. headers
    3. lists
    4. list items
    5. table rows
    1. <b>
    2. <i>
    3. <em>
    4. <strong>
    5. <br>
    1. bold
    2. italics
    3. emphasis
    4. strong emphasis
    5. line break

Attributes

    Like elements, attributes differ in functionality

    • 'href' and 'src' are mandatory for their elements '<a>' and '<img>'
    • 'width' is an attribute for some elements yet may be used within a 'style'
    • '<p style="font-weight:bold">' seems redundant with '<b>' and '<strong>'
    • 'style' is never necessary, yet always valid.
    • 'style' has "key value pairs" instead of values.

    What is the pattern here?

Style

    Style plays by its own rules.

    • Styles may be specified inline with elements (or in a head style element)
    • Styles have an internal notation style using colons and semicolons, as well as keywords.
    • Styles almost appear to be written in another language

    That is: Do we really need n ways to to express a concept as simple as bold?

CSS

Calvin (Deutschbein)

Async

Cloud

CSS

    Style attributes and elements are written in CSS, or "Cascading Style Sheets"

    • The atomic unit of CSS is a rule, which contains
      • A selector, which references an HTML element, and
      • A declaration block surrounded with by curly braces, which contains
        • Declarations, terminated by semi-colons, which contain:
          • Properties, punctuated by colons, and,
          • Values

    When we write CSS inside HTML:

    • In style attributes, we only include the declaration block within quotation marks rather than curly braces.
    • In style elements in headers, we write full CSS rules.

Style Attributes

    • Consider the following HTML snippet with a style attribute. <p style="font-weight:bold">Coffee</p>
    • It looks like this:

      Coffee

      • Recall: In style attributes, we only include the declaration block within quotation marks rather than curly braces.
      • Recall: A declaration block... contains
        • Declarations, terminated by semi-colons, which contain:
          • Properties, punctuated by colons, and,
          • Values

Finger Binary

I am going to ask thought provoking questions and would like you to show your answer using "finger binary".


0b00 == 0

0b01 == 1

0b10 == 2

0b11 == 3

Preview Question 1

    Consider the following HTML snippet. <p style="font-weight:bold">Coffee</p>

    What is this?style="font-weight:bold"

    1. A CSS declaration block
    2. A CSS rule
    3. A CSS selector
    4. An HTML attribute

Preview Question 2

    Consider the following HTML snippet. <p style="font-weight:bold">Coffee</p>

    What is font-weight:bold

    1. A declaration
    2. A declaration block
    3. A property
    4. A rule
    5. A selector
    6. A value

Preview Question 3

    Consider the following HTML snippet. <p style="font-weight:bold;color:magenta;">Coffee</p>

    What is font-weight:bold;color:magenta;

    1. A declaration
    2. A declaration block
    3. A property
    4. A rule
    5. A selector
    6. A value

Preview Question 4

    Consider the following HTML snippet. <p style="font-weight:bold;color:magenta;">Coffee</p>

    What is font-weight:bold;

    1. A declaration
    2. A declaration block
    3. A property
    4. A rule
    5. A selector
    6. A value

Preview Question 5

    Consider the following HTML snippet. <p style="font-weight:bold">Coffee</p>

    What is font-weight

    1. A property
    2. A rule
    3. A selector
    4. A value

Preview Question 6

    Consider the following HTML snippet. <p style="font-weight:bold">Coffee</p>

    What is bold

    1. A property
    2. A rule
    3. A selector
    4. A value

Style elements

    This is an HTML webpage with a style element.<!DOCTYPE html> <html lang="en"> <head> <style> p { background: blue; color: white; } </style> </head> <body> <p>This page is just a demo.</p> </body> </html>

    • Recall: The atomic unit of CSS is a rule, which contains
      • A selector, which references an HTML element, and
      • A declaration block surrounded with by curly braces

Preview Question 7

    Consider the following HTML excerpt. <style> p { background: blue; color: white; } </style>

    What is p { background: blue; color: white; }

    1. A declaration
    2. A declaration block
    3. A property
    4. A rule
    5. A selector
    6. A value

Preview Question 8

    Consider the following HTML excerpt.

    What is p { background: blue; color: white; }

    What is p

    1. A declaration
    2. A declaration block
    3. A property
    4. A selector
    5. A value

Preview Question 9

    Consider the following HTML excerpt.

    What is p { background: blue; color: white; }

    What is { background: blue; color: white; }

    1. A declaration
    2. A declaration block
    3. A property
    4. A value

Preview Question A

    Consider the following HTML excerpt.

    What is p { background: blue; color: white; }

    What is background: blue;

    1. A declaration
    2. A declaration block
    3. A property
    4. A value

Preview Question B

    Consider the following HTML excerpt.

    What is p { background: blue; color: white; }

    What is background

    1. A declaration
    2. A declaration block
    3. A property
    4. A value

Preview Question C

    Consider the following HTML excerpt.

    What is p { background: blue; color: white; }

    What is blue

    1. A declaration
    2. A declaration block
    3. A property
    4. A value

CSS

  • Rule
    • Selector
    • {Declaration block}
      • Declarations;
        • Properties:
        • Values

Try it:

  • Create a webpage:
    • Named "Hello World Page"
    • With a content header "A Webpage"
    • With paragraph containing the text "Hello, World!"
    • With at least one comment.
    • Properly indented.
    • Style using a 'style' element in the 'head' element.
      • Bold the "Hello, World!" text, in a 'p' element.
      • Make the header red, blue, or green, in a 'h1' element.
      • Italicize the "World!" text, in a 'span' element.

CSS

Selectors can also be more sophisticated than referring to an html element.

  • A selector may refer to a comma-separated list of html elements
  • p, h1 { background: gray; color: white; }
  • A selector may refer to a class of html elements using a "." prefix
  • .bluebold { color: blue; font-weight: bold; }
  • A selector may refer to an id of an html element using a "#" prefix
  • #bookname { font-style: italics; }
  • Using a complex syntax, a selector may refer to any combination of these.

Selectors for class and id refer to HTML elements with a relevant class and id attribute.

CSS

  • Rule
    • Selector, a comma separated list of
      • HTML tag names,
        • HTML class attribute names, and
        • HTML id attribute names, among other things
    • {Declaration block}
      • Declarations;
        • Properties:
        • Values

Selector Example

    Consider the following HTML file with a style element. <!DOCTYPE html> <html lang="en"> <head> <style> p { background: blue; color: white; } .invert { background: white; color: blue; } #fancy { font-style: italics; } </style> </head> <body> <p>Normal</p> <p class="invert">Invert</p> <p class="invert" id="fancy">Both</p> </body> </html>

    This enumerates all selectors individually, and applies multiple attributes to "Both", or...

Selector Example

    Consider the following HTML file with a style element. <!DOCTYPE html> <html lang="en"> <head> <style> p { background: blue; color: white; } .invert, #both { background: white; color: blue; } #fancy, #both { font-style: italics; } </style> </head> <body> <p>Normal</p> <p class="invert">Invert</p> <p id="fancy">Fancy</p> <p id="both">Both</p> </body> </html>

    This enumerates all selectors individually, and applies multiple attributes to "Both", or...

Try it:

  • Create a webpage:
    • Named "Hello World Page"
    • With a content header "A Webpage"
    • With paragraph containing the text "Hello, World!"
    • With at least one comment.
    • Properly indented.
    • Style using a 'style' element in the 'head' element.
      • Bold the "Hello, World!" text, denoted with a class like 'bolded'.
      • Make the header red, blue, or green, with a class like 'colour'.
      • Italicize the "World!" text, with a class like 'fancy'.

Try with ids as well as classes.

Standalone CSS

It is most common to write CSS separately, in a .css file.

  • Good aesthetics: Uniform style across pages
  • Good coding: Factorization

Simply reference the relevant stylesheet using the following in the HTML head:

  • page.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <p>Normal</p> <p class="invert">Invert</p> <p id="fancy">Fancy</p> <p id="both">Both</p> </body> </html>

  • filename.css p { background: blue; color: white; } .invert, #both { background: white; color: blue; } #fancy, #both { font-style: italics; }

Usually the names are "index.html" and "styles.css"

  • Like HTML, CSS is easier with indentation. Here's one method: p { background: blue; color: white; } .invert, #both { background: white; color: blue; } #fancy, #both { font-style: italics; }

Try it:

  • Create a directory that implements a webpage:
    • Maintain the index.html webpage:
      • Named "Hello World Page"
      • With a content header "A Webpage"
      • With paragraph containing the text "Hello, World!"
      • With at least one comment.
      • Properly indented.
    • Additionally create a "style.css" stylesheet.
      • Take the css styles from the header style element index.html
      • Alter index.html to refer to the stylesheet
      • Change the header color in styles.css to make sure it worked.

This is the "hyper" in HTML, as we are now linking pages.

Something like:

index.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <p>This page is just a demo.</p> </body> </html> styles.css p { background: blue; color: white; }

They just have to be in the same directory.

    $ ls -al *.html *.css -rw-r--r-- 1 cd-desk 197121 161 Jun 20 11:05 index.html -rw-r--r-- 1 cd-desk 197121 47 Jun 20 11:06 styles.css

Aside:

  • I'm used to seeing a lot more CSS than HTML
  • Generally, CSS has to handle a lot of cases
  • It can be quite verbose
  • Most pages have relatively little content
  • Most pages (that we see) are richly designed.
  • Look at Willamette: user@DESKTOP-THMS2PJ:~$ curl https://willamette.edu/ 2>/dev/null| wc 647 2677 46650 user@DESKTOP-THMS2PJ:~$ curl https://willamette.edu/css/dist/style.css 2>/dev/null | wc 9022 28518 292022

What is that bash command doing?

Aside:

  • CSS comments are "C" style. /* This is a comment */
  • They begin with '/*' and end with '*/'
  • They can span multiple lines.
  • I don't use them a lot, but they show up when looking at other webpages, here's Willamette.edu/css/dist/style.css: .two-column-group { width: 100%; /* Chrome, Safari */ page-break-inside: avoid; /* Theoretically FF 20+ */ -moz-column-break-inside: avoid; break-inside: avoid-column; /* IE 11 */ display: table; /* Actually FF 20+ */ }
  • These comments are about browser compatibility, a common topic.

Exercise:

  • We have seen an element and an attribute named "style" and seen style defined in an external file.
  • We have not seen what happens when these conflict.
  • Using your front end skills, determine how conflicts are resolved between:
    • Style elements in headers and style files in link elements in headers
    • Style defined by element, class, and a id selectors.
    • Style in headers and style in elements.
  • Create a self-documenting HTML webpage with CSS style sheet describing conflict resolution.
  • Stage the webpage as a Github page using the following guide.
  • Find a partner and verify your findings on another device. <!DOCTYPE html> <html lang="en"> <head> <style> p { color: blue; } </style> </head> <body> <p style="color: red;">If this text is blue, a style element in the header has precedence over a style attribute in a content-holding element.</p> </body> </html>

HTML/CSS

  • HTML/CSS hold and style data.
    • CSS styling is mostly static, based on enviroment.
    • HTML styling is most unsupported, and can be indeterminate.
    • When underspecified, browser defaults determine styling.
  • What if we want to:
    • Change styles without a reload?
    • Change content without a reload?
    • Change rendering while maintaining printability?
  • Consider the case of websites with dark modes.

HTML and CSS

All of HTML/CSS gives static styling.

HTML is a

  • Element
    • Start Tag
      • Attributes
        • Attribute value
        • Attribute name
    • Content
    • End Tag
  • Element
    • Void Tag
      • Attributes
        • ...

CSS is a

  • Rule
    • Selector(s)
    • Declaration Block
      • Declaration
        • Property
        • Value
  • Attribute Value
    • Declaration Block
      • ...

JavaScript

Calvin (Deutschbein)

Async

Cloud

Scripting

  • Introduce the contentful element<script>
  • In the context of HTML/CSS, we may perform some limiting scripting.
  • <script>alert('Hello, world!');</script>
  • This scripting language is JavaScript, and it is the embedded scripting language of HTML.
  • It is the most popular language in the world BY FAR (close to double all other languages put together)
  • Most people I know that use it hate it.

Let's hear it for JavaScript, folks.

Alert

  • Hello world is a bit odd in JavaScript because it isn't really it's own language*
  • It doesn't have a print statement (how could it?) but and isn't invoked at command line or in an IDE.
  • We can use some HTML and CSS to call a JavaScript function like so. <button onclick="SomeFunc()" style="background:white;color:black;font-size:40px">Push for alert!</button>
  • This does nothing because I haven't written "SomeFunc()".

    *In addition to not being its own language, it also is its own language, but more on that latter.

Alert

  • No easy way to start, so we start in the middle.
  • We can make a JavaScript function to send a "hello world" alert.: <script type="text/javascript"> function SendAlert(){ alert('Hello World'); } </script>
  • Think: Where should this element be placed within an HTML file?

Alert

  • With both the script: <script type="text/javascript"> function SendAlert() { alert('Hello World'); } </script>
  • and the button updated to "SendAlert" <button onclick="SendAlert()" style="background:white;color:black;font;font-size:40px">Push for alert!</button>
  • I am able to see a "hello world" alert pop up in my browser.

    This may require some debugging with browser permissions - it is a pop-up after all!

Try it:

  • Create a webpage, that may be index.html but updated:
    • With a script element.
    • With an alert within the script element.
  • Determine how to make the script run:
    • When the page loads.
    • When a button element is pressed.
  • Formulate an opinion on:
    • The best place in an HTML webpage to place a script element
    • The best way to indent JavaScript codeblocks in script elements
    • The best way to indent JavaScript generally

Once this is working, experiment more. Does JavaScript work on Github pages?

JavaScript

JavaScript is a full-featured language, with the associated benefits and costs

  • JavaScript lines are semi-colon terminated (like C/C++/Java, not like Python)
  • JavaScript ignores whitespace (like C, not like Python)
  • JavaScript expressions may contain linebreaks for readability (like C, not like Python)
  • JavaScript codeblocks are joined with curly braces (like C and CSS, not like Python)
  • JavaScript has important keywords (like C and Python)
  • JavaScript is case-sensitive - use camel case.

JavaScript and Java have no relation. The language's actual name is ECMAScript.

Variables

JavaScript has many useful keywords.

  • var declares a variable. let and const are variations.
    • var is old, and bad in a complicated way. Don't worry about it.
    • const makes a constant - write all your code with constants initially.

Use Const

JavaScript has many useful keywords.

  • Change a const to a let if and only if you most update the value of the variable. <script type="text/javascript"> function SendAlert() { const greeting = 'Hello World'; alert(greeting); } </script>

Control Flow

JavaScript has many useful keywords.

  • if and for behave "as expected", but use C/C++/Java syntax (not R/Python)
    • The R/Python "for" loop is a "for each" loop, which is theoretically different in programming language theory.
  • Use if with a condition in parenthesis and a code block in curly braces. function SendAlert() { let greeting = 'Hello World'; if (navigator.userAgent.indexOf("Firefox") != -1) { let greeting = 'You have good taste.'; } alert(greeting); }
  • What do we think 'navigator.userAgent.indexOf' means?

Control Flow

JavaScript has many useful keywords.

  • Extend if with else
  • Here's an extended conditional block: function SendAlert() { let greeting = 'Whatever I guess.'; if (navigator.userAgent.indexOf("Firefox")!=-1) { greeting = 'You have good taste.'; } else if (navigator.userAgent.indexOf("MSIE")!=-1) { greeting = 'Get Firefox.'; } else { ; } alert(greeting); }

Control Flow

JavaScript has many useful keywords.

  • JavaScript for uses, say traditional "for" instead of R/Python "for each".
  • There is a three part statement include in parenthesis:
    • First, an initializing condition.
      • As a convenience but not a requirements, this usually sets a variable for testing using let
    • Then, a terminating condition. This usually is a test of the variable.
    • Then, an incrementing condition. This usually is an update to the variable.
    let text = ""; for (let i = 0; i < 5; i++) { text += "The number is " + i + "\n"; } alert(text);

Note we get to use either single or double quotes on strings.

Functions

JavaScript has many useful keywords.

  • JavaScript function creates a function that may be called by name.
    • Can be called by an HTML button.
    • Can be called elsewhere in a script.
  • It is similar enough to Python def and R function
  • They may take arguments, and have return values using a control flow return
    • 'Control flow' means isn't applied as a function, like R language 'return()'
    function triple(n) { return 3 * n; }

Note we get to use R/Python/C/Java etc. style arithmetic.

Notes

  • JavaScript numbers are all floats.
  • JavaScript has both null and undefined for case and error handling.
  • JavaScript has zero-indexed strings that can use single or double quotes.
  • JavaScript has many features that integrate with html, but no real "print".
  • Comment JavaScript by prefixing with double slash// That is, C++-style single-line comments

Dark Mode

We can use JavaScript to create dark modes

  • Create a CSS class for dark mode.
  • Create a JavaScript function that toggles the class of an HTML element.
  • Create an HTML button that calls the JavaScript function.

CSS Class

I like cyan on black.

    .dark-mode { background-color: black; color: #00ffff; }

JavaScript function

  • I use a built-in object to list everything in the HTML body. document.body.classList
  • I can add or remove a class to the body element with toggle: function toggler() { document.body.classList.toggle("dark-mode"); }
  • Recall .dark-mode { background-color: black; color: #00ffff; }

HTML elements

  • I use a button element with an onclick attribute.
  • Recall function toggler() { document.body.classList.toggle("dark-mode"); } .dark-mode { background-color: black; color: #00ffff; }

    See the example.

Try it:

  • Add a dark mode toggle to your index.html

See the example.

Standalone .js

I see JavaScript "embedded" much more than CSS

  • Most JavaScript is used on a single page, so why factor it out
  • Keeps the scripts and the elements that call/interact together

But there's a lot of .js libraries so we need to practice linking.

    <script type="text/javascript" src="scripts.js">

Something like:

index.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> <script type="text/javascript" src="scripts.js"><script> </head> <body> <p>Oh I'll need a button won't I?</p> </body> </html> styles.css .dark { /* I like cyan and black */ background-color: black; color: #00ffff; }
scripts.js function toggler() { // using a const to linebreak const bd = document.body; bd.classList.toggle("dark"); }

They just have to be in the same directory.

    $ ls -al *.html *.css *.js -rw-r--r-- 1 cd-desk 197121 337 Jun 20 13:57 index.html -rw-r--r-- 1 cd-desk 197121 97 Jun 20 13:56 scripts.js -rw-r--r-- 1 cd-desk 197121 55 Jun 20 13:55 styles.css

Try it:

  • Have index.html, scripts.js, and styles.css define a Github page.

See an example.

Coding Demo

    As time allows.

    • console.log
    • getElementById
    • .innerHTML
    • Interview questions