Tag Archives: jquery

Getting More From Twitter Bootstrap’s Typeahead Library

Twitter Bootstrap comes packaged with a simple auto-complete library that’s stylistically integrated into the CSS framework. It’s convenient, but not the most-documented part of Bootstrap. I was working on a hobby project recently, and I wanted to have an auto-completing search field, but it took a bit of work to extend the basic implementation.

The first, and probably most important, step was to implement an AJAX data source. The plugin supports this out of the box, but the documentation page doesn’t have an example. It’s easy enough. You pass a function that takes the query and hands it off to one of jQuery’s magic asynchronous request functions, like so:

$(document).ready(function() {
		minLength: 3,
		source: function(query, process) {
			$.post('/search/typeahead', { q: query, limit: 8 }, function(data) {

Your request URL needs to respond with a JSON array of strings, which the typeahead library will process. The variables “q” and “limit” are sent along with the POST request in this example, and a PHP back-end returns the relevant data in response.

Continue reading →

Using Google-Hosted jQuery With a Local Fallback

Referencing commonly-used JavaScript libraries, like jQuery, stored on Google’s CDN is a good way to speed up your site. Many popular websites do so, which means the chances of a user having jQuery sitting in their browser cache already is pretty high. It doesn’t make a whole lot of sense to download it all over again for another website, does it? Using the copy on the Google Libraries CDN just makes a lot of sense.

But what if the servers Google has hosting it went down for some reason? Given Google’s track record, it’s not likely to be an issue, but it’s a good point. Fortunately, you can easily reference a backup. You can have a copy of jQuery on your server, and use a little bit of JavaScript to load it only if the Google one doesn’t load for some reason.

This little snippet, found in HTML5 Boilerplate, will do just that:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.4.min.js"><\/script>')</script>

This should even work with WordPress, if you put the second script line right before the </head> tag in your theme.

Google +1 Content Unlocker with jQuery

You’ve probably seen sites like MacHeist and Make Use Of run promotions where you can unlock a software license or enter a drawing for an iPad by posting a message to Twitter or Facebook and then entering your email address into a form that magically appears after. It has also become an increasingly common practice for recording artists to give away free music downloads in exchange for Liking them on Facebook.

There’s probably sufficient documentation on how to implement this sort of thing with Twitter, so let’s try something a bit different. How about those new Google +1 buttons?

The +1 button has a convenient JavaScript callback that could be used for all sorts of fun things, such as un-hiding content on the page.

First, you need to put the button markup on your page, as well as the content you wish to hide until said button is clicked. The DIV holding the content should of course be hidden by default. Be sure to set the callback parameter of the button.

<div id="plusonebutton">
 <g:plusone callback="plusone_callback" href="http://www.webmaster-source.com"></g:plusone>

<div id="plusonecontent" style="display:none">
 <p><strong>The user has clicked the +1 button.</strong> Here's some content that was not previously visible. Lorem ipsum dolor sit amet.</p>

Next, you want to include the +1 script and jQuery in your page header. After you’ve taken care of that, you need to write your callback function. The function fires when the button is clicked (assuming the name matches the one specified in the button parameter) and passes a JSON object containing the button state, among other things.

<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

<script type="text/javascript">
 function plusone_callback(response) {
 if (response.state == 'on') {

The callback should check the JSON object to see whether the state is set to “on” rather than “off,” and replace the button with your hidden content if that is the case.

You can see a demo of the finished page here.

I don’t know whether Google frowns upon this sort of thing or not, but it would be a great way to provide a surprise bonus (e.g. an ebook or song download) when someone likes one of your pages. So, just don’t use it for anything spammy or deceptive and you should probably be fine.

Update: It has come to my attention that this could be used in many crappy ways, such as those irritating people who force you to Like a video on Facebook before they let you watch it. (Which is completely against the spirit of the concept, as well as social media.) Don’t do stuff like that. Seriously.

Get Twitter and Facebook Link Statistics with JSON and jQuery

Both Twitter and Facebook have little JavaScript widgets that allow you to share a page using the respective service, displaying a running total of users who have done so. While that’s fine for most purposes, what if you just need the count, for some atypical application?

It’s not well-documented, but the two social media sites have JSON APIs for that purpose.

With a little bit of jQuery magic, you can collect the values on page load and update the DOM with the number. Here’s something I threw together for a project I was working on:

(function() {

var url = 'http://xkcd.com/792/';

jQuery.getJSON("http://urls.api.twitter.com/1/urls/count.json?url="+url+"&callback=?", function(data) {
jQuery('#socialstuff span.twcount').html(data.count);

jQuery.getJSON("https://graph.facebook.com/"+url+"&callback=?", function(data) {
jQuery('#socialstuff span.fbcount').html(data.shares);


As long as you remember to include jQuery, and have the right HTML elements for the JavaScript to populate, it’s pretty much plug-and-play.

You can see it in action here.

Pure JavaScript QR Code Generator with jQuery

Need a fast and lightweight way to generate QR codes in-browser, without relying on a third-party service? There’s a new jQuery plugin that’s exactly what you’re looking for. Weighing in at only 4kb, it generates QR codes using only JavaScript—no image resources, no calls to remote servers.

After including it in your page, and jQuery of course, you create an empty DOM element to hold the QR code (a DIV, for example) and then you just do something like this:


The plugin is available on GitHub, and is released by the author under an MIT license.

An alternative, for those of you who don’t mind using a third-party service—and prefer simply including an image rather than extra JavaScript—can use the wonderful Google Chart API.

Tempo: A Tiny JSON Templating Engine

Tempo is a 4kb JavaScript library that renders JSON into an HTML template. Your script can take something like this…

<ol id="tweets">
 <li data-template>
  <img src="{{profile_image_url}}" />

…and populate it with JSON data from the Twitter API, which you could load with a couple lines of jQuery. It works with browser as far back as IE6 and doesn’t require any dependencies.

It seems like a friendlier way to deal with JSON data, and it offers the advantage of any templating system: you can separate the logic and data from the presentation.

MediaElement.js — HTML5 Video Player With Flash Backup

Many modern web browsers have early support for the <video> and <audio> elements in the HTML5 spec. Unfortunately, their implementation varies depending on the ideals of the various browser developers. Safari expects video to be encoded in the high-quality H.264 codec, other browsers prefer Ogg Theora. Google is trying to push their own freely-licensed VP8 codec, which Mozilla is showing signs of adopting. Then there’s Internet Explorer, which doesn’t support the <video> element at all.

Thankfully, there’s a way to fairly easily support everything. You can offer HTML5 video in one or more formats and fall back on Silverlight or Flash if necessary.

MediaElement.js allows you to do that with a little bit of jQuery voodoo. After including all of the required files, you can serve-up an H.264 video for Safari and iPhone/iPad users like so:

<video src="myfile.mp4" type="video/mp4" width="640" height="360"></video>
jQuery(document).ready(function($) {

There is also a way to specify more than one video type in the <video> element, if you have re-encoded it into more than one codec:

<video width="640" height="360">
<source src="myfile.mp4" type="video/mp4" >
<source src="myfile.ogg" type="video/ogg" >
<source src="myfile.webm" type="video/webm" >

You will want to check it out if you’re interested in cross-browser compatible web video.

Lazy-Loading Images

You may have noticed that a lot of large blogs, like Smashing Magazine and the TUTS+ network, are “lazy-loading” images in their posts. Sometimes, as you scroll through a post full of images, you might catch an image fading in just as it comes onto the screen.

This technique is known as lazy-loading. It makes web pages appear faster, and can save a little server bandwidth. Instead of loading all of the large images on a page, you use JavaScript to delay their loading until they’re needed. This makes the initial page load faster. As the user scrolls down the page, the script loads the images just before they’re needed and places them in their spots.

There is a jQuery plugin you can use for lazy-loading images on any page.

For WordPress users, there is an easy to install WordPress plugin that implements the jQuery lazy-load plugin for you.

Like it? Tweet it! A JavaScript TweetMeme Alternative

“Like it? Tweet it!” is a new JavaScript widget by Andy Graulund that, using Twitter @Anywhere, provides an easy way to display a box for people to tweet about your posts. It automatically loads a shortened URL and let’s you write a message to go along with it.

It provides more customization options than the alternatives, namely TweetMeme. You can use any link as a trigger for the overlay, and it’s possible to re-style the box. You can also change much of the text used, and set which short URL is placed in the tweet.

The only drawback is that users have to connect their account with the application. It only has to be once, and the user can then use any Like it? Tweet it! box around the internet. This is something that has been bothering me about the Twitter @Anywhere platform. Why should a basic tweet box or follow button widget require the authorization process, while the follow buttons in hovercards don’t? Why can’t they use the user’s Twitter login cookie like the hovercards do?

Use Google-Hosted jQuery in Your WordPress Theme

How many sites use popular JavaScript libraries like jQuery? A lot. That’s why Google hosts many of them on their speedy CDN, so browsers only have to download jQuery or Prototype once in a day, instead of once per site.

How can your WordPress-powered site benefit from this? Digging into WordPress has the answer:

if ( !is_admin() ){
   wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"), false, '1.3.2');

This little snippet goes in your functions.php, where it deregisters WordPress’s internal copy of jQuery and references Google’s. Unfortunately, it’s not set up for the handy no-conflict mode that lets you use Prototype scripts on the same blog.

Page 1 of 3123