Introduction To jQuery (Part 3): Waiting For The Page To Load & Anonymous Functions

By James Bruce, MakeUseOfMarch 03, 2013 at 01:31PM

introduction to jqueryjQuery is arguably an essential skill for the modern web developer, and in this short mini-series I hope to give you the knowledge to start making use of it in your own web projects. In the first part of our jQuery tutorial, we looked at some language fundamentals, and how to use selectors; in part 2, we moved on to methods of manipulating the DOM.

In part 3, we’ll tackle the problem of how to delay jQuery until the page has loaded, then I’ll try to explain what anonymous functions are and why you need to know about them.

Delayed Loading: How & Why?

If you’ve been trying out some of the code from part 1 and 2, you may have come across some errors, odd behaviour, or things just plain not working. The most common error I experienced when learning jQuery was that of DOM elements not being found – even though I could plainly see them in the source of the page, jQuery kept telling me it just couldn’t find them! Why is that?

Well, it’s all to do with the order in which things are loaded by the browser. At it’s simplest, if you have a jQuery script running in the browser before the DOM element it’s looking for has actually been created, the script will load first, but not do anything because it can’t find the element, then the DOM element will load later. This is less of a problem if you place all your scripts near the footer, but it can still happen.

The solution is to wrap your scripts in whats called a document ready event. This makes the enclosed code wait until the DOM has been fully loaded (until it’s ready). Using it is simple:

$(document).ready(function(){
//your code to delay goes here
});

There’s an even shorter way of doing this outlined in the jQuery documentation, but I’d strongly suggest you use this way for code readability.

This document ready event is another good example of an anonymous function, so let’s try to understand what this means.

Anonymous Functions

If like me you’ve got some beginner level programming experience under your belt, the idea of anonymous functions – which is core to jQuery and Javascript – might be a little disconcerting. For one, it makes errors due to mismatched braces quite common, which is why I’m going to explain it now. If you’d like a thorough explanation as to why anonymous functions are better than regular named functions on a more technical level, I’d suggest reading this fairly complex blog post.

Until now, you’ve probably only come across named functions. These are functions that have been declared with a name and can therefore be called anywhere else, as many times as you like. Consider this trivial example, which will log a message to the console when the page is loaded.

function doStuffOnPageLoad(){
console.log("doing stuff!");
}
$(document).ready(doStuffOnPageLoad);

This is useful if your function is designed to be re-used, but in this case it’s kind of convoluted since we only really want it to fire once when the page is loaded. Instead, we don’t bother defining a separate function, and just declare it inline as a parameter as and when needed. The previous example would therefore be better re-written as:

$(document).ready(function(){
console.log("doing stuff");
});

You may not see many advantages of this at the moment – it’s only marginally less code in this case – but as your scripts progress in complexity you’ll appreciate not having to jump around trying to find function definitions. Unfortunately, it does make things a little more difficult for beginners – just look at all those braces – so be sure to check the following points if you’re getting errors:

  • Correct number of corresponding braces – indenting your code helps.
  • Curly vs round braces.
  • Statement closing with a semicolon – but not needed after a closing curly brace.

introduction to jquery

Using a code editor like Sublime Text 2 can really help as it highlights corresponding braces and automatically indents code for you. A dedicated code editor is essential, really.

That’s it for this lesson, but  you should get into the habit of enclosing some basic DOM manipulations in document ready event before moving on, and start editing files in a code editor if you aren’t already. Next time, we’ll take a look at events and how they are used to add interactivity to a page – such as make jQuery do something when a button is clicked. Questions or comments always welcome below.

The post Introduction To jQuery (Part 3): Waiting For The Page To Load & Anonymous Functions appeared first on MakeUseOf.

How Power Failures Corrupt Flash SSD Data

By Soulskill, SlashdotMarch 01, 2013 at 05:06PM

An anonymous reader writes “Flash SSDs are non-volatile, right? So how could power failures screw with your data? Several ways, according to a ZDNet post that summarizes a paper (PDF) presented at last month’s FAST 13 conference. Researchers from Ohio State and HP Labs researchers tested 15 SSDs using an automated power fault injection testbed and found that 13 lost data. ‘Bit corruption hit 3 devices; 3 had shorn writes; 8 had serializability errors; one device lost 1/3 of its data; and 1 SSD bricked. The low-end hard drive had some unserializable writes, while the high-end drive had no power fault failures. The 2 SSDs that had no failures? Both were MLC 2012 model years with a mid-range ($1.17/GB) price.'”

Share on Google+

Read more of this story at Slashdot.

Big Dog Can Now Throw Cinder Blocks, Thereby Making It The Scariest Robot Ever

By John Biggs, TechCrunchMarch 01, 2013 at 09:22AM

0

While I’m sure there’s some scientific reason for demonstrating how the quadrupedal Big Dog can pick up and throw cinder blocks across a workshop (“Ahem, urm, we’re showing how the mass of the brick has little or no direct effect on the quadruped’s center of gravity, allowing it to carry large objects in the field, ahrm.”), I think what we’re seeing here is the first example of a nascent new robotic sport, human tossing.

What’s really going on here are experiments involving using the legs of the robots to propel objects. “This sort of dynamic approach is routinely used by human athletes and is now improving the performance of robots,” writes Big Dog’s creators at Boston Dynamics. If they only knew.

Imagine a field full of Big Dogs and some of the finest convict athletes from the off-world colonies. Zarg fakes to the left but Big Dog lunges and grabs his suit, ripping off the helmet (and head) and throwing it across the end zone. Torgo grabs a cinder block to throw at Master Big Dog but two Minor Big Dogs grab it in mid-air and toss it back, crushing a group of spectators in the stands.

Naturally, the Big Dogs always win.

via Giz

Easily Add an Auxiliary Port to an Old Car Stereo for About $3

By Thorin Klosowski, LifehackerMarch 01, 2013 at 09:00AM

Easily Add an Auxiliary Port to an Old Car Stereo for About $3If you have one of those stereos that was released in that awkward time between CDs and MP3 players, then it might be missing the now-standard auxiliary port for easy playback. Redditor Esplodies found themselves in this exact situation, and cleverly hacked together an auxiliary port for about $2.50 that works on some older CD players with a CD changer output.

This trick only works on CD players that don’t have an aux port, but it’s surprisingly easy to do. Esplodies used a CD-ROM audio cable and a resistor to plug into the rear CD changer port of the CD player. Then, they just wired that up to an auxiliary port, drilled a small hole in the front of the stereo, and that was it. It’ll only work on a few different models of stereos, but if yours doesn’t fit the bill, you can do it with a little solder, or go all out and add Bluetooth instead. Head over to Reddit for the full picture guide.

Saved myself $92.50 on an Aux port with a little DIY know how | Reddit via

Audi Vs. Audi Paintball Duel

By (author unknown), Core77February 28, 2013 at 01:00PM

audi-vs-audi.jpg

…And here’s the second most awesome thing I’ve seen all week: The guys over at Audi UK came up with a fantastic way to test out the RS 4 Avant, using methods that have no applicability whatsoever to real-world driving. I’m a little disappointed that the guns don’t swivel, and the ergonomic placement of the triggers seems poor, but I did enjoy the secondary/tertiary/quatenary paint-delivering devices. I won’t spoil the surprise(s) for you:

You’re likely wondering how they captured some of those aerial shots, as having a floor-mounted crane amidst those drifting cars doesn’t seem feasible. The answer is: Drones to the rescue!

audi-vs-audi-2.jpg

(more…)

10 Secrets to Locating Non-Patent Prior Art

By (author unknown), Groklaw NewsPicksFebruary 27, 2013 at 10:08PM

3. Get on the phone:

Don’t fear cold-calling. If the patent identifies people, or papers cited look promising, locate and contact the authors to see what materials they maintain, or if they can refer you to others. One search led me to the cell phone number of a CEO, was on a golf course when I called – he was very helpful pointing me to the right person.

4. Find the packrats and hoarders – those that build their own collections, either from their career, or interest. These folks exist, but they don’t publicize their collections, it isn’t indexed, and they may not appreciate visibility. Other sources are from estate sales and antique stores, but this is better for proactively building a collection for future use.

5. A by-product of the non-patent prior art search is identification of potential testifying experts. Sign ’em up. – Stuart Soffer, Patently O

Introduction To jQuery (Part 2): Methods & Functions

By James Bruce, MakeUseOfFebruary 27, 2013 at 03:01PM

introduction to jqueryThis is part of an on-going beginners introduction to jQuery web programming series. Part 1 covered the jQuery basics of how to include it in your project, and selectors. In part 2, we’ll continue with basic usage as we look at some methods you can perform on those DOM elements, and some more language fundamentals.

$(selector).method();

If you recall from lesson 1, this is the basic structure of a DOM manipulation in jQuery. DOM manipulation isn’t the only thing you can do with jQuery of course, but it’s the easiest place to start from and the most common, so that’s why we chose it.

To quickly recap, the selector part of this statement allows you to use CSS-like element names, classes, or IDs in order to locate parts of the DOM. For example, to grab all the <div> with a class name of .hidden, we would use:

$('div.hidden')

The second part of this equation is the method to perform on these DIVs once we’ve found them (if they exist at all; or they may only be one “matching” item). Remember, jQuery will only ever return one element for ID selections, since IDs should refer to unique items. If you’re going to have more than one of something, it must be defined as a class in CSS.

On to methods then; what can you do with elements of the DOM anyway?

First off, I introduced you to the .css method last time so that you could use it for testing. The format is simple:

.css('property','value');

Anything definable by CSS can therefore be adjusted by jQuery – colors, transparency, location, size – to name but a few. The change is immediate.

If you’d rather animate the CSS changes, then I’ve got great news for you; there’s also a method called .animate(). It’s a little more complex though:

.animate({'property':'value'},speed);

As an example:

.animate({'opacity':'0.25','height':'100px'},'fast');

At this point, you might be wondering what the curly braces are for; they’re called an “object literal”, and are typically used to create a list of property:value pairs, kind of like an indexed array if you’re coming from other languages. You’ll use them a lot in jQuery, so I’ll say this again – get used to checking properly for closed brackets and braces!

Check out this page for lots of working examples of the animate method.

As well as manipulating the CSS properties of something, you can adjust the contents of it with the .text(), .html(), and .val()  methods too (val is for the contents of form elements). These methods act as both setters and getters; if you don’t specify a value, they will get the current value. If you do specify a value, they will replace the current value.

Here are some quick examples:

Get the current value of the name field in the comment form and assign it to a variable comment_name:

var commenter_name = $(#comment-form #name).val();

Set the value of <span class=’name’> to the value grabbed from commenter_name:

$('span.name').text(commenter_name);

Then we have a vast selection of methods for cloning, moving around, inserting or deleting parts of the DOM. Your imagination is the limit, really.

Let’s say you wanted to dynamically insert an advertising image block after every every 3rd paragraph in the content column, but you’re doing it in Javascript so that initial page load can be kept clean. Sounds pretty complex, right? Hardly…

$('div#content p:nth-child(3n)').after('<img src="ad.jpg"/>');

Breaking that down, we’ve asked jQuery to:

  1. Find the div with an ID of “content”
  2. Find the p’s contained within that div
  3. Filter to every 3rd p using nth-child pseudo selector (more on that here)
  4. Insert an arbitrary img after each matching element

I can’t possibly list all the methods here and nor would you want to read that. The point is, there’s a method for doing pretty much whatever you can think of when it comes to manipulation, so check the API for one you can use.

introduction to jquery

Also, bear in mind that there might be more than one way to do something. If for example you can’t narrow down the correct object to insertAfter(), perhaps think about finding the next child down and using insertBefore() instead.

Method Chaining

Lastly today, let’s have a quick word about method chaining, basically just because it’s awesome. First, let’s consider the following lines of code:

$('nav#menu').fadeIn('fast');
$('nav#menu').addClass('beingShown');
$('nav#menu').css('margin-right','10px');

That sounds reasonable enough, right? But you can do the same in just one line:

$('nav#menu').fadeIn('fast').addClass('beingShown').css('margin-right','10px');

That does exactly the same thing, and is called method chaining. Since nearly all jQuery methods return a jQuery object themselves, each one can feed into the next. This means less code – which is always a good thing – but it actually also runs faster.

Why? Well, each time you invoke the basic jQuery $ command and selector, you’re asking it to search through the DOM tree looking for a matching element. When you chain methods, you don’t need too keep referring back to the DOM, because it knows where they are now, and can perform the method instantly.

That’s it for today, and I think we’ve probably covered quite a lot. You should now be armed with the ability to perform some pretty heavy DOM manipulations, so have a go, chain your methods together and make a real mess of the page. For now, you’ll want to place your scripts in the footer in order to give the rest of the page time to load. Next week we’ll tackle the issue of making jQuery do things only when everything has loaded correctly with events, and the curious case of anonymous functions.

If you’ve just stumbled upon this post, you’re probably a web developer of some sort and might want to check out all of our WordPress and blogging articles, or even our Best WordPress Plugins page.

The post Introduction To jQuery (Part 2): Methods & Functions appeared first on MakeUseOf.