agenda

What is JavaScript?

From Wikipedia:

"JavaScript is a scripting language most often used for client-side web development. JavaScript was influenced by many languages and was designed to have a similar look to Java, but be easier for non-programmers to work with."

Common Uses Of Javascript

Document Object Model (DOM)

The Document Object Model (DOM) is the mechanism through which javascript can manipulate an HTML page and access information about the user's browsing environment.

Javscript Basics

Lets review the Javascript essentials:

Implementation:

Adding Javascript To HTML:

Where you place your Javascripts (embedded or external) in the .html may have consequences for successful code execution.

Commenting:

As usual, comments are human readable notes that do not affect processing. Useful for declaring your authorship, for describing what the script is doing, and for designating the script organization. Remember, like HTML and CSS, javascript comments can be viewed by your clients!

Variables:

Javascript variables are places in memory where information can be stored. The are declared with the var keyword and are given case sensitive names. Assign values with a = from right to left.

//create a variable named 'username'
var username = "Shania";

//use the variable
alert("Hello, " + username + "!");

Functions:

Javascript functions are blocks of reusable code that are first defined, then invoked as many times as needed.

Troubleshooting

Javascript Libraries

Frameworks provide a pre-written codebase including several built in functions that can make rapid development of sophisticated javascripts much easier, more efficiently, and result in more browser-combatible scripts.

jQuery

jQuery is written in javascript. It may contain instructions that use a jQuery specific syntax, and may also include standard javascript instructions.

jQuery Requirements

Before using any jQuery, you will first need to load the library codebase into the browser memory. You have two options for how to do this

  1. Link to shared hosted version, for example
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>

    The advantage of this method is that many clients will already have cached version of some of these URLs, thus reducing server requests. Choose from one of several jQuery CDNs (Content Delivery Networks):

  2. Link to your own local copy
    Three main forms:
    • Uncompressed - best for reviewing the code
    • Packed - most often used for production systems
    • Minified - used for systems with Unix backend (requires GZip)
    • Download from jQuery

In addition to the basic jQuery framework, you need to include your own code either as an embedded block or linked to an external file. Be sure to load jQuery first, before your own Javascripts.

Exercise: Run a jQuery script

  1. Include the jQuery library in the <head> section of an HTML page:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
  2. Add an additional <script></script> tag to the <head> section, and place the following code inside:
     $(document).ready(function(){
    	alert("jQuery is working.");
    });
  3. Test the page: A modal dialog box with the alert message should pop up.

jQuery Patterns

You will notice this same pattern in many jQuery statements,

 $(object).action(function(){
	//javascript code
});

The common syntactical patterns used by jQuery should be carefully noted. Great care must be exercised when coding to ensure the proper placement of a multitude of nested instructions.

jQuery Patterns
  • $(object).action( );
    Most jQuery code will be contained inside this pattern. The object is the entity you are targeting, usually a valid CSS selector in quotes.

  • function(){}
    Anonymous functions are function definitions that have no name. They are automatically run, and do not require explicit invocation.

  • $(object).action(  function(){}  );
    The anonymous function will be invoked when the action occurs.

Events

A common action for jQuery scripts will involve events that can be detected and responded to by invoking anonymous functions. Most events will be based on user interaction.

Common Events:

Some events will not require user interaction to trigger. For example, the ready() event occurs as soon as the DOM is fully loaded (all html, css etc has arrived in the client browser)

Event Parameter Passing

Learning More About An Event

If you need to know more about an event that has just occurred, define an event parameter for the anonymous function. Inside the function you can access the event as an object that you can query details upon

/* include an 'event' parameter in the anonymous function... */
$("div").click(function( event ){
/* ...access event specific info using the parameter */
alert("X position is " + event.pageX );
});

Overriding Default Behaviors

Sometimes you will want javascript behaviors to override the default behavior. For example, if you want to use the click event of an anchor tag, you may want to disable the usual anchor tag click.

Add the prevent.preventDefault();

$("a").click(function( event ){
event.preventDefault();
alert("Hello World");
});

Reading / Writing

jQuery provides capabilities for reading, and changing the contents of an HTML page.

Attributes

The attributes of any element can be changed with jQuery. See a list of jQuery attribute functions

The basic pattern for adding attributes is
$('selector').attr('attributename', 'value');
Your instructor will walk you through some attribute examples

The basic pattern for reading an attribute is
var attributeValue = $('selector').attr('attributename');

CSS

The style of any element can be changed with jQuery. See a list of jQuery CSS functions

The basic pattern for altering CSS properties is
$('selector').css('property', 'value');

The pattern for reading CSS a property is
var cssPropertyValue = $('selector').css('property');

Effects

Several common javascript special effects have been standardized for reuse. See a list of jQuery effects

The basic pattern for applying effects is
$('selector').effect()
Your instructor will walk you through some effect examples

Animate is especially powerful, and has a slightly more complex syntax:

$('selector').animate({
property01: 'value',
property02: 'value'
}, speed);
Note: animate can only effect CSS properties that have numeric values.

DOM Traversal

You can traverse the DOM tree using several traversal functions:

/* style the parent tag of #some_tag */
$("#some_tag").parent().css("color", "blue");

/* you can chain the traversals as you like */
$("#some_tag").next().next().children().css("color", "blue");

The Current Element (this)

Plugins

In addition to functions native to jQuery, several developers have implemented plugins to further enhance the possibilities.

The official jQuery plugin site.

is a popular, powerful image gallery handler. Other, assorted plugin options and jQuery techniques are available:

To Do

The session 8 quiz will be open book, practical.