How to Sort an Associative Array (object) in Javascript

I’ve been working on an ajax site that needs to pass parameters elegantly via the hash tag. While working, I realized that there is usability value to a standardized URL (not to mention SEO value, if Google ever indexes such javascript based pages). In any event, I created this function to sort my hash arrays, and figured you might find it useful too:

function sortObj(arr){
	// Setup Arrays
	var sortedKeys = new Array();
	var sortedObj = {};

	// Separate keys and sort them
	for (var i in arr){
		sortedKeys.push(i);
	}
	sortedKeys.sort();

	// Reconstruct sorted obj based on keys
	for (var i in sortedKeys){
		sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
	}
	return sortedObj;
}

You can construct a demo page with the following HTML:

<html>
<body>
<script type="text/javascript">

// These vars are for demonstration purposes
var alertSort = "";
var blah = {}
blah.test2 = "testb";
blah.test1 = "testa";
blah.test3 = "testc";

// This function sorts objects by key
function sortObj(arr){
	// Setup Arrays
	var sortedKeys = new Array();
	var sortedObj = {};

	// Separate keys and sort them
	for (var i in arr){
		sortedKeys.push(i);
	}
	sortedKeys.sort();

	// Reconstruct sorted obj based on keys
	for (var i in sortedKeys){
		sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
		alertSort += "/" + sortedKeys[i] + "=" + arr[sortedKeys[i]];
// This line is for demonstration purposes
	}
    alert(alertSort);   // This line is for demonstration purposes
	return sortedObj;
}

// Call the function
sortObj(blah);

</script>
</body>
</html>

How to Create a jQuery Bookmarklet

I suspect many of my readers have written at least one jQuery Plugin / Script. In this post, I’d like to show you how to get the most out of that script by also releasing it as a jQuery Bookmarklet. Below, you’ll find two examples of utilities that are ripe for bookmarkleting, as well as a prepared jQuery Bookmarklet file that you can easily modify for the purpose.

Note: Even if you haven’t written a jQuery plugin before, you’ll find bookmarkleting someone else’s plugin as easy as using it on a site.

Before I get to the code though – take a look at the payload. You can add the following links as bookmarklets by right-clicking and selecting “Add to bookmarks / favorites” (in Chrome, you press “ctrl+shift+b” to open the bookmark manager, and drag them over). You can try them before you bookmark them by simply clicking the links on this page too.

Example One:


Clicking the above link will add the table sorter jquery plugin to the page, including its stylesheet, and it will apply the script to all tables on the page. Once it’s loaded, you can click on any of the table column headers to sort the rows by column values.

Example Two:

The visualizer bookmarklet will add graphical representations of the data in the table. As with the table sorter, this bookmarklet was adapted from a pre-existing plugin, Filament’s jQuery Visualize.

2009 Employee Sales by Department
food auto household furniture kitchen bath
Mary 190 160 40 120 30 70
Tom 3 40 30 45 35 49
Brad 10 180 10 85 25 79
Kate 40 80 90 25 15 119

(Continue This Article…)

How to use Firebug in IE6 (and all other browsers)

Yaknow, I’ve been using Firebug for quite some time, but I haven’t seen many places mention using it as a bookmarklet. Having gotten partway through programming my own makeshift javascript bookmarklet debugger, I was thrilled to find out Firebug Lite can be bookmarkletized too! Here’s the link – right click and add it to your bookmarks to try it out:

Free RapidShare Service & Countdown Bypass JavaScript

The free RapidShare downloads are pretty good – but the downloading process  is unnecessarily frustrating. Whereas many other providers drown their visitors with ads to generate revenue that pay for their servers (which is reasonable), RapidShare forces you to wait for no reason other than to frustrate you.

Fortunately, as adblocker has proven, we are capable and legally entitled to control the display of websites as we please. So, with no further ado, here is the solution:

Simply right click and bookmark the above link, so that next time you’re stuck on a web page that’s making you wait for no good reason, you can open the bookmark, and the countdown will immediately complete.

Here is a Rapidshare File to test it on.

(Continue This Article…)

Automated Link Building – White Hat Style

Yaknow, most of the time, black hat SEOs have all the fun. When you don’t have to follow the rules, the world of SEO opens up to mathematically generated content, canned-ham links, and any number of script based processes. Well, today is the day of the white hat, because I’ve just written a killer link building script that will amplify your honest successes.

Link Building Pro, based at seox.org, will automatically add a citation to the footer of any text copied from your website. Unlike other similar solutions, though, it specifically uses the meta keywords from the page as the anchor text – ensuring that the links use the precise keywords you’re optimizing for. And, here’s the best part, any text within the selection that matches the text of another link on the page will automatically be converted into that link. As a consequence, if this selection is then copied into the user’s site, you’ve not only gained one link of citation, but also as many links as logically apply to the text itself.

Of course, what makes this white hat is that it’s all voluntary. The user could easily remove the links if he chooses. But the default switches from being no citation or link to several, and as the default action is the easiest, it is also the one most often taken.

PS: Unfortunately, my previous script “Search and Share” interferes this script (doh!). For now, you’ll have to pick one or the other, but I’ve got big integration plans for the future!

Using jQuery Clone to Add Dynamic Data

As a User Interface Expert first and Programmer second, I put a lot of consideration into how I code. With every step, I do my best to ensure that designers with less programming experience will be able to accomplish what they’d like. This distinction in programming methods is most clear in how I place dynamic data onto the page.

Whereas many scripts embed the html markup into their javascript, I much prefer to leave it on the page. More specifically, I prefer to leave a model of the html on the page, and to inject the dynamic data using that model. As my example, I’ll continue yesterday’s post on a rolling delicious feed.

If you’d like to skip ahead, you can view the demo here, or scroll down to view the whole block of code.

But I prefer to break things down first. Let’s look at my so-called model:

<div id="deliciousList">
    <div id="deliciousModel" class="model item">
        <p><a class="url"><span class="title"></span></a></p>
        <p>Posted by: <span class="author"></span></p>
		<p>Tags: <span class="tags"></span></p>
    </div>
</div>

Notice that it creates the delicious list, and that inside it is an “item”. We’ll be identifying this model, and duplicating it as many times as we need to. When it’s duplicated, we’ll simply find the spans with the appropriate classes, and insert content. It’s easy and processor efficient, see for yourself:

// Clone duplicates the model (with bindings), strips model class/id, gives a unique id, and then adds it before the model
 $("#deliciousModel").clone(true).removeAttr("id") .removeClass("model").attr("id", "del" + i).insertBefore("#deliciousModel")

 // The finds get each class from within the model and replace it with values from the feed.
 .find(".url").attr("href", entry.u).end()
 .find(".author").html(entry.a).end()
 .find(".tags").html(processedTags).end()
 .find(".title").html(entry.d);

The first line does the cloning, removes the identifying attributes (and class model causes a display:hide;), and inserts the new block.

The subsequent lines insert the appropriate data. Each “find” and “end” here is really important. By chaining the javascript, we’re preventing the code from constantly searching the entire document, and we’re containing the modifications to the model itself.

For the entire block of code, view below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delicious Feed</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type="application/javascript">
    $(document).ready(function(){
// DELICIOUS JSON -- http://feeds.delicious.com/v2/json/tag/hyperstudio
$.getJSON('delicious-json.php', function(data){
$.each(data, function(i, entry) {

tags = entry.t;
tagLength = tags.length;
processedTags = '';

jQuery.each(tags, function(i, val) {
processedTags += ' ' + val;
if (i < tagLength - 1) processedTags += ',';
});

// Clone duplicates the model (with bindings), strips model class/id, gives a unique id, and then adds it before the model
$("#deliciousModel").clone(true).removeAttr("id") .removeClass("model").attr("id", "del" + i).insertBefore("#deliciousModel")

// The finds get each class from within the model and replace it with values from the feed.
.find(".url").attr("href", entry.u).end()
.find(".author").html(entry.a).end()
.find(".tags").html(processedTags).end()
.find(".title").html(entry.d);

if ( i == 10 )  return false; // Limit to 10 entries

});
});
    });
</script>
<style type="text/css">
html { font-size:10px; font-family:Arial, Helvetica, sans-serif;}
a {color:#066; font-size:12px;}
p {margin:0; padding:0;}
a:hover {color:#099;}
#deliciousList {border:1px solid #333; width:400px; margin:0 auto; padding:0 10px;}
.item {margin:10px 0;}
.clear {clear:both;}
.model {display:none;}
</style>
</head>
<body>
<div id="deliciousList">
    <div id="deliciousModel" class="model item">
        <p><a class="url"><span class="title"></span></a></p>
        <p>Posted by: <span class="author"></span></p>
<p>Tags: <span class="tags"></span></p>
    </div>
</div>
</body>
</html>

Calling Remote JSON Files via Javascript / jQuery

Not too long ago, I was asked to create a rolling delicious feed using their JSON data. It took me quite a while to realize what was going wrong – but the solution was obvious as soon as the problem became clear. If you’re going down the same path, maybe this bit of advice will help.

Firstly, you have to create a local reference of the JSON data. As I understand it, this has to do with the JSON server settings and security. In any event, it’s easy enough to do. Create a file, such as my delicious-json.php. All you need to put in it is this:


<?php
echo file_get_contents("http://feeds.delicious.com/v2/json/tag/hyperstudio");
?>

Easy peasy. Now you can reference it via jQuery, like so:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
$(document).ready(function(){
// DELICIOUS JSON -- http://feeds.delicious.com/v2/json/tag/hyperstudio
  $.getJSON('delicious-json.php', function(data){
    $.each(data, function(i, entry) {
      // Process your data here
    });
  });
});

How you use the JSON is up to you. In tomorrow’s post, I’ll describe my preferred method – cloning a model. Doing so has a lot of speed benefits, but more importantly, it separates the html from the javascript. As a consequence, any web designer can easily step in and modify the aesthetics without touching code. This facilitates the very important separation of concerns.

Div Class Clear – Without the Markup

The Div Class Clear is an old trick for getting container backgrounds to stretch down to the bottom of its contents. Although there has since been a push for the “float nearly everything” technique, I’m not convinced that constantly setting floats and widths across all elements is a sustainable method. Instead, let’s address the only problem people have with the Div Class Clear method – the added markup.

We can remove this markup quite simply with jQuery. Rather than mess with the actual on-page elements, why not insert it dynamically? Check out the code:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type="text/javascript">
    $(document).ready(function(){
$("*:last-child").filter(function() {
return $(this).css('float') != 'none';
}).parent().append("<div class='clear'></div>");
    });
</script>
<style>
.clear {clear:both;}
</style>

Note: As you may imagine, this method assumes that the viewer has javascript enabled. Given that the downside is a matter of background stretching, and considering all the numerous other things that break when javascript isn’t enabled, I (generally) readily accept this sacrifice. After all, it’s not like Flash, where they get no content at all.

Separating jQuery Functions into External Files (without selectors!)

In javascript, writing reusable blocks of code is easy. You simply enter something like: “function myFunction() { … }”, and then you later call it by simply writing “myFunction();”. Consequently, when I write jQuery, I often use this javascript shorthand within my jQuery ready tags. As long as all the code stays in a single file, things go smoothly.

But sometimes code grows, and when it does, you’ve got to separate your logic into separate external js files. That’s when things break. You see, in each of these external files, you now have to separately reiterate the jQuery ready tags, and when you do, you’ve buried your functions in a (jQuery) function, rendering it hidden. Out of scope. Or as the error console will tell you, “Missing”.

The trick is to create a jQuery function. There are articles all over the place that tell you how to do this. But every one that I’ve found seems to assume that you want your function to act on a selector. What I needed (and you may as well), was a function that acted just like that regular old javascript function (with jQuery syntax enabled). Believe it or not, all it takes is a minor tweek. Check it out:

External File (tilex.js):

  (function($){
    tile = function() {
      $("body").append('See? It works.');
    };
  })(jQuery);

Inline HTML:

<!DOCTYPE html>
<html>
<head>
<title>HyperStudio Timeline</title>
  <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="js/tilex.js"></script>

  <script type="text/javascript">
   $(document).ready(function(){
      tile();
    });
</script>
</head>
<body>
</body>
</html>

Common SEO Mistakes: CSS Image Replacement

Knowing about CSS Image Replacement and  Dynamic Text Replacement, as well as how to implement them, is undeniably valuable. As with most of SEO, having a developer’s skill set (or at least a knowledge of your options), will enable you with a can-do world view. In this case, when a client tells you that they’re committed to a web unsafe font for their headers, and that they therefore can’t use the appropriate keyword rich header tags, you’ll answer “yes you can”.

But there is a very common problem with over-zealous implementation of such SEO tactics without full consideration of their impact. Even SEOs who I have high regard for are victims of this vice. Have a look:

seomoz (Continue This Article…)