Wednesday, September 18, 2013

An Introduction to JavaScript, jQuery, and the DOM

The last two days were whirlwind of coding activity that included an introduction to JavaScript, jQuery, and the Document Object Model (DOM).

JavaScript is one of the more popular languages on the web. It has been used in tandem with HTML and CSS for quite a while and has changed little since its creation in 1995. I found this interesting because I have always thought of languages as fast-changing. In reality, only browsers and web standards (html, css) change frequently. JS is used primarily to create interactivity on a website, thus it has been called an "event handling" language.

In 1998, a technique that has since been dubbed Ajax (Asynchronous Javascript And XML) was introduced and was the dawn of "Web 2.0". Before Ajax, the page had to be refreshed in order to access additional information from the server. Every time you waste time scrolling down your facebook page and more information pops up, thank the folks at Internet Explorer for their pioneer work. JSON is the current JavaScript compatible "Ajax".

Enough history, let's get into some light lifting.

5 Primitive Types

There are 5 primitive "types" in JavaScript:

  1. string: a set of characters surrounded by ""
  2. number: a set of numbers. other languages often refer to this as "integer"
  3. boolean: logic based true and false
  4. null: lacking value, not 0
  5. undefined: An error
The basics: Variables are the most basic part of Javascript. They are used as placeholders for information. By doing this, you give the characters additional meaning so they are able to transmit information more efficiently. Below is an example

var name = "Brian"; //a statement that defines a new variable 'name' as "Brian"

console.log(name); //logs the contents of the variable 'name' into the console
This particular example is quite simple, but you could imagine a more complex variable, such as...

var era(runs, innings) = runs/innings;

console.log(era(4,2));
Here you are defining a variable 'era' which takes the parameters runs and innings. When arguments are entered in the parameters place holders and logged, the console would return 'runs' / 'innings', or in this case '2'.
Another example would use booleans. If someone is typing a phone number into a website, and you want to validate the information before submitting it, you might use the following function.

var number = prompt("What is your 10 digit phone number?\nFollow the form xxx-xxx-xxxx);
if((number.length === 12) && (number.charAt(3, 7) === "-"){
    console.log(number);
}else{
    alert("please enter a valid phone number");
}
Here we used If, the boolean "is" statement. If the number was 12 letters long and had a dash in its 4th and 8th character, we would enter the the number into the console. Otherwise an alert would pop up informing the person that they would need to enter a valid number.
If we wanted to get even crazier, we could define this as a function by doing the following...

phoneNumberFunction = function(){
var number = prompt("What is your 10 digit phone number?\nFollow the form xxx-xxx-xxxx);
if((number.length === 12) && (number.charAt(3, 7) === "-"){
    console.log(number);
}else{
    alert("please enter a valid phone number");
}}
We have now defined the function phoneNumberFunction and we can call it whenever we want to perform the task defined within the {}.
The function that we have created is"pure". This means that it does not lead to "side effects" within the rest of your code by redefining variables.

Let's look a bit more intently at functions as they are a core part of programming.
At its core a function is

  • An Input–Output Machine
  • Reusable
  • Encapsulates a piece of "functionality"
When a function is defined, any variables used within the function cannot be accessed outside of the function. Conversely, variables defined outside of a function can be used in the function. Variables used both outside and inside the function remain in their respective locations. This is called "scoping", and more specifically within JavaScript as Lexical Scoping.


jQuery and the DOM

The DOM sounds dangerous, large, and scary. It isn't. The DOM (Document Object Model) basically refers to the skeleton or 'table of contents' that your html tags form. On your computer, press Option+Command+I if you are on a Google Chrome Browser. The bottom of your browser window unfurls to reveal your "Developer Tools" If you wave your mouse over the bulleted html script that falls beneath the Elements tab you are very literally waving your mouse over the DOM.

The DOM is the browsers rendering of your code into elements that supercede characters within a document.

The reason why this isn't scary is because all of CSS is styling elements by selecting DOM elements. CSS is basic by now, so this realization was salvation. To make matters better, I learned that jQuery is a JavaScript library that selects DOM elements using CSS syntax. Hallelujah!

To access a DOM element using jQuery simply do the following. Provide a link to the latest jQuery API in your head tags. Then, in the bottom of your body tags, add your javascript and use $ or jQuery as variables to link to ids or classes of elements within your html code. Pretty basic, but from here, you can make a site interactive quickly and easily.

<head><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script></head>
<body><div id="example"></div>

test = $("#example');

</script></body>

Terms that we have learned:

var //keyword declare variable 
+ //the concatenation operator. Joins things
=== // boolean equal to. Use instead of ==
if // keyword that takes booleans. returns if true, passes if false
if else // keyword similar to if. 
else // keyword if 'if' and 'else if' are false, 'else' returns
. //access property
length //special property that finds length of a string
== // === but allows type coersion
! // "not" reverses booleans
typeof //keyword to check type of expression. bugged
.toLowerCase() // turns a string to lowercase
.toUpperCase() // turns a string to uppercase
.substring(from,to) // outputs the set of characters within a string corresponding to the defined numerical placeholders
return // completes function and breaks it
&& // boolean AND
|| // boolean OR







No comments:

Post a Comment