JavaScript Notes

¡Supera tus tareas y exámenes ahora con Quizwiz!

PowerTip Option: popupId

Default: 'powerTip' Type: String Description: HTML id attribute for the tooltip div.

Form Events: reset

click reset button

Object property:

variables that belong to an object. May represent attributes of the object such as name, length, value, etc.

jQuery Selectors: descendent selectors

$('#idname a') gets all a elements within an element with id="idname"

jQuery Selectors: an id:

$('#idname') gets the element with id="idname"

Creating tabbed panels: After the click function, add code to trigger a click on the first tab:

$('#tabs li:first a').click(); You can add additional functionality inside the click function to change the css to indicate which one is clicked or to change the css if JavaScript is enabled or disabled.

jQuery Selectors: a class

$('.classname') gets all elements with class="classname"

jQuery Selectors: child selectors:

$('blockquote > img') gets img tags that are child elements of a blockquote

jQuery Selectors: adjacent siblings:

$('div + h3') gets all h3 elements that immediately follow a div element

jQuery Selectors: an element:

$('h1') gets all the h1 tags on a page

jQuery Selectors: elements with a specific attribute:

$('img[alt]') gets all img tags with an alt attribute regardless of value $('img[width="100"]) gets all img tags with width="100" attribute $('img[alt^="thumbnail"]) gets all img tags with an alt attribute value that starts with "thumbnail" $('img[alt$="thumbnail"]) gets all img tags with an alt attribute value that ends with "thumbnail" $('img[alt*="thumbnail"]) gets all img tags with an alt attribute value that contains "thumbnail" anywhere within it

Event: assign an anonymous function to an event

$('selector').on(event, function(e) { //function code here; });

Event: assign a function to an event

$('selector').on(event,eventFunction); selector: element, class, id or other jQuery selector (see Chapter 4) where the event occurs event: event to assign to the selected element eventFunction: function that will run when the event is triggered. Note that there are no parentheses after the function and you cannot pass any parameters to the function

JavaScript cannot :

-Read or write files on the client machine -Write files on server machines -Close a window that it has not opened -Read information from an opened Web page that came from another server

Common uses of JavaScript:

-Rollover buttons and images, slideshows -Form validation -Calculations and feedback -Customize pages by controlling the content that is displayed, opening new windows, display alert boxes, etc. -Animated navigation

download to your own server

1 advantages: continue to work if CDN servers are down 2 disadvantage: load on server, download times, updates 3 Download latest version of jQuery from http://jquery.com/download/ 4 Right-click on minified version of latest release and save to your website.

link to a CDN server

1 advantages: don't have to download and host on your server, faster response, latest updates 2 disadvantages: have to be connected to Internet 3 generally a good idea unless you have an isolated application not connected to the Internet 4 add link in <head> section of your page: (pick one) jQuery CDN: <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script> Google CDN: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> Microsoft CDN: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.10.0.min.js"></script> based on version 3.1.0 (latest version as of this writing) Visit http://jquery.com/download/ for latest links.

Rules for Functions:

1. Reserved word function is required 2. function_name identifies the function. Rules same as for variables 3. () required, even if no parameters. 4. Parameters are optional. If used, they are arguments or data values that are passed to the function from the calling procedure. Multiple parameters are separated by commas. (param1, param2, param3) 5. The JavaScript statements that compose the function are enclosed in curly brackets {} functions should be placed in the <head> section of a page or in an external JavaScript file.

There are rules about naming variables:

1. Variable names must start with a letter, dollar sign ($) or underscore ( _ ) 2. Variable names can only contain letters, numbers, the dollar sign and the underscore. No spaces or other special characters may be used. 3. JavaScript is case sensitive, so you must be consistent with capitalization. If you create a variable called myVar, and later use MyVar, then JavaScript will treat them as two different variables. There are no hard and fast rules on capitalization but convention is to start with lowercase and capitalize the first letter of any subsequent words firstName, lastName, address, zipCode, etc. It is a very good idea to follow this convention to help you keep your names consistent. Many hours of debugging time can be attributed to simple capitalization errors. 4. There is a set of reserved words that cannot be used as a variable name. These are words that are part of the JavaScript language itself such asif, new, while, else, return, etc. See page 47 in the textbook for a complete list. 5. You should use meaningful variable names that indicate what the variable represents to make it easier to follow and debug your JavaScript code

jQuery

1. popular open-source JavaScript library 2. friendly to web designers 3. relatively small size 4. reliable and well-tested 5. large developer community 6. includes plug-ins

Adding jQuery to your page

2 methods: link to a CDN server or Add JavaScript code to use jQuery after the link to the jQuery library

jQuery Selectors: filters based on characteristics $(selector:filter) where selector can be an element, id or class and filter can be:

:even and :odd select every other element in a group :first and :last select the first or last element in a group :not selects elements that do not match the selector type :has selects elements that contain another selector :contains selects elements that contain specific text :hidden selects elements that are hidden :visible selects elements that are visible

Creating tabbed panels: Create a div for each panel and assign an id.

<div id="tab1"> ... </div> <div id="tab2"> ... </div>

Creating tabbed panels: In the JavaScript, add a click event for the <a> tags in the unordered tabs list.

<script> $('#tabs a').click(function() { ... } </script>

jQuery Plugins

A JavaScript file that works in conjunction with jQuery to perform a specific task. Directory at http://plugins.jquery.com May be free or paid Useful for things like sliders (carousels), map integration, animated navigation, etc.

Function

A function is a group of statements treated as a single unit. Functions are reusable - we can call a function multiple times within a page or from multiple pages Functions do not run until they are called

Object:

A model of something. In JavaScript, objects may refer to a data type, elements on a web page, the browser window, etc.

Tooltips

Created automatically by browser using title attribute. Can be enhances using a jQuery plugin: PowerTips

PowerTip Option: placement

Default: 'n' Type: String Description: Placement location of the tooltip relative to the element it is open for. Values can be n, e, s, w, nw, ne, sw, se, nw-alt, ne-alt, sw-alt, orse-alt (as in north, east, south, and west). This only matters iffollowMouse is set to false.

PowerTip Option: offset

Default: 10 Type: Number Description: Pixel offset of the tooltip. This will be the offset from the element the tooltip is open for, or from from mouse cursor if followMouse is true.

PowerTip Option: closeDelay

Default: 100 Type: Number Description: Time in milliseconds to wait after mouse cursor leaves the element before closing the tooltip. This serves two purposes: first, it is the mechanism that lets the mouse cursor reach the tooltip (cross the gap between the element and the tooltip div) for mouseOnToPopup tooltips. And, second, it lets the cursor briefly leave the element and return without causing the whole fade-out, intent test, and fade-in cycle to happen.

PowerTip Option: fadeOutTime

Default: 100 Type: Number Description: Tooltip fade-out time in milliseconds.

PowerTip Option: intentPollInterval

Default: 100 Type: Number Desctiption: Hover intent polling interval in milliseconds.

PowerTip Option: fadeInTime

Default: 200 Type: Number Description: Tooltip fade-in time in milliseconds.

PowerTip Option: intentSensitivity

Default: 7 Type: Number Desctiption: Hover intent sensitivity. The tooltip will not open unless the number of pixels the mouse has moved within the intentPollInterval is less than this value. These default values mean that if the mouse cursor has moved 7 or more pixels in 100 milliseconds the tooltip will not open.

PowerTip Option: manual

Default: false Type: Boolean Description: If set to true then PowerTip will not hook up its event handlers, letting you create your own event handlers to control when tooltips are shown (using the API to open and close tooltips).

PowerTip Option: smartPlacement

Default: false Type: Boolean Description: When enabled the plugin will try to keep tips inside the browser view port. If a tooltip would extend outside of the view port then its placement will be changed to an orientation that would be entirely within the current view port. Only applies if followMouse is set to false.

PowerTip Option: mouseOnToPopup

Default: false Type: Boolean Description: Allow the mouse to hover on the tooltip. This lets users interact with the content in the tooltip. Only works if followMouse is set to false.

PowerTip Option: followMouse

Default: false Type: Boolean Description: If set to true the tooltip will follow the users mouse cursor.

jQuery Process

Download files and unzip if necessary Identify files actually needed (i.e. omit documentation, demos or other files not needed for execution) and upload to your site Attach CSS files in head section after other stylesheets Link to plugin JavaScript file - AFTER jQuery file link. Modify HTML for plugin Call plugin function in your JavaScript

Creating tabbed panels: Create an unordered list with an id for the tab labels.

Each label should link to the id of the associated panel <ul id="tabs"> <li><a href="#tab1">Tab 1</a></li> <li><a href="#tab1">Tab 1</a></li> ... </ul>

Variable:

a location in memory that contains a value. You create a variable and give it a name so that you can reference that value in your JavaScript code.

jQuery Traversing Functions: find(selector)

Example (using html code above): $('#content').click(function() { $(this).find('div').css('border','red 2px solid'); } puts a red border around div1, div2, nav and gallery

jQuery Traversing Functions: closest(selector)

Example: $('img').hover(function() { $(this).closest('div').css('border','red 2px solid'); }) puts a red border around the gallery div when you mouseover an image

jQuery Plugin considerations:

Only install what you need. Plugins add overhead and may slow down your site. Reliability: -dependent on developer to fix problems and keep up to date -look at number of downloads, user reviews, release date and update dates

myVar = "This is my variable";

To assign a value to a variable use the equal sign:

var myVar;

To create a variable use the word var followed by the variable name:

var myVar = "This is my variable";

You can create a variable and assign it a value in the same statement:

var myVar1, myVar2, myVar3; or var myVar = "This is my variable", myNum = 100, myBool = false;

You can create multiple variables at the same time by separating them with commas: Note: Although it is good practice to use the var verb to create your variables, it is not strictly required by JavaScript. If you use a variable name that has not been declared, JavaScript will still create and use the variable. This is partly why it is so critical to adhere to naming standards. If you accidentally use MyVar instead of myVar, JavaScript will actually create a variable called MyVar and use it rather than giving you an error message.

jQuery

a JavaScript library that can make using JavaScript a little easier and more consistent.

Setting and reading tag attributes: .toggleClass()

adds a class to the selected element if it does not exist, removes it if it does exist: $('selector').toggleClass("classname");

Setting and reading tag attributes: .addClass()

adds a class to the selected element: $('selector').addClass("classname"); leaves existing classes there as well

Adding content to a page: .after()

adds html after the selected element's closing tag $('selector').before("content to add");

Adding content to a page: .prepend()

adds html as first child element of the selected element (just after the opening tag) $('selector').prepend("content to prepend");

Adding content to a page: .append()

adds html as last child element of the selected element (just before the closing tag) $('selector').append("content to append");

Adding content to a page: .before()

adds html before the selected element's opening tag $('selector').before("content to add");

Mouse Events: mousedown

press down on mouse button (as for a drag action)

Document/Window Events: load

browser finishes loading all of a web pages files (including images, multimedia, scripts, css, etc.)

Mouse Events: click

click and release mouse button

Mouse Events: dblclick

click and release mouse button twice. Same as click event twice. Do not assign click and dblclick to same tag or click event will run twice before dblclick. Not a normal action for a web page.

Form Events: focus

click or tab into a form field (move cursor to the field)

Setting and reading tag attributes: .removeAttr()

completely removes an attribute from a tag: $('selector').removeAttr('attribute');

Adding content to a page: .remove()

completely removes the selected element from the page $('selector').remove();

Adding content to a page: .replaceWith()

completely replaces the selected element $('selector').replaceWith("replacement content");

Document/Window Events: scroll

drag the scroll bar, click up, down, home or end key

Mouse Events: mousemove

every time a mouse moves. Can be used to track location of the mouse

Form Events: change

form field changes

Example of a function that receives and returns values:

function calcAvg(val1, val2, val3) { avg = (val1 + val2 + val3) / 3 return avg; } ans = calcAvg(10, 20, 30); The function has 3 parameters: val1, val2, and val3. When we called the function, we passed it the numbers 10, 20 and 30. This assigned val1 a value of 10, val2 a value of 20 and val3 a value of 30. The function calculated the avg (10 + 20 + 30) / 3 which equals 20 which it stored the avg variable. This value was returned to the calling statement so that at the end of the statement, the variable ans would equal 20.

To create a function definition:

function function_name(parameters) { JavaScript statements; }

To call a function:

function_name(parameters); or var x = function_name(parameters); Note: Parameters may be variables or values. Functions may or may not return a value

Object method:

functions that belong to an object. Represent things the object can do or that you can do to an object.

Document/Window Events: unload

go to another page, close browser window or tab

Creating tabbed panels: inside the click function add code to do the following:

hide all the panels $('#tab1, #tab2, ...).hide(); get the id of the tab to show from the href attribute of the link: var showId = $('this').attr('href'); show the selected id: $(showId).show();

Adding content to a page: .hide()

hides a visible element

PowerTip

i.e.: $('.gallery img').powerTip({ placement: 'sw-alt, smartPlacement: true, fadeOutTime: 250 });

jQuery Traversing Functions: parent()

locates the parent of the current element $('selector1').event(function() { $(this).parent().effect(); }); Example: $('img').hover(function() { $(this).parent().css('border','red 2px solid'); } puts a red border around the paragraph when you mouseover an image

Adding content to a page: .show()

makes a hidden element visible

Form Events: blur

move away from a form field

Mouse Events: mouseout

move mouse off of an element

Mouse Events: mouseover

move mouse over an element

To reference an object property or method, use the dot syntax:

object.property or object.method().

Keyboard Events: keypress

press a key

Keyboard Events: keydown

press down on a key (same as keypress - but fires before)

Keyboard Events: keyup

release a key

Mouse Events: mouseup

release mouse button

Setting and reading tag attributes: .removeClass()

removes the specified class from the selected element: $('selector').removeClass("classname");

Adding content to a page: .html()

retrieve html from a selection: $('selector').html(); replace content in a selection: $('selector').html("replacement content");

jQuery Traversing Functions

select elements within the current selection $('selector1').event(function() { $(this).find('selector2'); }); would find all instances of selector2 within selector1

jQuery Traversing Functions: siblings(selector)

selects all of the other elements at the same level of the DOM as the current element selector is optional. If used, it will only select siblings of the specified type $('selector1').event(function() { $(this).siblings().effect(); }); Example: $('img').hover(function() { $(this).siblings().css('border','none'); $(this).css('border','red 2px solid'); }) removes the border from all of the other images in the same paragraph and places a red border around the current image

jQuery Traversing Functions: children(selector)

selects only the immediate children of the current selection (not children of children) $('selector1').event(function() { $(this).children('selector2'); }); would find all instances of selector2 that are children of selector1 Example: $('#content').click(function() { $(this).children('div').css('border','red 2px solid'); }) puts a red border around div1 and div2 only

jQuery Traversing Functions: next(selector) nextAll

selects the next element at the same level as the current element selector is optional. If used, it will only select siblings of the specified type $('selector1').event(function() { $(this).next().effect(); }); Example: $('#div1').hover(function() { $(this).next('div').css('border','none'); $(this).css('border','red 2px solid'); }) removes the border from div2 and places a red border around div1 nextAll() returns all of the next siblings for the selector

jQuery Traversing Functions: prev(selector) prevAll()

selects the previous element at the same level as the current element selector is optional. If used, it will only select siblings of the specified type $('selector1').event(function() { $(this).next().effect(); }); Example: $('#div12').hover(function() { $(this).next('div').css('border','none'); $(this).css('border','red 2px solid'); }) removes the border from div1 and places a red border around div2 prevAll() returns all previous siblings of the current element

Form Events: submit

submit a form by clicking submit button or enter (sometimes)

Setting and reading tag attributes: .css()

to retrieve the value of a CSS property: $('selector').css('cssproperty'); to change the value of a CSS property: $('selector').css('cssproperty', 'value'); to retrieve the value of multiple CSS properties at once: chaining: $('selector') .css('cssproperty', 'value') .css('cssproperty2', 'value2') .css('cssproperty3', 'value3' . . .; object literal: $('selector').css({ 'cssproperty': 'value', 'cssproperty2': 'value2', 'cssproperty3': 'value3', . . });

Setting and reading tag attributes: .attr()

to retrieve the value of an attribute: $('selector').attr('attribute'); to change the value of an attribute: $('selector').attr('attribute', 'value');

jQuery Selectors

to select an element using jQuery, use $('selector') where 'selector' can be:

Add JavaScript code to use jQuery after the link to the jQuery library

use $(document).ready(function() { // code goes here }); ensures that the page has loaded before the JavaScript code runs alternate method (preferred) is to add the jQuery libraries and JavaScript code at the bottom of the page just before the closing body tag </body>. This prevents search engine crawlers and screen readers from having to read through all the JavaScript before the page content.

Document/Window Events: resize

user resizes browser window through min/max icon or dragging

Adding content to a page: .text()

works like html() but replaces only the text - leaves html tags alone replace text content in a selection: $('selector').text("replacement text");


Conjuntos de estudio relacionados

BIOS 1700 Exam 2: Chapter 8 Notes

View Set

French 2 Qu'est-ce qui est arrivé?

View Set

Econ 120 (Macro) - Chapter 15 Quiz Questions

View Set

Management Loes Final Exam Review

View Set

Ch 35 PrepU: Communication and Teaching with Children and Families

View Set

Kuwait, Saudi Arabia, UAE, Jordan, Yemen, Turkey

View Set

CFA 57: Derivative Markets and Instruments

View Set