JavaScript and jQuery Introduction

JavaScript and jQuery Introduction

Introduction

JavaScript is an actual programming language that is interpreted and run by your browser. It makes a webpage interactive and dynamic instead of just a rigid page that doesn't change once it's loaded. You can use it to send and recieve bits of information without having to load another page.  It allows you to drag and drop elements, or react to clicks and hovers. You can even use it to make an in-browser game.

It is syntactically similar to Java. It requires semi-colons at the end of each statement. However, it does not have rigid data types. Any variable can store data of any type - sort of like python. In fact, a variable can even store a function or actually contain nothing (undefined).

jQuery

Many of the ways you would routinely use JavaScript are made drastically easier by using the jQuery library. jQuery provides a simplified interface for finding elements in a webpage, easy methods for modifying styles and appending content, simple functions for doing making fluid transition animations, and a reliable way to send and recieve data like JSON to a server asyncronously.

Setting Up jQuery

the jQuery .js file simply needs to be included in the pages scripts. This can be done really easily by using Google's hosted libraries. One of the advanatages to using Google's hosted libraries is that the file may already be cached in the user's browser.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Using the JavaScript Console

The JavaScript console is extremely useful. In Chrome, it can be revealed by going to Options > Tools > Developer Tools > Console (the furthest tab to the right). This provides an interactive console. You can type a line of JavaScript, and you can read any errors or the output of any console.log() command in the JavaScript ran up until this point.

Searching for Elements

Elements in a webpage can be searched for extremely easily with jQuery. The the string used in the search is practically identical to the specifiers in CSS. ID's are specified with a # sign, classes are preceeded by a ., you can search for a specific drilldown by seperating specifiers by spaces, and seperate searches can be done simulteneously be using a comma.

results = $("#main .gallery img"); // gets img tags in gallery classes in main ID

Modifying Elements

Contents

To replace the contents of an element, you can use either the html or text method, where text will strip tags. Both the html and text methods can return the current contents of an element if the function is called without any parameters.

var titleText = $("#main h2.title").text() //gets the text in the heading tag
$("#main h2.title").text("New Title!"); //replaces the text in the heading tag

To add to the current contents at the end. Note that there is also a prepend method that adds to the beginning.

$("#main").append('<div class="new">New Stuff</div>');

Styles

Style information can be set and retrieved similar to the contents of an element. Select the element then use the css jQuery method to either retrieve or set the style by calling .css() with only the attribute or by calling it with both the attribute name and a value. It can also be called with a dictionary as an argument, with key value pairs corresponding to the css attribute names and values.

$("#comments .new").css("color", "#C00"); //adds to elements' style="" attribute

Another way to change the style of an element would be to simply toggle a class on the element, then defining the CSS in a stylesheet. jQuery provides a lot of methods for this, like checking whether an element has a class (hasClass), adding a class (addClass), switching back and forth whether an element has a class (toggleClass), and removing a class (removeClass).

Other style information can be easily retrieved and set in jQuery, like heights, widths, margins, positions on page, and scoll positions.

Animation

Styling can be easily animated with jQuery effects, which is possibly one of its most useful features.

Some animations are predefined all having to do with hiding and revealing elements, like: hide(), .slideDown(), slideUp(), fadeIn, fadeOut

$(".oops").hide()

Alternately, an animation can be completely customized with very little code by using the animate method. Many css values can be animated except colors, which requires jQuery UI. The first argument to animate is a dictionary of attributes and values for the styles, and the second argument is the duration of the animation in milliseconds.

$("#main").animate({ width: "50%" }, 1000 );

Events

Events are what make JavaScript truly interactive. They allow your script to react to changes.

Essentially, events are simply functions that are called whenever something happens. For example, if you want to make a webpage do something in response to a click, you simply say attach a function to an elements click event.

function reactionToEvent() {
$(this).text("CHANGED!"); //change calling elements text
}

$("#mybutton").click(reactionToEvent);

Which is the same thing as:

$("#mybutton").click(function() {
$(this).text("CHANGED!"); //change calling elements text
});

There are all kinds of events available. One of the most common ones used in jQuery is to delay actions until the document is loaded by using: $(document).ready(handler)

Here are some of the other most common ones:
click, mousedown, mouseup - React to button presses
hover - Reacts to the mouse entering or leaving an element
keydownkeypress - Reacts to keyboard button presses like hotkeys.
change - Reacts to form elements being altered like inputs, select boxes, and radio buttons

There are many more events available than that, but they may require the use of the jQuery bind method.

Sending and Receiving JSON

JSON is an awesome tool for sending structured data to and from a server. You can retain the data types of any JavaScript variable, like a dictionary that has arrays that have all kinds of different data types. It turns the data types into a structured and linear string, which is a process called serializing. For example, a CSV is a sort of a way of serializing a two dimensional array.

var stuff = {
numbers: [0,1,3,6],
on: True,
comment: "Hello"
};

function successResponse(responseData) {
console.log(responseData); // dumps the data to browser's console
}
function failResponse() {
console.log("There was an error");
}

// send the stuff in JSON by POST to localhost and run the above function when done
$.ajax({ type: "POST", url: 'localhost', dataType: 'json', data: stuff, success: successResponse }).fail(failResponse);
Evan Boldt Tue, 03/26/2013 - 00:29