Newbie Hacker Guide

If you’re new to programming, we strongly recommend that you start by building a personal website. It doesn’t have to be fancy (just some information about you, links to social media, and a basic design will work), but it will give you experience designing a basic “app” and publishing it for the world to see! Check out Pranav and Derek’s for some design inspiration. We reccommend you read through the HTML/CSS and Git guides for this project. Before anything else, though, read about text editors.

If you’ve had some basic experience and feel comfortable with your ability to build and deploy an app look at some of the more advanced guides.

The internet has a lot of helpful reasources to help you sort through troubleshooting your code and learn new code. Three extremely helpful reasources are: Code Academy, Bento box, and Stack Overflow. Check out these websites now to familiarize yourself with their setup.

Text Editors

Getting Your Code on Paper

If you already have a favorite text editor (Note: Word, Google Docs, or any other word processing software are NOT text editors. They are documents software, and that is a BIG DIFFERENCE), feel free to use that. For the purposes of learning, we recommend Sublime Text. To do so, please click on the “Download” bar at the top and download either Sublime Text 3 or the newest version of Sublime Text 2. Once you have it downloaded, you can use it to create plain-text files for whatever kind of language you are using. Name your file with the correct extension (.html for HTML, .js for JavaScript, .hs for Haskell, etc) and Sublime should automatically recognize it and highlight it appropriately.

You should also install the Sublime Package Manager, which lets you extend the functionality of Sublime Text with pre-written packages. To install the package manager, visit this site and follow the instructions for your version of Sublime (Sublime Text 2 or Sublime Text 3).

Then you can visit here for an easy description of how to use the package manager, and come here to look for some cool packages to install (you can also search from Sublime itself).

You can also check out a few more advanced Sublime tips.

Web Design 101

Building your first (pretty) website

Welcome coders of all levels! Feel free to check out the Code Weekend website for a quick overview of HTML, CSS, and Javascript. In case you missed it, here’s how the three come together to make websites work:

What are HTML, CSS, and Javascript?

HTML (Hypertext Markup Language) is like the backbone of any webpage. It’s where we add in all the information - what they webpage actually displays as well as information about the page itself such as its title.

CSS dresses up this information. Most (but really all) webpages link to a CSS file that stores information on how a browser should display the information it recieves in the HTML. While it is possible to add CSS code into the HTML document, it is never done as it makes it nearly impossible to keep track of code and also slows down the page.

Javascript is the fun part. It does dynamic things with your webpage, updates content on the fly and can animate just about anything. We’ll talk about this later.

HTML

HTML stands for HyperText Markup Lanuage. It is HyperText because it hyperlinks you to other text. It is a markup language because it is not written as plain text. It is marked up into the form of HTML elements called tags.

What is the DOM?

Every webpage is built in the HTML DOM (Document Object Model). This means that every element in the HTML code is an element (or a Node, the mathematical kind - not to be confused with Node.JS). So we could call this paragraph an element in the DOM; the same is true of any of the images and pretty much everything else here.

The DOM

CSS

Does your website have style?

CSS is a really funny language with a lot of oddities. I’ll go through a few of them here:

Cascading

CSS stands for “Cascading Style Sheets”. Go back to the idea of a DOM, and envision a website as a tree. “Cascading” just means that the same element can have the same property set to different values in different places (perhaps in different CSS files), but the most specific setting is the one followed on the page.

For example, your CSS may set all body text in the body tag to blue, but text surrounded by an h1 tag is set to black. The text will end up being black, since the h1 tag is more specific than the body tag.

Margins and Padding

Roughly speaking, setting margins and padding to particular values will give cushions of space around your content. In general it won’t matter which you set, but technically the margin is outside the “border” and the padding is within it. You can generally specifiy which margin/padding to set, or uniformly set them in every direction.

Margins, Borders, and Padding

You should almost always put some kind of margin/padding around text. It’s really difficult to read when words stretch all the way out to the edge of a box or page, so your eyes will appreciate the white space.

Sizes

Sizes of elements can be set and adjusted in several ways.

Colors

Colors can generally be set by just indicting a color name. To get a really specific color, you can use a color selector to find the hexadecimal representation of a color. Hexadecimal values are between 0 and 9 or a and f. The numbers are equivalent to, well, themselves, and the letters are two-digit numbers (a=10, b=11, c=12, et cetera). For example, #1bb99a is the shade of green we use on the PennApps website. People generally use “color pickers” to find the hexadecimal version fo the colors they want.

If you want to change a box color, alter the background property. Text color can be changed with the color property.

Aligning

Just like a Word document, you can align text and objects to the left, right, or center of a page.

Floating

You can set elements to “float” to some part of the page. For example, if you’d like to see a picture on the left of a text box, you can set float:left;. Be careful—there are a ton of nuances here.

Animating

Yes, you can actually animate your CSS code. Below is an animation that causes a circle to blink red:

@keyframes blink {
	50% {
		background: radial-gradient(circle, red 15%, transparent 40%), #cc5;
	}
}

/* in the actual CSS element */
animation: blink .5s infinite;

Keyframes are just different snapshots of your animation. In the blinking example, the original keyframe is a white circle, and the second keyframe is a red circle.

Bootstrap

The easiest shortcut to good design

Poke around on Bootstrap. There are two main ways to use it in a website.

You’re welcome to download Bootstrap, but it’s probably easier just to link to the website you want (or download just the files you want off the Internet).

Resources

Time to realize that thievery isn’t always wrong

There are tons of resources out there to help with CSS and design:

This guide was provided by Brynn Claypoole.

Git/Github

Version control for the rest of us

What is Git

Git is the tool that handles your version control, Github is the online repository where you store all your files. Version control records specific changes to a file or a set of files over time so that you can access specific versions later. Github stores these versions on the cloud. Since you can add multiple people to a Github repository, it’s also an excellent way to collaborate with others on projects. You should try this awesome simulation-version of this tutorial here. Then you should make your Github account with your school email.

To install git on Mac: - Use spotlight search to find and open terminal. - Type git into terminal. If a bunch of text is printed you have git already. - Otherwise go here and download git.

To install on Windows: - Go here and download git.

Unix

Unix is how your operating system is organized. Everything is organized into a hierarchy similar to a tree. Everything starts in the root and goes up to the leaves-files. Files are contained in folders called directories. You get to a file through a path of directories. $ acts as a colon, and - denotes the root.

Terminal

Terminal is your text based access to the operating system. It carries out Unix commands. Here are some helpful and common Unix commands:

Feel free to try some of these commands, and look up others to see how they work.

Set Up Git

Now that we have a basic understanding of Terminal and Unix commands we can set up git.Go here to set up Git. You have already completed step 1. We highly recommend setting up an SSH keypair with your computer to allow more ease of use with Github. You can do that here. A few things to know about using Terminal: if you enter something and there is no message afterwards that usually means it has worked, and when typing in a password it will not appear that you are typing anything, but this is also working.

Repositories

As said before, a repository is where your code is stored on Github. You can make a repsoitory following instructions. You can also see instructions on how to commit a change from Github itself.

How to Add Changes Using Terminal

This assumes that you have setup a SSH keypair with your computer.

If you check your Github, you will see that the files have been updated and/or added.

Fork a Repository

Forking a repository is something you’ll want to be able to do to collaborate with others on repositories. Github’s instructions on forking a repository are here.

Their instructions also walk you through creating a branch. All files in a repository automatically end up in the master branch. However, if you would like to make some changes to the main code without damaging parts of the code that are working then you can create another branch and later merge it. When you’re done making edits you can merge this other branch with the master branch again.

Go to to do more interactive tutorials!

Webpage Hosting

Webpage hosting is what actually puts your website on the internet. Many places offer hosting for a price but Github will host your webpage for free. You can see their instructions for hosting websites here

Resources

Here is another excellent guide to Git!

OOP && Java

What is Java?

Java is a multi-faceted object-oriented programming language designed to allow developers to “write once, run anywhere”. When Java code is compiled, it is not converted to machine code like in many other languages; instead, it is converted to Java “bytecode”; this bytecode is then executed on the Java Virtual Machine, a program which is available for a wide variety of platforms. As result, Java can be run in the same way on any machine with the JVM installed. While sometimes maligned for being syntactically verbose (lots of rules you have to follow when you code in Java), Java is nonetheless a popular language with millions of developers and hundreds of millions of users. Developed in the early 90’s by Sun Microsystems (now a part of Oracle), Java is one of the most widely used languages for apps of any size!

What is Object-Oriented Programming?

In essence, object-oriented programming (OOP) is a programming paradigm where data and the functions (often called methods) to use the data are connected. The data and its associated methods are packaged together in a single unit, called an object. Because of this, the main program in many OOP apps is often small, instead simply instantiating (creating) several objects and then calling their associated methods to make them interact.

Hello the Hard Way

Here is an example of a rather complex “Hello World!” program in Java. In this example, we will take advantage of the extensive Java Swing library, an extensive GUI library which can be used in a wide variety of apps. (All credit to Wikipedia for the program)

import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
    	public static void main(String[] args) {
            	JFrame frame = new JFrame();       	//Creating frame
            	frame.setTitle("Hi!");             	//Setting title frame
            	frame.add(new JLabel("Hello, world!"));//Adding text to frame
            	frame.pack();                      	//Set size to smallest
            	frame.setLocationRelativeTo(null); 	//Centering frame
            	frame.setVisible(true);            	//Showing frame
    	}
}

Though seemingly complex, this program will allow us to examine the ways the object-oriented features of Java work.

First, note the “import” statements up at the top. Like “include” in C, this instructs the compiler to compile the public libraries for javax.swing.JFrame and javax.swing.JLabel (Note: if we wanted to include ALL of the swing library, we could have used import javax.swing.* ). Next, notice the line public static void main(String[] args) { . While it is not vital to know what every word in this line means, it suffices to say that this line must appear once, and only once, in every Java program. We call this the “main method” and it begins the execution of every Java program. Once inside the main method, we will make calls to other objects to finish the logic of our program.

Next, notice the line JFrame frame = new JFrame();. This line provides an example of the essence of OOP. Somewhere else, the library JFrame has been created. In our program, we want to use the JFrame to display our image. Therefore, after importing the package, we have to make a JFrame; to do so, we start by declaring to the compiler that we are making a new JFrame named frame (i.e. JFrame frame). Next, we associate that JFrame with a JFrame which we instantiate (create) using the “new” keyword (i.e. ` new JFrame()`). After this line is executed, we have a fully functioning JFrame object called frame which we can manipulate later.

Next, notice the line frame.setTitle(“Hi!”);. This allows us to see two more important Java characteristics. First, methods (like “setTitle” are passed as follows: objectName.methodName(argumentsToMethod)). Second, notice the camelCase. This is just common Java style for naming. Instead of separating multiple words in a method name or object name, we use the notation firstSecondThirdEtc to differentiate between different words in the name.

We won’t explain the entire rest of the program here, but use the tips here to dissect and absorb it!

Resources

http://docs.oracle.com/javase/tutorial/ http://www.oracle.com/technetwork/topics/newtojava/overview/index.html http://en.wikipedia.org/wiki/Javadoc http://www.java.com/en/download/faq/whatis_java.xml http://en.wikipedia.org/wiki/Java_(programming_language)

As, always Google ‘learn Java’ and you’ll find lots more resources.

Python

Coding language with simplicity and power

Python is a widely used programming language. Similar to Java, it is primarily and object-oriented language (see the Java / OOP page for more information on that). However, compared to Java, Python is designed to be extremely readable and usually requires fewer lines of code. To see this simplicity, here is a “Hello World!” program in Python:

print “Hello World!”

Furthermore, Python has a “batteries included” philosophy, meaning that many important and useful libraries are already included. This makes Python a very good place to start for new programmers.

Resources

What is Android?

Android is the most widely used mobile operating system in the world. Unlike its main competitor, iOS, the Android system is open source and is distributed across many, many different hardware devices (often with modifications). This makes Android another very popular choice for building apps. Apps for Android are written in a modified form of Java.

Resources

Build a simple app

More about Android development for beginners

If you’d like to install eclipse, a great way to build Java and Android apps, go here

This is a great beginner guide to Android!

iOS

Developing apps for Apple’s mobile platform

###What is iOS? iOS is mobile operating system used on all Apple mobile devices. Because of this, it is second only to Android in terms of mobile OS popularity. As such, it is a very popular platform to build and develop apps. iPhone applications are written in Objective-C.

###Resources

Apple documentation

Apple Developer’s Road Map to iOS

XCode IDE

iOS development lab

Chrome DevTools for Debugging

The first steps to making your website.

Why Chrome DevTools?

Be it a hackathon or an internship, being good at debugging is an extremely useful skill to have. It’s very rare that a program you write runs perfectly the first time you write it, and therefore as coders we have to spend a lot of time debugging and trying to identify what parts of the code cause problems in our program. IDEs(Integrated Development Environments) like Eclipse provide users with built in debuggers to make this process easier, but what do you do when it comes to web programming? Most people use a text editor like Sublime when programming for the web, and these editors don’t come with powerful debugging capabilities.

Especially at a hackathon like PennApps where time is very valuable, you wouldn’t want to waste 10 hours trying to figure out what’s wrong with your code. Luckily, Chrome has very powerful and easy to use tools built in for debugging purposes. Other browsers have tools similar to this too, however I had a fairly easy time starting out with Chrome DevTools due to the great resources available on the web.

So now that we know why Chrome DevTools could be a valuable resource, let’s begin!

An In-Depth Guide to All Your DevTools Needs

The guide you’re reading now will be covering some of the most basic and important features of DevTools. If you happen to have a couple of hours free, and would like to delve more into the capabilities of DevTools, I strongly recommend taking this free Code School course. It’s basically a series of short videos that explain different features of DevTools, all followed with a Challenge section that gets you to actually use that feature. It’s very informative and easy to follow, and by the end you will have a much better idea of how to use DevTools to your advantage.

If you don’t think you have the time, don’t worry. This guide assumes this is your first time working with Chrome DevTools.

Opening up DevTools

After opening up Chrome, there are two ways you could pull up DevTools.

First way: Click the icon on the top right of your Chrome window (three horizontal lines lined up vertically), go to Tools → Developer Tools

Second way: You can also Right Click anywhere on the screen and select Inspect Element.

You should get something like this on the bottom half of your screen:

Chrome DevTools Tabs

Now that you have DevTools open, let’s take a look at the tab names and what they are primarily used for.

Elements - This is the tab that’s currently open on the screenshot above. It’s used to see the different HTML elements on your document along with the CSS properties that apply to them. One of the great features the Elements panel offers is the ability to live-edit HTML or CSS and see the changes immediately reflected on your browser.

Resources

This tab shows the resources (HTML, CSS, JavaScript files, images, storage, etc) that were loaded for your web page. We won’t be dealing a lot with this tab in this guide, however it’s useful to see whether you’re loading everything you want to the page and check other things such as the sizes of your images.

Network

I personally find this to be an incredibly useful panel. If you go to the Network panel and refresh your page, you will see all of the resources loaded for your page, along with their sizes, load times, and when they started loading. If something goes wrong with loading up a resource or another operation in your web app (such as an HTTP request), you will see a status code on this tab telling you what went wrong. This is a great way to see how long your web app takes to load up or how long different operations in your web app take to fire up.

Sources

This is probably the tab I spend the most time in as I try to debug a web app I’m working on. You can use the JavaScript debugger built into Chrome DevTools through this tab. The debugger allows you to set breakpoints in certain parts of your code and shows you what the state of your web app is at a certain line in your program.

Timeline

The timeline panel is mostly used for testing the performance of your web app. If you want to check with how much memory your web app is taking up or how fast it’s performing, it’s likely that you’ll use this tab. However, if you’re not dealing with a realtime app or a memory intensive app (such as a web app that makes use of 3D graphics) for the hackathon, you don’t need to worry about this tab for now.

Profiles

Another tab that’s mostly useful for inspecting performance. For instance, you can run a JavaScript CPU Profile for a certain amount of time and then see what functions take up how much time. In this case the JavaScript profile could be useful in spotting which functions seem to be the slowest in your app, and how you could go about making them faster.

Audits

This is basically a tab that offers you advice on how to improve your performance and network times. The terminology in some of these advices could be a bit confusing, so don’t worry about it if it doesn’t make a whole lot of sense. We won’t be focusing on this tab in this guide.

Console

This brings up a JavaScript console that you can interact with. It’s useful for testing out whether some of your methods work as expected, to inspect different elements in the DOM (Document Object Model), or to check some of your JavaScript objects.

Since this is more of an introductory guide to the most essential features of DevTools, I’ll try to explain to you some of the tools I use the most and how it could help you out when you’re working on your app. I’ll mostly focus on Elements and Sources, and touch a bit on Profiles and Console. Again, if you wish to check out all these features, I highly recommend the Code School course I posted earlier.

Elements Tab

The Elements Tab is made up of two parts: the left side which shows the HTML elements in a nice tree format, and the right side which shows what styles and properties are applied to the currently selected HTML element.

As you might have already noticed, if you hover your cursor over different HTML elements of the tree while in the Elements panel, you will see different parts of the page being highlighted in blue. This is a handy feature that allows the user to see which HTML element is currently being selected. Clicking on one of these elements will update the right part of the Elements tab to reflect the styles and properties that apply to the selected element.

Another really cool feature of this tree-view is that you can double click on any tag or text to edit it in your browser. This is very useful if you simply want to make a small change in your HTML and see what it does, since the change will be immediately reflected on your browser view. However keep in mind that the change you made will not be reflected in the code you have on your computer, so if you want to keep the change you have to go back and make the same change in your text editor.

Now let’s take a look at the right side of the elements panel. If you’re familiar with CSS, you will see that on the right side of the elements panel currently shows all the styles that apply to the selected element. It will show which styles are inherited from which elements, which could also be useful in figuring out weird bugs you have with your styling. Like the tree-view, you can edit styles and see their changes reflected on the page instantly. Simply click on the attribute name (like border-radius) or the value (like 30px) and edit it as you wish. For changing colors, Chrome offers you a color picker so you might find that useful too. You can also add your own attributes by simply clicking on the white space between the { } brackets.

In addition to that, the right panel also displays information about the margins and paddings of the given element, under Metrics. You can click on different parts of the different boxes to edit your margins, borders and paddings instantly.

I believe that these are the most useful features of the Elements tab, but if you want more information or a more detailed explanation of the discussed features, you should check out this page on the Chrome Developers website.

Sources Tab and the Debugger

First, I just want to briefly explain why you might find the DevTools JavaScript Debugger useful. As your web application gets bigger and bigger, you will have functions that call other functions, that call other smaller functions. You might have used print statements or console.log statements in the past to figure out which point the program runs up to. In smaller applications, this might be a fine way of debugging, but I assure you learning to work with a debugger will save you a lot of precious time. After you become comfortable with it, you will figure out bugs that would take hours to figure out with print statements in minutes.

The basic concept to understand when using a debugger is the concept of breakpoints. The debugger allows you to set breakpoints on any line of code you want. After being set, a breakpoint will be triggered when the program runs up to that point. Triggering a breakpoint will freeze the application, and this is why it’s so useful to use them.

At this point you can actually follow which lines are being called in your code by using the Step Over button, which will skip that line and go to the next line in your code that’s being called. Using Step Into will go into the function call that is on the current line. So let’s say you’re on a line that calls a function foo(), Step Over will skip over the call and take you to the next line of code, while Step Into will take you into foo. Step Out is the direct opposite of Step Into and will take you out of the function you’re currently in.

Let’s say you set up two breakpoints far from each other, and your program came to the first one. If you don’t want to step over every line until the second break(although you certainly can), you can simply press the Play button to resume the program, until it triggers another breakpoint. The Pause and Play buttons can also be useful in situations where you have a game or animation that looks off in certain parts of gameplay, since you can just Pause and the program will pause at that state.

With what you know so far, you can see which lines of code are being executed in your code. However the real power of debugging comes from being able to see the state of every variable in your code when a breakpoint is triggered. When a breakpoint is triggered, the right panel of the Source tab will show you a list of variables or objects. You can actually go into these and observe what their state is at a given line of code. This is an incredibly useful feature, since you can pinpoint exactly what’s wrong with your code at a given line if you analyze all the variables involved and can tell what’s wrong with their values.

This was more of an introduction to using a Debugger, because I wanted to direct you to the Chrome Developers page that has a great step by step guide on how to use the Debugger. I recommend reading through the “Debugging with Breakpoints” part. I don’t think you need to worry about the parts after that if this is your first time with debuggers or a browser debugger. The Code School course also does a great job in explaining how to use the Debugger in an interactive way.

JavaScript Console

The JavaScript console could be a useful tool in debugging, since if you have any console.log statements in your actual code, this is where you will see the output. I know I mentioned earlier that the debugger is much more powerful, however there are still times where going with some console.log statements could make sense. Let’s say there is a 3D animation in your web app, and you want to see how your object changes its position over time. You could set a breakpoint in your method that gets called every frame, and check the position using the debugger. However this could take a while and you might want to just see everything at once. A simple: console.log(“Object position:” + object.position) could be a much simpler way to see the change in position throughout the animation. The JavaScript Console would be where you would check the output of these calls.

In addition to checking console.log output, you can also directly write into the JavaScript console. If you have an object called cube in your app, you could simply type in: console.log(cube) into your console and the console would output the properties of the object cube. Or let’s say you want to access an element in your HTML, you could simply type: document.getElementById(“button”) to get the element with the id of ”button”(If you’re familiar with jQuery, the Chrome JS console also works with statements like: $(“#button”) ).

Let’s say you want to test out whether a function you wrote, called foo, does what it’s supposed to. You could type: foo() into your console and see whether it works as it should. This can be a powerful tool if you end up having too many little functions in your app and you just want to test out whether one of these work right.

If you want to learn more about the JavaScript console, take a look at this Chrome Developers page. You can skip the “Using the Console API” part, but the “Basic operation” and “Using the Command Line API” parts contain some information that might help you out.

Conclusion and Further Resources

And with that, we’re done! I hope you found this guide as a helpful introduction to some of the most important features of Chrome DevTools. It might be a hard to get into it at first, but once you get in a habit of using Developer Tools (in any browser), it will save you a lot of time when debugging or when you’re just completely lost.

As I’ve said multiple times throughout this guide, if you want to learn more about DevTools, these two resources are very helpful: 1. Discover DevTools on Code School: Easy to understand, split up into different sections, each section followed by a simple yet effective interactive challenge. 2. Chrome Developers page on DevTools: This is the official documentation on DevTools, and if you want to know something about DevTools, it’s guaranteed to be on here. Some parts might talk about things you might not know, but don’t be intimidated by that. It contains information for both beginners and more advanced users of DevTools.

This information was created by Emre

Using Node.js

First of all, we gave a whole series of lectures about Node at Code Weekend. Also here’s more about Node.js. You should check both out if you’re interested in learning Node!

An important piece of any complete web application is a server backend. Users make requests to your server, which then returns web pages to them as responses. One of the simplest and most lightweight frameworks is Node.js, making it an excellent choice for beginners. Node.js allows users to write server side code in JavaScript. If you would like to try a different option for your app, you could also try Ruby on Rails, which based on the Ruby language, and Django, which is based on Python. Almost every language has a corresponding backend framework or library.

Node.js

For those interested in learning Node, there are many excellent resources.

The Official Node website, has a lot of documentation.

A great starting tutorial is the Node Beginner Book.

For a more technical overview, you can watch the tech talk by Ryan Dahl, the creator of Node.js.

If you don’t like either of these, a simple google search for “Node.js tutorials” or something similar will provide many free options.

JavaScript

If you are new to JavaScript, it’s a good idea to get comfortable with it before diving into node. Javascript is a extremely important part of web development, even for apps not using node.There are plenty of good JavaScript tutorials, including:

Eloquent JavaScript, a good book for beginners to JavaScript or programming in general.

Code academy, a free, hands on tutorial to many web technologies, including JavaScript.

As with above, plenty of other options can be found easily through Google.

Resources

Use these resources for specific info, rather than learning from scratch:

The Node.js official documentation

Mozilla’s JavaScript documentation

Express Guide to Node and Express

JQuery

JQuery is a helpful Javascript library that makes possible to bring webpages to life without going insane. It provides helpers for DOM manipulation, event binding, AJAX requests, and even animations. JQuery is compatible with nearly all browsers (including oldies like IE) and has a wide range of plugins available that extend its functionality even further.

This guide will assume some knowledge of programming and HTML/CSS but extensive practice of Javascript will not be required to understand it. However, the better you know the language the more dangerous you’ll be when you sit down to program. For an excellent primer in the Javascript language (as well as a look at how miserable events are without JQuery!), go here.

Getting set up

This part is easy. Just put <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> right before the </body> tag in your HTML. This loads the JQuery script onto the page and lets you call its methods with $. Of course, can also provide it yourself rather than relying on Google, but this is the easiest way.

Right under that snippet, put another script tag, like so:

<script>
    $(‘document’).ready(function(){
        //Your JQuery and Javascript code goes here
});
</script>

This tells JQuery to wait until the document is loaded, and then run whatever code you put in the body of the function.

DOM Manipulation

Check out the HTML/CSS page to learn about the DOM.

JQuery makes it really easy to add, remove, and change DOM nodes. For instance, if we wanted to create a new <h2> element that said “PennApps rocks,” we would write

$(‘<h2>’).html(‘PennApps rocks’);

Now, while this has created a new DOM node like we wanted, it isn’t actually inserted into the DOM anywhere. To do that, we would write:

var header = $(‘<h2>’).html(‘PennApps rocks’);
$(‘body’).append(header);

This will insert the header at the very end of the body. If we had wanted it at the beginning, we could have used prepend.

But for every yin, there must be a yang; and so to balance the power of insertion, we must wield the power of deletion. To remove the header element from the DOM:

header.remove();

Finding nodes in the DOM

One of the most common tasks you’ll use JQuery for is finding all nodes in the DOM that match certain criteria. For instance, you might want to find all paragraphs in order to change their style or make some other changes.

For this, it helps to know some CSS selectors, because JQuery can find nodes just the same way a style sheet does. In CSS you could color all paragraphs red with:

p /* ← this is the selector! */ {
    color: red;
}

You could do the same thing in JQuery as well, in much the same way:

$(‘p’).css(‘color’, ‘red’);

You use the same ‘p’ selector here as in the CSS, and in both it selected all <p> tags in the DOM. Two other common selectors are the class selector .class-name and the id selector #id-name. For a list of more advanced selectors in JQuery please see http://api.jquery.com/?s=selectors.

Method Chaining

It would be a real pain to have to write out the same selector over and over just to change multiple properties on an element. Luckily, JQuery has a neat trick; every one of its methods returns the original JQuery object that you create when you write the selector! This way, you can just chain the methods one after another, like so:

var myNode = $(‘#myID’).css(‘color’, ‘red’).attr(‘width’, ‘500px’).css(‘width’border’, ‘1px solid blue’);

Event Binding

Clicks, Keypresses, and more

JQuery makes it easy to make something happen when a user clicks the a button or presses a key. Once you’ve selected the node you want to bind the event to (either via selectors as shown above, or by creating the node in the Javascript and storing it as a variable), you can use the .click(), .keypress(), and a host of other event binding methods to do some seriously cool stuff. Google and Stack Overflow will be your best bet for finding out how to do something specific (like binding only to the ‘up’ arrow for example).

JQuery also supports touch events, although unfortunately not with a nice helper method like ‘click().’ You have to bind to touch events manually like so:

$(‘#myButton’).on(‘touchstart’, function(){
    alert(‘You touched the button! Hooray!’);
});

This will open a popup window when a user touches the button with id=”myButton” (but not clicks with a mouse).

You can also use .on() to bind to custom events that you can name yourself. This can be really useful in a lot of situations; for instance, you might have a ‘save’ event that gets triggered every time the user clicks a save button. Here is an example of such a setup:

$(‘#savebutton’).on(‘save’, function(){
    alert(‘Saving’);
});
$(‘#savebutton’).trigger(‘save’); //Alerts ‘Saving’

This can be really useful for situations in which you need a few events, or you need a lightweight ‘event bus’ that you can hook into different parts of your application. Such a use case is actually a little beyond JQuery, but if you’re interested, check out some frameworks like Backbone that have a more robust event system keyed into model data.

Animations

Rather from simply inserting elements into the DOM, JQuery provides a few functions to make their entrance and exit a little more polished. The simplest of these are fadeIn() and fadeOut(), which are pretty self explanatory; the element is phased from invisible to visible, or vice-versa. But you can also program custom animations based on CSS properties via the animate() function, or chain multiple animate() calls. Now, with only JQuery loaded you can only animate numerical properties; but if you want to animate colors or other properties, you should check out some…

JQuery Plugins

JQuery is open source and fully extensible, and it has a lot of really great plugins to extend its core functionality. Some are pretty much libraries in their own right, like JQuery UI, a collection of extremely useful interactive components; some are much smaller and a lot less documented (such as verdict.js). Plugins can be loaded with a <script> tag the same way as JQuery itself, and there is virtually guaranteed to be a plugin for anything you can think of.