JavaScript

Calvin (Deutschbein)

Week 11

Cloud

Announcements

  • Recall the out-of-sequence lecture on web technologies.
  • The cloud is used for, pretty much
    • Big Data
    • The Internet
  • We did 2/3 of the web - HTML and CSS, but no JS.

We don't need to be JS pros, but we do need to be aware of JS.

Big Idea

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

Javascript "Creep"

  • Big Idea: browsers and servers
    • Browsers (clients) [front end]:
      • HTML
      • CSS
      • JavaScript
    • Servers [back end]:
      • JavaScript (Node.js)
      • SQL

Today

  • Big Idea: browsers and servers
    • Front end:
      • HTML
      • CSS
      • JavaScript
    • Servers [back end]:
      • JavaScript (Node.js)
      • SQL

RECALL: 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.

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

    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

    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.

CSS

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

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; }

Review:

  • 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?

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
      • ...

End Review

  • If there are an HTML, CSS, or conceptual questions: ask now.
  • I may not know the answers but it's good to ask!

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?) and isn't invoked at command line (Python/Bash) or in an IDE (R/Python).
  • 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 (Node), 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.
  • Advanced students: Implement a feature that reads user input, such as an echo or calculate feature.

    See an example.

  • Coding Demo

      As time allows.

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