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

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.

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.

Make Enter Key Tab in Forms

Sometimes, web browsers really suck. Default form behaviors are a major cause for suckage – but  good UI developers can override them. Heck, if you know how to copy and paste, you’re halfway there. I’ve patched together the following script, which converts the enter tab into a tab click when a form input is focused. Try it for yourself by copying it into the header of your page:

<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(){
$("input").not( $(":button") ).keypress(function (evt) {
if (evt.keyCode == 13) {
iname = $(this).val();
if (iname !== 'Submit'){
var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false;
}
}
});
    });
</script>

If you need some html code to test it with, you can use:


<form id="form1" name="form1" method="post" action="http://www.disney.com">

<label>
<input type="text" name="textfield" id="textfield" />
</label>
<label>
<input type="text" name="textfield2" id="textfield2" />
</label>
<label>
<input type="text" name="textfield3" id="textfield3" />
</label>

<label>
<input type="submit" name="button" id="button" value="Submit" />
</label>
</form>

If you’d prefer, you can try a live demo of the Enter to Tab on this site.

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>

Browsers Trim Pixel Decimals

In all browsers but FireFox, if you have 3 equal-height divs stacked that together should equal 100px in height, you’ll end up with 99px. And if you have 30 divs stacked that together should equal 1000px, you guessed it, they’ll only reach 990px high. This is because all 33.33~px height divs will be rounded down to 33px, and the remainder is lost.

The best solution to this problem is to save and carry over the decimal point via javascript. Setting each div to be absolutely positioned might work, but is pretty heavy on the browser, and less than ideal for layout. Here’s what the code change that I’ve written looks like:

Where my code began as:

$(".oneYear li").css("height", someFraction);

My code became:

$(".oneYear li").each(function(i){
    decFix = (fixSomeFraction%1); // get the decimal value
    fixNewSmallUnitSize = parseInt(fixSomeFraction); // set fix size to an integer
    $(this).css("height", fixSomeFraction); // assign height to the fix size
    fixSomeFraction= someFraction + decFix; // add the decimal remainder to the unit size for next time
  });

First I store the remainder by dividing the fraction by one (in other words, just the stuff after the decimal). Second, I convert the number to an integer, which strips everything after the decimal. I then assign this whole number to the div’s height. And finally, I add the stored decimal value to the next div, which may or may not be bumped up by one pixel consequently.

What you see happening here is essentially just a slight modification of the loop that jQuery has to make to all the “.oneYear li” elements anyway. Although it’s easy to forget that jQuery performs this work behind the scenes, it does, and knowing that will allow you to most efficiently redefine the process for your own purposes.