Web Design II
Class 03: Intro to JavaScriptTopics
- Introduction to JavaScript
- JavaScript Examples
- Class 03 Single Page Site (javascript components) Lab
Class 3 will be just right.
Introduction to JavaScript
JavaScript:
JavaScript is an object oriented scripting language used to develop organized block of commands and is often used to add dynamic components to the web.
Progressive Enhancement:
- HTML = content
- CSS = design
- JavaScript = interactivity
Complexity:
- HTML = markup language
- JavaScript = scripting language
- C = programming language
Introduction to Programming:
We will be touching on programming. There are majors and courses dedicated to programming solely. It is good to be able to “read” code. Once you know one language, others are more easy to acclimate to.
All language contains:
- Syntax = grammar
- Semantics = vocabulary
JavaScript Structure:
- Variable
- Container that holds a value
- Statement
- A single line of code containing instructions.
- Function
- Blocks of statements.
- Object
- Contains properties (variables), events (test situation [ex. onclick, and methods (functions).
Metaphorically
- Functions are like machines.
- Statements are the things the machine does.
- Variables are things the machine may interact with.
Variables:
Variables may store, update, or replace data.
Variables:
Variables may store, update, or replace data.
- Three Properties
-
- var (keyword):
- The reserve word var declares that it is a variable.
- Name:
- The name allows you to call the information whenever you need it.
- Value:
- The data that is stored in the variable. This is not necessary to declare this initially.
- Rules
- Name cannot begin with a number.
- Name cannot include spaces.
- Name cannot use anything but letters, numbers, _, and/or $ (usually $ refers to jQuery).
- Name cannot use a reserve or keyword.
-
- Camel Case:
- In order to differentiate words without spaces you can start with lowercase and then uppercase for each subsequent word. (ex. totalPrice).
- youCanActuallyReadAWholeSentenceWithoutSpaces
- muchharderifcamelcaseisnotusedEVENWORSEINALLCAPS
var dogName = ‘Paco’ ;
Variable Assignment:
When you apply a value to a variable it is called an assignment.
JavaScript Data Types:
- number: 123, -123, 1.23, etc.
- string: ‘text’
- boolean: true, false
- array: list[‘white’,’black’,’red’]
- object:document
- and more…
Scope:
- Local
- The variable only exists inside the function it is declared in
- Global
- The variable exists outside a specific function and may be used anywhere in the code.
Statements:
A statement is a single line of code that contains instructions.
- A statement may be a variable assignment, mathematical equation, function call, etc.
- Each statement ends with a semicolon (;). Think of it like a period at the end of a sentence.
Comments
Comments are used to explain what is happening in your code and are not read by the computer.
-
- //
- Used to comment out a single line.
- /* at start and then */ at the end
- Used to comment out multiple lines of code. As much as you’d like.
Operators:
Expressions: Are assignments, math, or concatenations that evaluates into a single value.
Expressions, Conditionals, and loops use operators.
Common Operators (math):
- + addition (concatenation strings)
- – subtraction
- * multiplication
- / division
- % modulo (remainder)
Postfix Operators (increment/decrement):
- ++ adds one
- — subtracts one
Logical Operators (increment/decrement):
- && and
- || or
- ! not
Assignment Operators:
- += total += 1 is same as total = total + 1
- -= total += 1 is same as total = total – 1
- *= total += 1 is same as total = total * 1
- /= total += 1 is same as total = total / 1
- %= total += 1 is same as total = total % 1
Comparison Operators (for conditionals):
- > greater than
- >= greater than or equal to
- < less than
- <= less than or equal to
- == equal to
- != not equal to
Conditions & Loops:
Conditions and loops test for a certain condition and if met run a block of code once or many times.
If Statement: tests the condition and then runs if true.
For Loop: set a variable to count the times code runs and stops when that is reached.
{
Do this
}
Else
{
Do this
}
For (as long as this is true)
{
Do this
}
While Loop: runs a loop while specified condition is true.
Do While Loop: runs without conditional then test afterwards to run again.
While (this is true)
{
Do this
}
Do
{
Do this
}
Repeat (if this is true)
Functions/Methods:
A function (method when inside an object) completes a specific task with a block of commands grouped together so that they may be called and reused.
Function Syntax:
- function
- the keyword that let’s the computer know that this a function.
- ()
- the parameters are data that is passed to the function to process.
- {}
- the code block contains all the statements the function runs.
- return
- the return is the information sent back from a function call.
- function call
- this is how you execute a function. You may also send a function data via arguments.
Objects:
Objects are data models that may contain variables, functions, and events.
Object Components:
- Properties
- properties are variables nested inside of objects.
- properties come in pairs, key and value.
- Methods
- methods are functions nested inside of objects
- methods contain blocks of code that complete a given task
- Events
- events describes the response of the object to an input.
- events respond to things such as clicking, hovering, entering text, etc.
Typical Order of Operations:
- event triggers a method
- method completes a series of instructions
- method retrieves/updates object properties
Built-in Objects:
- Browser Object Model
- Represents information regarding the browser, history, screen, etc.
- Document Object Model
- Represents information regarding the document (HTML).
- Global JavaScript Objects
- These are generic built-in commonly used objects.
Document Object Model (DOM):
The complete document is represented as an object. All elements are also represented as children objects of the DOM. JavaScript communicates with the HTML document via the DOM.
Script Syntax:
- <script>
- Holds javaScript. Either embedded or linked.
- document
- Represents the DOM.
- .dot notation represents a member operator. The text that follows is part of the object.
- write()
- This is a built in method of the DOM.
- ‘<p>Hello World</p>’
- This is the parameter (data) being sent to the write method.
document
<html>
<head>
<body>
<title>
<style>
<h1>
<p>
Events:
Events are how your user interacts with the webpage. Events trigger functions.
Event Handling:
- Select element to be interacted with.
- Indicate event type that triggers a response.
- Code that runs once triggered.
HTML Event Handler:
This is the oldest form of producing an event. It is considered bad practice but is very simple to produce.
Browser View
The time?
Traditional DOM Event Handler:
This is superior to the HTML event handler in that it allows you to separate the JavaScript from HTML.
Browser View
Click me for the date!
DOM level 2 Event Listener:
This is the newest way of attaching a JavaScript event to an element. It is the most complicated but is also the most flexible. Adobe Animate generates this code.
Browser View
Show Date
JavaScript Examples
Below you will find examples of various JavaScript Components. You are NOT required to do these. I just included them as examples if you would like to try any of them. You MUST complete the lab slide show tutorial at the very bottom of this page.
Read More JavaScript Tutorial Video
Read More:
Add a read more button that will reveal more information when clicked.
HTML:
- <p>
- The text.
- <span id=”dots”>
- A span that has the … when the rest of the text is hidden.
- <span id=”more”>
- A span that holds the hidden text.
- <button onclick=”readMoreFunction()” id=”rmBtn”>
- A read more button that runs the readMoreFunction when clicked.
CSS:
- #more {}
- display: none;
- Turn off the more text by default.
JavaScript:
- function readMoreFunction() {
- Function that will run when the button is pressed.
-
- var dots = document.getElementById(“dots”);
- Variable that stores the … text.
- var moreText = document.getElementById(“more”);
- Variable that stores the more text.
- var btnText = document.getElementById(“rmBtn”);
- Variable that stores the read more button.
- if(dots.style.display === “none”) {
- If the … is not visible.
-
- dots.style.display = “inline”;
- Turn on the … using inline.
- btnText.innerHTML = “Read more”;
- Change the button text to read more.
- moreText.style.display = “none”;
- Turn off the read more text.
- else {
- Else do the following
-
- dots.style.display = “none”;
- Turn the … off.
- btnText.innerHTML = “Read less”;
- Change the button text to read less..
- moreText.style.display = “inline”;}}
- Turn on the read more text.
Read More HTML
Accordion JavaScript Tutorial Video
Accordion:
Expands and collapses sections.
HTML:
- <button>
- Use the button tag to make a clickable object.
- class=”accordionBtn”
- Add a class attribute to target the object.
- <div>
- Create a div that will contain what will be revealed.
- class=”accordionPnl
- Add a class attribute to target the panel that will be revealed.
CSS:
- .accordionBtn {}
- background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; text-align: left; border: none; outline: none; transition: 0.4s;
- Style the accordion button.
- .active, .accordionBtn:hover {}
- background-color: #ccc;
- Style the accordion button when it is active and on hover.
- .accordionPnl {}
- padding: 0 18px; background-color: white; display: none; overflow: hidden;
- Style the accordion panel so it is hidden initially.
JavaScript:
- var accBtn = document.getElementsByClassName(“accordionBtn”);
- Store all of the elements with the acccordionBtn class name into an array named accBtn.
- var i;
- Create an array to count in the for loop.
- for (i = 0; i < accBtn.length; i++) {
- For each of objects in accBtn run the following code.
-
- accBtn[i].addEventListener(“click”, function() {
- Add an event listener that listens for click and runs a function.
-
- this.classList.toggle(“active”);
- Turn on or off the object highlighting if selected.
- var accPnl = this.nextElementSibling;
- Store the current accordion panel into accPnl variable so it can be controlled.
- if (accPnl.style.display === “block”) {
- If the display is set to block (visible).
-
- accPnl.style.display = “none”;}
- Turn the display off.
- else {
- Else the display is probably set to none (off).
-
- accPnl.style.display = “block”;}});}
- Turn it on using block.
Accordion HTML
Accordion CSS
Accordion JavaScript
Modal JavaScript Tutorial Video
Modal:
A popup.
HTML:
- <button>
- Use the button tag to make a clickable object.
- class=”modalBtn”
- Add a class attribute to target the object.
- <div class=”modal” id=”modal”>
- Create a div with a class and id that will contain what will be revealed.
- <div class=”modalContent”>
- Create a div with a class and id that has the content.
- <p class=”closeBtn”>
- The close button.
CSS:
- #modalBtn {}
- margin: 25px; padding: 10px; font-size: 1.25em; font-weight:700;
- Style the modal button.
- .modal {}
- display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.25);
- Style the modal popup.
- .modalContent {}
- background-color: white; margin: 15%auto; padding: 20px; border: 1px solid rgb(75, 75, 75); width: 80%;
- Style the content of the modal.
- .closeBtn {}
- color: rgb(104, 104, 104); font-size: 1.5em; font-weight: bold; text-align: center;
Style the close button.
- .closeBtn:hover, .closeBtn:focus {}
- color: black; text-decoration: none; cursor: pointer;
- Style the content of the modal.
JavaScript:
- var modal = document.getElementById(“modal”);
- Store the modal element in the variable named modal so it can be accessed.
- var modalBtn = document.getElementById(“modalBtn”);
- Store the modal button element in the variable named btn so it can be accessed.
- var closeBtn = document.getElementsByClassName(“closeBtn”)[0];
- Store the close button element in the variable named closeBtn so it can be accessed.
- modalBtn.onclick = function() {
- Apply a function when the button is clicked.
-
- modal.style.display = “block”;}
- Turn on the modal from display: none to display:block.
- closeBtn.onclick = function() {
- Apply a function when the button is clicked.
-
- modal.style.display = “none”;}
- Turn off the modal from display: block to display:none.
- window.onclick = function(event) {
- Apply a function when the window is clicked.
-
- if (event.target == modal) {
- If the modal is the thing clicked.
-
- modal.style.display = “none”;}}
- Turn off the modal from display: block to display:none.
Modal HTML
Modal CSS
#modalBtn {
Modal JavaScript
Tabs JavaScript Tutorial Video
Tabs:
Tabs inside of a page that you can reveal.
HTML:
- <button>
- Use the button tag to make a clickable object.
- class=”tableBtn”
- Add a class attribute to target the object.
- <div class=”tabContent”>
- Create a div with a class that will contain what will be revealed.
CSS:
- .tabBtn {}
-
background-color: rgb(148, 147, 121); color: white; float: left; border: none; outline: none; cursor: pointer; padding: 14px16px; font-size: 17px; width: 20%;
- Style the tab.
- .tabBtn:hoverl {}
-
background-color: rgb(80, 79, 57);
- Highlight the tab on mouse hover.
- .tabContent {}
-
color: black; background-color: rgb(224, 224, 207); display: none; padding: 50px; text-align: center;
- Style the content revealed by the tab.
- .tabActive {}
-
color: black; background-color: rgb(224, 224, 207);The style of the opened tab.
JavaScript:
- function openTab(tabClicked) {
- Apply a function when the window is clicked.
-
- var i;
- Counting variable for the For loops.
- var tabContent = document.getElementsByClassName(“tabContent”);
- Store the tab contents in this variable so it may be accessed in the code.
- for (i = 0; i < tabContent.length; i++) {
- For each object in stored in the tabContent variable run the following code.
-
- tabContent[i].style.display = “none”;}
- Turn off the tab content from display: block to display:none.
- var tabBtns = document.getElementsByClassName(“tabBtn”);
- Store the tab buttons in this variable so it may be accessed in the code.
- for (i = 0; i < tabBtns.length; i++) {
- For each object stored in the tabBtns variable run the following code.
-
- tabBtns[i].classList.remove(“tabActive”);
- Remove the tabActive class so none are active.
- if(tabBtns[i] == tabClicked) {
- If the current tab button is the same as the tab that is clicked run the code below.
-
- tabBtns[i].classList.toggle(“tabActive”);
- Toggle the tabActive class so that the tab button appears on.
- tabContent[i].style.display = “block”;}}}
- Turn the tabContent on via block so the tab content is not visible.
- document.getElementById(“defaultOpen”).click();
- Click whatever tab button as the defaultOpen id attribute so that the tab is on to start.
Tabs HTML
<div class=“tabContent”>
<div class=“tabContent”>
<div class=“tabContent”>
Tabs CSS
Tabs JavaScript
Greeting JavaScript Tutorial Video
Greeting:
This code will check the time of day and type out a greeting.
HTML:
- <h3 id=”greeting”>
- This heading will be targeted and replaced using JavaScript.
CSS:
- #greeting {}
-
font-size: 3em; font-family: ‘Segoe UI’, Tahoma, Geneva, Verdana, sans-serif;
- Style the greeting.
JavaScript:
- var today = new Date();
- Store today’s date into a variable.
- var hourNow = today.getHours();
- Find the current hour and store that.
- var greetingTxt;
- Variable that will hold the generated greeting.
- if(hourNow > 18) {
- If the hour is greater than 18 out of 24.
-
- greetingTxt = “Good Evening!”;
- Greeting is good evening.
- else if(hourNow > 12){
- If the hour is greater than 12 out of 24.
-
- greetingTxt = “Good Afternoon!”;
- Greeting is good afternoon.
- else if(hourNow > 0){
- If the hour is greater than 0 out of 24.
-
- greetingTxt = “Good Morning!”;}
- Greeting is good morning.
- else {
- Else just do the following…
-
- greetingTxt = “Welcome!”;}
- Greeting is welcome.
- var i;
- Variable counter.
- var txt = greetingTxt;
- Variable to transfer the greeting to the typewriter.
- var speed = 50;
- Variable that determines the speed of the typing.
- function typeWriter() {
- Function that will create the typing effect.
- if (i < txt.length) {
- If the counter is less than the length (number of characters) in the text.
-
- document.getElementById(“greeting”).innerHTML += txt.charAt(i);
- Select the element with the greeting id and enter the next character of the greeting.
- i++;
- Increment the counter (add one to).
- setTimeout(typeWriter, speed);}}
- Wait to run the function again after the specified amount in the speed variable.
- typeWriter();
- Actually start the function that writes out the greeting.
Greeting HTML
Greeting CSS
Greeting JavaScript
Class 03 Single Page Site (javascript components) Lab
Single Page Site (javascript components) Lab:
Solid HTML code made the page well-structured, semantic and ADA compliant. The CSS has added design aesthetics as well as made the it responsive. Now it is time to add some pizzazz with interactive elements utilizing JavaScript. In this lab we will add at least one interesting interactive element such as an accordion, drop-down, popup, etc.
You will be graded on the following:
- Basic Document & File Structure:
- Master folder created with correct sub folders.
- All files named and placed correctly.
- Basic HTML and CSS structure produced.
- JavaScript Code:
- Code functions correctly.
- All coding and formatting errors removed
- Interactivity
- Buttons follow the usability standards.
- Aesthetics:
- Interesting and appealing design.
- Descriptive and well-written text
Resources:
- Assignment Video Tutorials
- You may watch these tutorial videos below to help you complete your assignment.
- Assignment Lab Materials
- You may download the lab materials used here: wd2_week03_labmateraisl.
Lab Tutorial Slideshow
This tutorial will review the HTML and CSS that was covered in Web Design I.
Wait! Before you go!
Did you remember to?
- Read through this webpage
- Watch the videos
- Submit Class 03 Single Page Site (javascript components) Lab on Blackboard