jQuery, Radio-buttons and attr(‘checked’)

To make this a bit more searcable on the magic intarwebs:

jQuery 1.6.x changed the behaviour of attr(‘checked’), as it is no longer used to manipulate the state of radio buttons (or other elements using the checked element). This is considered a property, not an attribute (the difference is subtle), so instead of:

    $("#element").attr('checked', 'checked'); // or
    $("#element").attr('checked', true);

The correct ™ way of doing this is:

    $("#element").prop('checked', true);

Complete Example of Tracking Start and End of Drag Operations with jQuery and Table Rows

After writing my previous post about “Keeping track of indexes while dragging in jQuery UI Sortable” I received a question about how this would work for sortable table rows. The code I included in the previous post should actually be enough to make everything work (.. as long as I understood the question correctly). I’ve created a minimal example as a complete implementation of the code from the previous post, and I’ve also included it as a live demo here.

This is based on jQuery 1.5.1 and jQuery UI 1.8.13. I’ve simply used the distribution versions of this example (you probably want to build your own UI bundle using the interface on the jQuery UI website).

Here’s a live demo that you can play with.

Inline javascript and WordPress could possibly be better friends.

The complete source for the minimal (but complete) example is included here:

        jQuery UI Example Page
Dragging from index
Hovering index
Keys Values
Key 1 Value 1
Key 2 Value 2
Key 3 Value 3
Key 4 Value 4
Key 5 Value 5
Key 6 Value 6

Keeping track of indexes while dragging in jQuery ui.sortable

While you’re handling a drag operation in the jQuery UI Sortable handler, there’s a few small issues that might almost drive you insane. These two solutions are based on information from various places on the net (such as a few discussions on Stack Overflow).

If you want to keep track of which location the item you’re dragging originated from, you can attach to the ‘start’ event in the Sortable configuration constructor. Use this event to attach the origin index as a data element:

start: function(event, ui) {
    ui.item.data('originIndex', ui.item.index());

If you want to find out what index the user is currently hovering above (to change the numbering of a list instantly), you can use the same method on the placeholder element (available as ui.placeholder, so to fetch the current index the user is hovering over, call ui.placeholder.index()). There is however a gotcha’ here, as the original element is still present in the list – just allow to float freely around (the dragging action). We handle this by fetching the origin index and subtracting one if we’re after the location we started at.

You can handle these events in the ‘change’ event handler:

change: function (event, ui) {
    var originIndex = ui.item.data('originIndex');
    var currentIndex = ui.placeholder.index();

    if (currentIndex > originIndex)
        currentIndex -= 1;

    // do magic

jQuery, .getJSON and the Same-Origin Policy

When creating a simple mash-up with data from external sources, you usually want to read the data in a suitable format – such as JSON. The tool for the job tends to be javascript, running in your favourite browser. The only problem is that requests made with XHR (XMLHttpRequest) has to follow the same origin policy, meaning that the request cannot be made for a resource living on another host than the host serving the original request.

To get around this clients usually use JSONP – or a simple modification of the usual JSON output. The data is still JSON, but the output also includes a simple callback at the end of the request, triggering a javascript in the local browser. This way the creator of the data actually tells the browser (in so many hacky ways) that it’s OK, I’ve actually thought this through. Help yourself.

In jQuery you can trigger the usual handling of events by using “?” as the name of your callback function. jQuery will handle this transparently and then trigger the function you provided to .getJSON in the first place.


url = "http://feeds.delicious.com/v2/json/recent?callback=?";

$.getJSON(url, function(data) { alert(data); });

There’s an article up at IBM’s developerWorks giving quite a few more examples and information about the issue.

Avoiding Resetting the Scroll Position in a Textarea When Inserting Content

Now, that’s quite a headline. And this post will explain just the simple concept posted in the headline. How to avoid (at least) firefox from scrolling to the top when you insert content into a textarea.

It’s simple. Very simple. And it was shown to be so very simple for someone who didn’t remember scrollTop by this thread.

In jQuery (which we use with the caret plugin):

currentScrollPosition = $("#textareaId").scrollTop();
/* do stuff */

Yep. So simple that it actually hurts a bit.

An Update to jQDynamicFontSize

When we released jQDynamicFontSize a couple of weeks ago, we hoped that others would find the plugin useful and keep it around as one of the many tools in your toolbox. We also had a small hope that people would find it useful to extend and maybe submit a patch or two back to us.

And lo’ and behold, during the weekend the first patch arrived in my mailbox. Written by Vegard Andreas Larsen, we now also support scaling against the width of a container. I didn’t even have an idea around this, and suddenly we have working code. The power of open source!

This adds two new options when initializing jqDFS:

  • limitWidth: Uses the width of the element to determine the size instead of the height. Defaults to false.
  • allowUpscaling: Allows the element to grow instead of shrink to fit the provided area. Only works when limitWidth is active currently. Defaults to false.

The original scale method should probably be rewritten to also use allowUpscaling, so if anyone feels slightly hackish tonight, just send the patch my way!

Introducing jQDynamicFontSize – A jQuery Plugin for Dynamic Font Size

We’ve released the first version of jQDynamicFontSize – a jQuery Plugin for dynamically adjusting the font size of an element to fit a number of lines. The plugin was written to allow us to resize a headline to make the headline fit on one line, sacrificing text size to avoid breaking text into two lines.

To paraphrase from the INSTALL file:

In a production system, use jquery-dynamicfontsize.min.js. For debugging
or developing, use jquery-dynamicfontsize.js.


Include a reference to the script after loading jQuery:

<script src="jquery-dynamicfontsize.min.js"></script>

Then call:


This will attempt to scale the font size of the element down with 10% in
3 iterations, stopping when a value has been found that allows the element
to only use one text line.


This will attempt to scale all h1 elements. Other jQuery selectors will also

Options supported:

    * squeezeFactor: A float value that will be used as the squeeze factor
      for each step. 0.1 means that we'll attempt to scale the font-size down
      10% for each iteration. Defaults to 0.1.
    * lines: The number of lines we'll attempt to fit the text to. When the
      text fits this (or a smaller) amount of lines, we'll stop scaling.
      Defaults to 1.
    * tries: The number of iterations we'll try before we give up and go with
      the last result. Defaults to 3.

We do currently not care for the line-height of elements, so if you’re feeling slightly hackish tonight, feel free to add the required piece of javascript goodness. Any suitable patches are welcome!

jQuery – IE triggers several click events

Strange problem occurred today, one of the very rare occasions were the behaviour of jQuery differed between Internet Explorer and Firefox. I’ve been trying to create a minimal example that replicates the behaviour, but have failed so far.

The problem was that in IE a click event triggered several times, which led an element to be expanded and then contracted again. This did not happen in Firefox. I found out that the problem was that I had placed my jQuery segment further inside the loop than I meant to, leading to code being duplicated four or five times through the page. After removing the duplicated function names and binds to .click(), everything worked as it should.

If you get several events triggered in Internet Explorer, but not in Firefox, check that you’re not accidentally binding the same function several times (.. while creating a minimized example that does this, I got the expected behaviour in both browsers, so I’m not completely sure of the reason). It might be worth a try as a fix, tho.

Whoisi – Social Aggregation

Just found out about whoisi.com through John Resig, and it’s quite a nifty little app. It aggregates several feeds in the context of an individual. The application does not require any login, and builds on the collection of all resources people are able to gather for one particular individual. I’ve collected the available feeds for myself over at my whoisi.com page, so that you can actually follow my flickr page, my twitter and my blog from one location. If you have any other resources where I’m contributing (maybe my youtube-feed?), feel free to add them.

I also suggest playing with the “random person” feature, I’ve had quite a bit of fun with that one today.

Number one feature: I don’t have to log in at Whoisi. Amazing. I just get a personalized link that I can email to myself for storage or simply bookmark it in my browser (or private on a bookmark site). No hassle. No email. No person information. Instant win.

You can read more about the technical implementation over at Christopher Blizzard’s blog.