Mindfly Website Design Studio

Mindfly Web Designer Favorite

Blog

Our Posts on Web Design

A Pseudo-Tutorial on Learning JavaScript

by Kyle Weems September 15, 2008 3:31 AM

There's a major risk with tutorials. You're devoting a portion of time to teach someone a portion of your hard-earned knowledge, which means you're helping foster future competition for your skillset. It seems like a bad idea in these financially troublesome times, so why risk it?

In short, so you're pestered less. I can't count the number of times I've been asked to help someone with a small web-related task that was trivial to me but monumentous to them, but would take up just enough time that it wrecked my train of thought on whatever project I was on. I'm a nice guy, so I don't want my thoughts to be hospitalized after a tragic derailment. Who's going to pay for new clothes for their little thought-children?

The solution? A tutorial.

A common issue with the web industry is titles. My business card says "developer", which is something like wearing a nametag at a convention that says "human." If I had to pick a new title, I'd go for "front end developer" which is slightly more clarifying and in my opinion sums up a tad better what I'm doing, which is combining HTML, CSS, .NET or PHP, and JavaScript in a big kettle and mixing it around for hours until it resembles the designs the more talented people in the studio create.

It's like being a digital sous chef without the knife wounds and drinking habit.

I work in a unique position in the studio, as I'm surrounded by people who more commonly are called "designers" or "developers" (in the back-end development sense), which means they're much more capable of making a gorgeous website or writing code that does more with a database than play patty-cake, but they're not so good at mixing the two.

I could comment about how many times I've been given a web application provided by the developers and asked to skin it with the site's design, only to realize the code is spitting out more tables than an IKEA store. I could do that, but I like my job and will instead compliment the developers on their amazing abilities.

They're rad. (Yes, I'm aware the eighties ended a while back.)

One of the areas my help is most requested is enhancing a mostly-finished website with some JavaScript that adds some extra functionality or pizazz (did I spell that right?), enhancing the experience and making clients go "Oooh!"

We like it when clients go "Oooh!" because then they're slightly more inclined to spend money on us.

A good deal of these JavaScript requests, though, are fairly basic, simple affairs. So rather than be disrupted every fifteen minutes to make a tiny script, I'm going to bite the bullet and introduce them to the basic concept of JavaScript and how to use it.

That's called passing the buck, people.

I always wondered whether that saying was a reference to a dollar bill or to a male deer. Granted, the latter seems a bit odd, but is more consistant with the sort of inconvenience the expression is used to describe.

The Conundrum: An About Box That Opens/Closes.

Teaching all of JavaScript in a single tutorial is a foolish endeavor. So is repeating the great work others have done in the past on the web. So this is more like a tutorial about tutorials, along with some basic setup instructions. I'm going to be focusing on one of the more common requests I get, which is how to make an element on the page appear or disappear with a mouse click (like an expanding menu or hidden picture, etc.)

In this tutorial, then, I have a website that has an "About Kyle Weems" box of information that can be opened or closed by a mouse click, which we'll be using JavaScript for.

We'll start, then, with the HTML and CSS for this 'site'. Take a look at Example #1, which shows a version of the site with no JavaScript. We've got this 'menu bar' that when hovered over opens the about box. This works well enough, but if we wanted it to stay open when we moved the mouse away, we need to look to more than CSS for the solution. We need (cue superhero music) JavaScript!

Getting Started: Finding Tutorials on JavaScript

JavaScript has been around in one form or another since 1996. Since it's used in websites, a lot of web-obsessed people have written more than a fwe handy tutorials about it. Three great sites to start with for the novice are W3School's JavaScript tutorials, Tizag, and a nice introduction to JavaScript that I found at Webmonkey. Go. Read them.

What... still here? Fine, I guess I'll help some more on our particular problem. Please remember, I'm skipping over a lot of basic details that you can glean from the tutorials I've linked above. Reading through this pseudo-tutorial without those will probably result in at least some minor confusion.

So, what now?

Adding a JavaScript File

The first step in adding JavaScript functionality to a web page is to attach the script you'll be using to the web page. There's a few options, including just pasting the script into the page itself. However, I recommend adding a link to a seperate .js file (which will hold your script) in the page's head, like so:

<script type="text/javascript" src="file.js"></script>

This will load the script when the page loads. You can then make the .js file with any text editor of your choice (I like Notepad ++ or Visual Studio Express 2008). JavaScript files, like pinatas, are full of delightful things, but instead of candy, it's functions.

A Basic Explanation of JavaScript Functions

We'll need a function for our example problem that can make the about box appear or disappear when we're clicking on the 'menu' for it. A function can be thought of as a package that holds a group of commands in JavaScript that you can then call later to do all these things at once. Functions are declared in JavaScript like so:

function nameGoesHere(){
 // code goes here.
}

we declare that we're making a function by starting with 'function' (easy, isn't it?) then provide a name for the function, then some parentheses (which can hold other things, but let's not jump the gun on that), then the curly braces. All the code for the function is contained inside the curly braces.

Take a look at Example #2. I recommend checking out the page source, as well as looking at Example #2's JavaScript file. In the JS file you'll find a function called toggleBox which holds most (but not quite all) of the code that we'll be using. You may also notice that the page doesn't appear to be doing anything. We'll get to that in a second.

Targeting Elements with JavaScript

The function has a lot of stuff going on, but we'll examine the core bit of code in there. JavaScript is used a great deal to manipulate HTML elements, which allows for all sorts of neat effects (especially when CSS comes into the picture). To manipulate those elements we need to target them. The most common way to do that with vanilla JavaScript is:

document.getElementById("elementIdHere")

Yes, that's a mouthful. We'll look at it a bit at a time. The 'document' part essentially is referring to the page, and the 'getElementById' means we're looking in that page for an element that has an id that matches the string inside the parentheses. Once we've targeted the element, we can do stuff with it. In our example #2's script file, you'll see that we're targetting two different elements. We're messing around with the className of 'aboutDetails' and we're changing the innerHTML and onclick of 'boxToggle'. When looking at the example's HTML file you'll see that 'aboutDetails' is the page we're planning on hiding/showing, and 'aboutDetails' is the plus sign, which we're intending to make work like a button.

Messing with css/classes

The className property allows us to add and remove classes from an object, which is a big deal. Since we've set up CSS that says div#aboutDetails.open { display:block;} in our page, by adding or removing that class with JavaScript we're able to make the div appear and disappear. It's a simple effect, but a handy one. You can create any sort of CSS, attach it to a class, and then have the JavaScript to cause that to take effect by changing an element's className.

We're also messing with innerHTML, which changes the text/content of an element (in this case we're turning the + into a - and back again).

Basic events

The big thing here that should be making this example work is the onclick property that we're modifying for 'boxToggle'. The onclick property is one of many element properties that is tied to an event, in this case the user clicking on the element with the mouse. By assigning it to the function toggleBox, we're saying that we want to run the function whenever the user clicks on the + sign in the menu.

So why isn't the example working?

Loading when the document is ready

This is a big deal for JavaScript, so it's worth detailing. JavaScript, by default, run all the script outside of a function (in this example, the line of code that sets up the onclick event) as soon as the script is loaded. We're calling for our script in the head of the page, which is loading before the page's content actually loads. This means that the JavaScript is trying to atach an onclick event to an element that doesn't exist yet.

In order to fix this, we need to load the script after the page has finished loading. How do we do that?

Well, we could put the link to the script at the end of the page, but that's messy and has it's own problems associated with it. So instead we need to just tell our script to load it's functions after the page is done loading.

We've done that here, in Example #3 (JS file is here). You'll notice it actually works.

What's different? Well, we've added that interesting little function called addLoadEvent. It was thought up by Simon Willison, who first introduced the idea for it here. What the function does is fire off an event called by it after the page loads, which helps us sidestep the whole problem. We've modified the line that calls for the toggleBox function as well. Now we've got a function called addToggleEvent that sets up the onclick event, and that function is now called by addLoadEvent(addToggleEvent)

Click away and learn exciting details about me.

Now, this is a perfectly good solution to the problem, and we could stop here.

JavaScript Libraries

However there's a lot of JS geeks out there who make me look tame, and they've constructed entire libraries that provide dozens (if not hundreds) of useful shortcuts to common tasks or neat animation effects that we'd like to use JavaScript for. They also help with a lot of the cross-browser problems that show up in more complex JavaScript commands (that's another one of those big topics we'll save for later.) In short, they make JavaScript development faster, which makes everyone happy.

Two examples of these libraries are jQuery and prototype. There's plenty others out there, and most do most of the same things in slightly different ways. I prefer jQuery myself because it's generally small and fast, and is really compact and simple in it's code and syntax. Take for example our Example #3. It has 39 lines of code for our whole toggle solution. Compare that to Example #4 (JS file here). You'll find that we shrank the code down to 17 lines (I could probably have tightened it up even more if I'd worked on it more), and even more importantly we're using syntax that is more human readable and friendly.

How do we use a library? Well, like the example shows we're adding in jQuery's .js file prior to our own JavaScript, so it loads first, allowing us to make use of its commands. This does mean our page's load time is a bit longer, but with modern download speeds and the relatively small size of jQuery (the version I used is only 54kb, smaller than many images), it's not a terribly noticeable hit, especially for larger sites with more content (and often more bells and whistles that JS could be used to enhance).

Now, once again, make good use of those tutorials I've linked. By itself this pseudo-tutorial is pretty sparse on explaining what JS is, and how to use it. It's more like a guide to a guide.

Enjoy.

Permalink | Comments (0) | Post RSSRSS comment feed

Comments

Add comment


(Will show your Gravatar icon)  

biuquote
  • Comment
  • Preview
Loading