JavaScript

Ace your homework & exams now with Quizwiz!

What is RegExp syntax?

/pattern/modifiers;

BOM

Browser Object Model

What do you do if your function in the event handler requires params?

Use an anonymous function that calls the specified function with the params element.addEventListener("click", function(){ myFunction(p1, p2); });

How can you add a class to an HTML element in HTML5?

Use classList element! label.classList.addClass("className");

What is JavaScript

dynamically typed runs in the browser object oriented (almost everything is an object) * objects are prototype-based (not class-based)

How can you change HTML elements using DOM?

element.innerHTML= element.attribute= % this is general syntax element.setAttribute(attribute, value) element.style.property=

===

equal value and equal type

Event Object Bubbles Property

if an event's bubbles property is set to true then there must be an event handler in place to handle the event will bubble up to its parent and trigger an event handler there

Conditionals

if, else if, ..., else sytax is similar to PHP, Java, or C for the syntax, the condition to test is contained within ( ) brackets with the body contained in { } blocks

Frameworks

libraries that do a lot of work for you

Loops

loops use the ( ) and { } blocks to define the condition and the body of the loop. You will encounter the while and for loops While loops normally initialize a loop control variable before the loop, use it in the condition, and modify it within the loop.

Event Types

mouse events keyboard events form events frame events

Client-Side scripting Cons

no guarantee that the client has JS enabled idiosyncrasies b/w various browsers and OS's make difficult to test for all potential client configuration what works on one browser might not in another can be complicated to debug and maintain

Semicolons

not required

How do you make the p1 element go hidden on click?

onclick="document.getElementById('p1').style.visibility='hidden'"

no integer type

only number, this means floating-point reunding errors are prevalent even w/ integers

How do you specify that an event listener uses event capturing?

optional third parameter for addEventListener() function. True for capture, False for bubbling

Client-Side scripting pros

prossesing can be off-loaded from server to client (reduces server workload) browser can respond more rapidly to user events than a request to a remote server can interact w/ downloaded HTML

Embedded JS

refers to the practice of placing JS code within a script element

How can you get the DOM via the BOM?

window.document - same as just document

Event bubbling

works in exactly the opposite manner of event capturing: it begins by checking the target of the event for any attached event handlers, then bubbles up through each respective parent element until it reaches the HTML element the inner most element's event is handled first and then the outer

How do you add an event listener to element with id myBtn to displayDate on click?

document.getElementById("myBtn").addEventListener("click", displayDate); - doesn't overwrite existing event handlers

How can you find HTML elements using DOM?

document.getElementById() document.getElementsByTagName() document.getElementsByClassName() can also find by CSS selectors: and by HTML object collections var x = document.querySelectorAll("p.intro"); can find an HTML object collection: var x = document.forms["from1"]; for (i=0; i<x.length; i++) { text += x.elements[i].value + "<br>"; }

How can you add an event handler using DOM?

document.getElementById(id).onclick=function() { //code }

Compare document.write() vs changing innerHTML of an element

document.write() writes to the bottom of the HTML page using JS changing innerHTML can update HTML anywhere in the page

Logical Operators

&& (and) || (or) ! (not)

If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which event is handled first in capturing? In bubbling?

- Capturing: the <div> element's click event will be handled first, then the <p> element's click event - Bubbling: the <p> element's click event is handled first, then the <div> element's click event

What can you access through the window object?

- the current page's URL - the browser's history - what's being displayed in the status bar - opening new browser windows (fun fact: alert() function is method of window object)

Define the following: 1) window.innerHeight 2) window.innerWidth 3) window.open() 4) window.close() 5) window.moveTo() 6) window.resizeTo()

1) inner height of browser window (not including toolbar and scrollbar) - For IE 5-8: document.documentElement.clientHeight or document.body.clientHeight 2) inner width of browser window - For IE 5-8: document.documentElement.clientWidth or document.body.clientWidth 3) open a new window 4) close the current window 5) move the current window 6) resize current window

Define the following events for the DOM: 1) onload 2) onunload 3) onchange 4) onmouseover 5) onmouseout 6) onmousedown/up 7) onclick

1) triggered when user enters page; can be used to check browser type and version or deal with cookies: onload="checkCookies()" 2) triggered when user leaves page; can be used to deal with cookies 3) used in combo with validation of input fields onchange="upperCase()" 4) triggered when user mouses over element 5) triggered when user mouses out of element 6) truggered when mouse-button is clicked/released 7) when mouse-click is completed

DOM Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick=JavaScript

What is the following: var patt = /w3schools/i;

A RegExp with w3schools as the pattern and i as the modifier - i modifier means the search is case-insensitive

Event Object preventDefault Method

A cancelable default action for an event can be stopped using the preventDefault() method

For Loop

A for loop combines the common components of a loop: initialization, condition, and post-loop operation into one statement.

Objects Included in JS

Array Boolean Date Math String Dom

Describe DOM as a tree structure

DOM Tree Root = Document Root Node = each element in the HTML doc - element nodes - text nodes - attribute nodes All nodes share common set of properties and methods

What is a better technique to use than to edit innerHTML if you want to update HTML page?

DOM functions createTextNode(), removeChild(), and appendChild() allow us to modify an element in a more rigorous way

DOM

Document Object Model - used to create dynamic HTML - a W3C standard for accessing docs - 3 diff parts: Core DOM, XML DOM, HTML DOM - owns all other objects on the web page

Properties

Each object might have properties that can be accessed, depending on its definition. When a property exists, it can be accessed using dot notation where a dot between the instance name and the property references that property.

Frame Events

Frame events are the events related to the browser frame that contains your web page. The most important event is the onload event, which tells us an object is loaded and therefore ready to work with

Functions

Functions are the building block for modular code in JavaScript. They are defined by using the reserved word function and then the function name and (optional) parameters. Since JavaScript is dynamically typed, functions do not require a return type, nor do the parameters require type.

DOM HTML Event Attributes

HTML Event Attributes To assign events to HTML elements you can use event attributes.

JavaScript Events

an action that can be detected by JavaScript We say then that an event is triggered and then it can be caught by JavaScript functions, which then do something in response.

Arrays

In practice, this class is defined to behave more like a linked list in that it can be resized dynamically. The implementation is browser specific, meaning the efficiency of insert and delete operations is unknown. The following code creates a new, empty array named greetings: var greetings = new Array(); var greetings = new Array("Good Morning", "Good Afternoon"); var greetings = ["Good Morning", "Good Afternoon"]; To access an element in the array you use the familiar square bracket notation from Java and C-style languages, with the index you wish to access inside the brackets.

Progressive Enhancement

In this case, the developer creates the site using CSS, JavaScript, and HTML features that are supported by all browsers of a certain age or newer. To that baseline site, the developers can now "progressively" (i.e., for each browser) "enhance" (i.e., add functionality) to their site based on the capabilities of the users' browsers.

JS Locations

Inline Embedded External

Conceptual Layers

JS (Framework, e.g. JQuery) JS (Aysnchronous) JS (Validation) JS (Presentation) CSS HTML

External JS

JS allows links to external files that contain JS. JS external files have the .js extension

Objects in JS

JS is not a full-fledged OO language doesn't really have classes Doesn't support inheritace and polymorphism But does support objects objects can have constructors, properties, and methods

Arrays Vs Objects

Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes though JS typeof operator returns object. If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results. Avoid new Array() There is no need to use the JavaScript's built-in array constructor new Array(). Use [ ] instead.

Event Object

No matter which type of event we encounter, they are all DOM event objects and the event handlers associated with them can access and manipulate them. Typically we see the events passed to the function handler as a parameter named e. function someHandler(e) { // e is the event that triggered this handler. }

Constructors

Normally to create a new object we use the new keyword, the class name, and ( ) brackets with n optional parameters inside, comma delimited

Define the following in a DOM: objects property method

Objects = all HTML elements Property = value that you can get or set Method = action you can do

Methods

Objects can also have methods, which are functions associated with an instance of an object. These methods are called using the same dot notation as for properties, but instead of accessing a variable, we are calling a method. someObject.doSomething();

JavaScript Layers

Presentation layer - classes focused on the user interface Business layer - Classes that model real-world entities, such as customers, products, and sales. Data layer - Classes that handle the interaction with the data sources

Graceful Degradation

Something that was once supported is replaced with something simpler but still functional?

Submitting Forms

Submitting a form using JavaScript requires having a node variable for the form element. Once the variable, say, formExample is acquired, one can simply call the submit() method: var formExample = document.getElementById("loginForm"); formExample.submit(); This is often done in conjunction with calling preventDefault() on the onsubmit event.

DOM Access a Style Object

The Style object can be accessed from the head section of the document, or from specific HTML element(s). Accessing style object(s) from the head section of the document: var x = document.getElementsByTagName("STYLE"); Accessing a specified element's style object: var x = document.getElementById("myH1").style; x.color = "blue";

DOM addEventListener()

The addEventListener() method Example Add an event listener that fires when a user clicks a button: document.getElementById("myBtn").addEventListener("click", displayDate);

Event Object Cancelable Property

The cancelable property is also boolean and indicates whether or not the event can be cancelled

DOM Style Object

The style object represents an individual style statements

Assignment

an happen at declaration-time by appending the value to the declaration, or at run time with a simple right-to-left assignment

Validating forms

Writing code to prevalidate forms on the client side will reduce the number of incorrect submissions, thereby reducing server load. There are a number of common validation activities including email validation, number validation, and data validation.

Can you add many event handlers to ANY dom object?

Yes, even the window object

DOM Create a Style Object

You can create a <style> element by using the document.createElement() method: var x = document.createElement("STYLE"); You can also set the style properties of an existing element: document.getElementById("myH1").style.color = "red";

Event propagation

a way of defining the element order when an event occurs.

Variables

are dynamically typed, meaning a variable can be an integer, and then later a string, then later an object, if so desired. use var for variable declarations

Inline Event Handler Approach

can't put example but its inline... The problem with this type of programming is that the HTML markup and the corresponding JavaScript logic are woven together. It does not make use of layers; that is, it does not separate content from behavior.

Inline JS

refers to practice of including JS code directly w/in certain HTML attributes. Inline JS is a real maintenance nightmare

Event capturing

starts with the outer most element in the DOM and works inwards to the HTML element the event took place on and then out again. For example, a click in a web page would first check the HTML element for onclick event handlers, then the body element, and so on, until it reaches the target of the event the outer most element's event is handled first and then the inner

Listener Approach

this approach separates the html and JS layers. var greetingBox = document.getElementById('example1'); v1 greeting.onclink = alert('Good Morning'); v2 greetingBox.attachEvent('click', alert('Good Morning')); or you can replace alert('Good Morning') with a function call

What is the syntax for try-catch-finally block?

try { // block of code to try, throw errors if something goes wrong } catch(err) { // block of code to handle errors } finally { // block of code to be executed regardless of initial try and catch result }


Related study sets

87% Introduction to Fire Behavior: Influences of Topography, Fuels, and Weather on Fire Ignition and Spread Quiz

View Set

Infection & Prevention- Bioterrorism/Emergency Preparedness

View Set

Fund of Info Tech Final Exam Study Guide

View Set