How to Sort an Associative Array (object) in Javascript

Javascript,Web Programming

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>
  • Digg
  • Sphinn
  • del.icio.us
  • RSS

How to Create a jQuery Bookmarklet

Javascript,Plugins,Web Programming,jQuery

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…)

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

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

Javascript,Web Programming

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:

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Free RapidShare Service & Countdown Bypass JavaScript

Javascript,Web Programming

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…)

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Where did Custom Players go in Youtube? (04/01/2010)

Media,YouTube

I’ll keep this short and sweet. At the beginning of this month, YouTube launched a redesign. With that launch, they “removed” the layout feature of custom players – which created a right column for YouTube Playlist Videos. Instead of this right column, the playlist videos appear below the video. While it’s graphically more slick, and I’m all for removing visual clutter, I’m not convinced it’s better in all scenarios, and it irritates me that the company would remove any feature from the realm of possibility.

Fortunately, although they don’t mention or link to it anywhere, you can still go directly to the old URL to create an modify these custom players /cp/.

Here is the link to create one:
http://www.youtube.com/custom_player

Here’s a link to view / edit them:
http://www.youtube.com/my_players

(Continue This Article…)

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Automated Link Building – White Hat Style

Javascript,Plugins,SEO (Organic)

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!

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

The Best Viral Marketing Text Citation (jQuery / WordPress) Plugin

Plugins,SEO (Organic),jQuery

Everyone’s seen social bookmarks, and yeah, they’re great. But even with them, your visitor has to specifically seek out promoting you. On the other hand, when you highlight and copy text from politico.com, it will automatically embed the URL.

Holy crap that’s cool!

Naturally, I wanted to do it too. But soon after beginning, I realized that there was still so much more to do. What is it that people wanted to do with the copied text? If the selection is long, perhaps it’s email or twitter. If it’s short (like a name or place), I’d bet it’s a search. My plugin takes Politico’s brilliant idea and gives it what Barry Bonds got.

To see the script in action, try highlighting any text on this page. For email or copy/paste credit, select 40+ characters of text. For specific search-worthy examples, try:

  • Wiki: Machiavelli
  • Google: World Trade Center, NY
  • Facts (Wolfram): Hamburgers
  • Amazon: 1984 by George Orwell
  • Ebay: XBOX 360

For more information about this plugin, visit the official Search and Share page. If you like it, I’d really appreciate you bumping me up on the social network of your choice. Thanks for the love!

PS: In case you missed the links the first time around, you can download the standalone jQuery version here, and you can download the wordpress version here.

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Get Email Alerts from Google Analytics

Google Analytics,PHP

Consider this Google Analytics Reports on crack. With this script, you can get an email when any of your websites drop in visit or page view counts (or anything else you want).

This plugin uses the Google Analytics API to send you reports conditionally, and is highly extensible, allowing you to pick and choose the stats you want to email based on, the threshold to notify you at, and which stats you want to send. Best of all, it accepts a list of websites within your account to check, such that you can be managing hundreds of sites, and only receive reports for the ones that need your attention.

Obviously, a notification of a significant decline in web stats could indicate a site being down, hacked, or busted in the search results. Ready to get it? You can download the Critical Alerts script here. Want help implementing it? Watch the video below for a blow-by-blow.

After watching the video, be sure to Subscribe to my RSS Feed, as I’ll be releasing more complex and elegant reports based on this script.

Also, in case it’s unclear in the Script (or if you want to copy paste it), the cron job to run is:
php ~/public_html/analytics/alert.php

Finally, a Special Thanks to:

  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Using jQuery Clone to Add Dynamic Data

Javascript,jQuery

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>
  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Calling Remote JSON Files via Javascript / jQuery

Javascript,PHP,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.

  • Digg
  • Sphinn
  • del.icio.us
  • RSS