Archive for 'jQuery'

AjaxQueue and jQuery 1.3

800px-Queue_algorithmn The website that I work on for the majority of my time had been running on the rather out of date jQuery 1.2 for quite some time. I recently found myself with a little bit of downtime and decided it was a good time to see if we could upgrade and take advantage of all the speed improvements that the latest version gives us.

On the most part, the upgrade was fairly painless. Most things worked without change but one particular plug-in did not – AjaxQueue. This is a great little control that acts as an add-on to the ajax method of jQuery, allowing a little more control over how concurrent calls are processed. It gives three modes of operation but for us, the most useful of these are abort and queue and from the names it is fairly obvious what they do.

After I upgraded to jQuery 1.3, it did not take me long to realise that the queue mode was broken. I briefly looked around for an alternative plug-in but found that all of them would require too much change to our existing controls. There was no alternative, I had to open up the hood of AjaxQueue and see what had gone wrong.

What I found was that there must of been a change to a method that the plug-in relied on – a method that it seemed, only became publicly available in version 1.3 – queue. Although the function was similar, the conclusion that I came to was that prior to version 1.3, the queue function automatically de-queued any function added and processed it. When using the latest jQuery, the ajax calls were queued but there was no code to start the processing of the queue.

It was slightly more complex I thought it would be to get it going – I had to ensure the queue was only started once. I finally came up with a solution and a newly revived plug-in, the code of which is below. As the original plugin has not been touched for quite some time (2007), I thought it ok to post my modified version here.

(function($) {
 
    var ajax = $.ajax,
        pendingRequests = {},
        synced = [],
        syncedData = [],
        ajaxRunning = [];
 
 
    $.ajax = function(settings) {
        // create settings for compatibility with ajaxSetup
        settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings));
 
        var port = settings.port;
 
        switch (settings.mode) {
            case "abort":
                if (pendingRequests[port]) {
                    pendingRequests[port].abort();
                }
                return pendingRequests[port] = ajax.apply(this, arguments);
            case "queue":
                var _old = settings.complete;
                settings.complete = function() {
                    if (_old) {
                        _old.apply(this, arguments);
                    }
                    if (jQuery([ajax]).queue("ajax" + port).length > 0) {
                        jQuery([ajax]).dequeue("ajax" + port);
                    } else {
                        ajaxRunning[port] = false;
                    }
                };
 
                jQuery([ajax]).queue("ajax" + port, function() {
                    ajax(settings);
                });
 
                if (jQuery([ajax]).queue("ajax" + port).length == 1 && !ajaxRunning[port]) {
                    ajaxRunning[port] = true;
                    jQuery([ajax]).dequeue("ajax" + port);
                }
 
                return;
            case "sync":
                var pos = synced.length;
 
                synced[pos] = {
                    error: settings.error,
                    success: settings.success,
                    complete: settings.complete,
                    done: false
                };
 
                syncedData[pos] = {
                    error: [],
                    success: [],
                    complete: []
                };
 
                settings.error = function() { syncedData[pos].error = arguments; };
                settings.success = function() { syncedData[pos].success = arguments; };
                settings.complete = function() {
                    syncedData[pos].complete = arguments;
                    synced[pos].done = true;
 
                    if (pos == 0 || !synced[pos - 1])
                        for (var i = pos; i < synced.length && synced[i].done; i++) {
                        if (synced[i].error) synced[i].error.apply(jQuery, syncedData[i].error);
                        if (synced[i].success) synced[i].success.apply(jQuery, syncedData[i].success);
                        if (synced[i].complete) synced[i].complete.apply(jQuery, syncedData[i].complete);
 
                        synced[i] = null;
                        syncedData[i] = null;
                    }
                };
        }
        return ajax.apply(this, arguments);
    };
 
})(jQuery);

Cuesheet Maker Bookmarklet for Discogs.com

Yesterday I discovered I had a few albums that had been ripped as a single track. I prefer having individual tracks and usually head on over to cuesheet heaven to look for the appropriate file that allows me to split them up with the awesome Medieval Cue Splitter. However I had a few tracks that had I could not find the appropriate cuesheet file for. I find myself in this situation fairly regularly and have also noticed that these albums usually have an entry at discogs.com, which has all the details including track lengths.

This got me thinking that it would be awesome to be able to create cue files from discogs.com. So I created the following – a bookmarklet to do just that.

Disclaimer: it is pretty rough and I cannot guarantee that it will work with all discogs.com entries and there is hardly any error checking. I have only used this in Firefox so I cannot guarantee it will work in any other browser. It only pops up a dialogue with the cuesheet contents on it but that was adequate for me to copy and paste it into a text file and tweak it so that it was a valid cuesheet.

The important thing is that it gathers the track names and artists and works out the index times. It also attempts to cope with double cds and also single tracks that are two different records playing at once (common with DJ mixes). Here is the bookmarklet (drag it into your bookmarks tookbar), followed by the code itself:

Drag this to your bookmark toolbar: Create Cue

The code itself:

javascript:(function(){var s=document.createElement('SCRIPT');
s.type='text/javascript';
s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js';
s.onload=function() {
	var title = jQuery.trim(jQuery('div.profile h1').text()),
		performer = jQuery.trim(title.substring(0,title.indexOf('-'))),
		file = title + '.mp3', secCount = 0, trkCount = 0, cues = [], cdNo = 1;
	title = jQuery.trim(title.substring(title.indexOf('-')+1));
	tracks = [];
	jQuery('div.tracklist .section_content > table tr').each(function(ix, el) {
		var trackCd = jQuery.trim(jQuery('td.track_pos',this).text());
		if (trackCd && trackCd != '') {
			var track = {}, tracktime = [], isDouble = false;
			trackCd = trackCd.split('-');
			if (trackCd.length > 1) {
				if (jQuery.trim(trackCd[0]) != cdNo) {
					createCue();
					cdNo = trackCd[0];
				} else {
					if (parseInt(trackCd[1]) == trkCount) {
						isDouble = true;
					}
				}
			}
			if (!isDouble) {
				trkCount+=1;
				track['trackno'] = trkCount;
				track['artist']= jQuery.trim(jQuery('td.track_artists',this).text()).replace(/\s-$/g, '').replace(/\n/g, '').replace(/\s+/g,' ');
				track['artist'] = jQuery.trim(track['artist']);
				track['artist'] = (track['artist'] == '') ? performer : track['artist'];
				track['title'] = jQuery.trim(jQuery('td.track_title',this).text()); 
				tracktime =jQuery.trim(jQuery('td.track_duration',this).text()).split(':'); 
				track['index'] = secondsToMinSec(secCount);
				secCount += (tracktime[0] * 60) + (tracktime[1] * 1);
				tracks[tracks.length] = track;	
			}
		}
 
	});
 
	createCue();
 
	//print it out
	var output = '';
	jQuery.each(cues,function(ix, cue) {
		output += cue + '\n\n\n';
	});
 
	alert(output);
 
	function createCue() {
		var quo = unescape('%22'),
			cue = 'TITLE '+quo+title+quo+'\n';
		cue += 'PERFORMER '+quo+performer+quo+'\n';
		cue += 'FILE '+quo+file+quo+' MP3\n';
		jQuery.each(tracks,function(ix, track) {
			cue += '  TRACK '+track.trackno+' AUDIO\n';
			cue += '    TITLE '+quo+track.title+quo+'\n';
			cue += '    PERFORMER '+quo+track.artist+quo+'\n';
			cue += '    INDEX 01 '+quo+track.index+quo+'\n';
		});
		cues[cues.length] = cue;
		//reset
		secCount = 0; trkCount = 0; tracks = [];
	}
 
	function secondsToMinSec(totsec) {
		var min = Math.floor(totsec / 60), 
			sec = (totsec - (min * 60));
		if (min < 10) {
			min = '0' + min.toString();
		}
		if (sec < 10) {
			sec = '0' + sec.toString();
		}
		return min.toString() + ':' + sec.toString() + ':00';
	}
};
document.getElementsByTagName('head')[0].appendChild(s);})();

I hope this helps some people, as it has me. Feel free to improve on it but if you make any changes, please let me know so that I can improve my version too.

Enjoy

Edit: Well it was not long until discogs changed their layout. I have update the code to reflect this. All should be well again.

Facebook-Style Expanding Textboxes With jQuery

Characters I was recently asked to create a textbox that would vertically expand depending on how much was written in it. This style of text box can be seen in the Facebook news feed for writing comments under peoples feed items. When I receive this type of request, I usually begin by researching what existing systems and plug-ins are out there, investigate the different approaches people take and then write my own based on which way I think best.

Firstly, a textbox (input type=text) is the wrong element to be using. It cannot be any larger than a single line, so a text area element needs to be used. As a text area element will not automatically expand by itself, the general approach to this problem is to use a hidden ‘staging’ element placed way off the viewable screen. The text entered into the text area is copied across to the staging element, which expands as needed and the resulting height used to resize the text area. It is not a difficult thing to achieve with jQuery and the basic structure of the plug-in can be made in relatively few lines of code.

There are a few things to watch out for however. Firstly, because we are taking the contents of a text area and placing it in a div, we need to watch out for special characters that need encoding before they will render correctly. Primarily the newline character but we also have to watch out for the other special characters that can cause issues. Nothing that cannot be fixed with regular expressions. The other thing that we need to be careful of is the CSS styles that have been applied to the text area. We require that the hidden element perfectly mimic the text area and that the text wraps at the same point. If it does not, we will incorrectly predict when the text area needs to grow. The font size and family, line height and padding need to be copied.

This would normally be the point that I post the code, but after I started writing the plug-in, I stumbled across an existing one that I could just not improve upon and decided to use it in it’s entirety. Its by a guy called Jason Frame and his plug-in can be found on github. For my particular implementation, I added the facility to have watermark text in it by utilising the great plugin over on digital bush and I also added some text parsing requirements that were required for the particular project.

Now for a word of warning. There are some problems with this approach, which I have not managed to solve (and incidentally, nor have Facebook). The text area element renders it’s content slightly differently in every browser. In the hidden element, the text will sit up directly against the edge of the div but in a text area it may not. I suspect this gap also varies from operating system to operating system but as far as I can tell, you cannot eliminate it with styles. The consequence of this is that predicting precisely when the text area needs resizing becomes very difficult. The only thing to do is to accommodate this margin of error. This can be done by making the text area display slightly taller than a single line and to always have an extra line available. That way, if things go slightly off, it is still usable. You can see this problem if you put a significant amount of dummy text into the text area and watch when it expands as you type. Instead of expanding when you reach a new line it happens at a different place. If any one manages to figure out how to completely eliminate this problem I am eager to hear how.

The Importance of a Good jQuery Selector

As a technical lead and working in a company that has had rapid expansion in the last six months or so, I have had the job of being a mentor to some of the new employees. I don’t think any of them had used jQuery before and so for every person that arrived, I needed to give a crash course on the subject. The jQuery selector is always one of the first things I describe and it is usually met with nods of understanding, as it is not a difficult concept to grasp when most developers are familiar with css and the DOM.

There have been two incidents recently however, that have made me realise that my crash course on jQuery selectors has been missing something vital. The first was when I found some time to explore the options of profiling some of our javascript code. When I first started this, the only option I could see was John Resig’s deep profiling script that injected the statistics at the bottom of the page. This had some limitations however, and I was very happy to open my news feeds soon after and find that he had added a couple of extra methods to FireUnit that enabled you to profile javascript function calls.

What I noticed straight away was that there were a lot of seemingly simple calls in our code that took a long time to execute. The reason for this was that the selectors were vague:

    $('.myclass').somefunction();

In order to find all the matches, even if there is only one, jQuery needs to traverse the entire DOM looking for any element that might have the matching class, and that takes time. By narrowing down the selector using, for instance, the type, jQuery can very quickly eliminate all other types. This speeds things up a lot.

The second incident was due to another ‘benefit’ of being a tech lead. I tend to get passed the most peculiar and hard to diagnose bugs. The bug in question was on a page that contained two autocomplete text boxes, one of which was part of a compound control. The bug manifested itself by not being able to select an item from the second autocomplete text box properly. I was handed the bug with the information that it seemed to happen only when you selected from the first autocomplete control first. Needless to say, there was a lot of poking around in the code of both the autocomplete and the compound control, which is particularly complex given the nature of the control.

Thanks to firebug’s great console logging, I discovered that the variable that contained all the autocomplete list items seemed to be a combination of both controls. It was not too long before i discovered the code that caused the problem:

    listitems = $('.auto').children('li');

There was nothing mysterious going on at all, jQuery was asked to select all of list items in both controls, so it did.

What had happened in both of these incidents is that I had failed to mention the importance of an accurate selector in jQuery during my crash course. The new developers were blissfully unaware of the consequences of not specifying exactly which elements you want jQuery to select. What I had also failed to emphasise was another way of narrowing down and speeding up the jQuery selection – by use of the elements that you already have. In the case of the autocomplete, we already had a reference to the list itself, so it was simple:

   listitems = thelist.children('li');

This not only eliminated the cross-contamination of the two controls but seeded things up. So the rules to keep things fast and to save me headaches are simple:

  • Use a selector that very accurately matches the elements you require
  • Utilise references to elements you already have

jQuery Plugin Callbacks and Events

I have written a fair few plugins for jQuery for both work and side projects. As any developer should, I am always trying to improve my techniques for creating them so that they are as efficient and maintainable as possible.
Up until recently, my usual technique for callbacks and events would be to include the function in the options that you pass in. For instance, you would setup you plugin as follows:

1
2
3
4
5
6
7
8
9
10
11
(function($) {
    $.fn.myPlugin= function(options) {
        var settings = {
            setting1: 0,
            setting2: ''
        };
        //overload default settings
        if (options) { jQuery.extend(settings, options); }
 
        return this.each(function() {
        .....

This would allow you to pass in any number of settings, including callbacks to utilise at runtime:

1
2
3
4
5
  $('#myselector').myPlugin({ 
        setting1:1234, 
        setting2:'somesetting',
        callback1: function() {}
  });

Yesterday it occurred to me that jQuery had a neat feature that is much better than doing this – custom event binding. jQuery not only allows you to bind the DOM events to elements such as click, focus, keydown etc but because of the way it stores all the bindings, you can bind any number of custom events as well. This means that you can set your events for the plugin as follows:

1
2
3
4
$('#myselector').myPlugin({ 
        setting1:1234, 
        setting2:'somesetting'
}).bind("mycallbackevent", function() {...});

Within your plugin you would need to trigger that event like so:

$(this).trigger("mycallbackevent", [somedata]);

This technique also provides a neater alternative to public functions on your plugin. Say you wanted to initialise the plugin when a link is clicked. I would have previously setup a public function in the plugin to do this:

this.init = function() { .. }

and then run it as follows:

$('a').click(function() { $('pluginselector').get(0).init(); }

With custom events you would setup the event inside the plugin as follows:

$(this).bind('init',function() { .. });

and run as follows:

$('a').click(function() { $('pluginselector').trigger('init'); }

Perhaps I have just been writing plugins incorrectly all this time but that seems much better to me.

jQuery Inline Confirm

I have been using Delicious social bookmarking service ever since Blinklist degraded and finally lost the plot with their new design. When I first started using Delicious, a feature of their interface really leapt out at me and I could not wait to include it into a project.
The feature I am talking about is their inline confirmation. That is, when you, for instance, delete a bookmark by clicking on the delete link, the link is replaced with an ‘Are You Sure? Yes/Cancel’ message.

Inline Confirm - Before

Inline Confirm - After

I really liked this as there was no page refresh for the confirmation message and it was not a modal popup, which is a little obtrusive at best. It also occurred to me that something like that would not require a huge amount of code either. This is what I came up with:

1
2
3
4
5
6
7
8
9
$.inlineconfirm = function(el, callback, parentSel) {
        var hideEl = parentSel ? $(el).parents(parentSel) : $(el);
        hideEl.hide()
        $('<div class="confirm">Are you sure? <a class="confirmyes" href="#">Yes</a> <span>|</span> <a class="confirmcancel" href="#">Cancel</a></div>')
            .find('a.confirmyes').click(function() { callback(); hideEl.show();  $(this).parents('div.confirm:first').remove(); return false; }).end()
            .find('a.confirmcancel').click(function() { hideEl.show(); $(this).parents('div.confirm:first').remove(); return false; }).end()
            .insertAfter(hideEl);
        return false;
    }

I decided on using just a function rather than a plugin, as I wanted asp.net control compatibility (see later). The function just swaps out the element(s) for the confirmation message and puts them back if cancel is pressed, otherwise it runs the callback. It utilises three parameters:

  • el – The element which initiates the inline confirm. i.e. The link
  • callback – A function to run if the answer is Yes
  • parentSel – (optional) This is a jquery selector that identifies a parent element of el that will be replaced with the prompt. This is so that you could for instance hide an entire section of html with the ‘are you sure?’ prompt. Particularly useful to keep layouts consistent.

This is a nice easy function to use in most web development language, however, if you are using asp.net, it becomes difficult to use it with the asp controls like <asp:Button /> or <asp:LinkButton />. This is because ASP.NET likes to take control of the click events of these so that it can create its event model at the server. There is the onClientClick property which allows us to have some control over the click event but we need to pass a callback function. After a little investigating, I discovered the GetPostBackEventReference function:

mylinkbutton.OnClientClick = "$.inlineconfirm(this,function() {" & ClientScript.GetPostBackEventReference(mylinkbutton, "") & ";});return false;"

The GetPostBackEventReference returns a string of the function that will be used to invoke the postback. Just what we needed.

The Technical Debt

I have spent the last few days at work doing some intense refactoring of a seemingly complex jQuery plug-in. I managed to cut it down by 140 lines and speed it up immensely. Whilst it would have saved time if I had written the plug-in myself in the first place, I cannot be expected to do everything and nobody else at work would improve their jQuery and javascript writing skills if I did so. I therefore label my time spent as paying of some of the technical debt that we create, in the process of releasing the software as quickly as we can. If you have not come across this metaphor before, here it is:

It really nails the reason that as developers, we try to refactor regularly. Unfortunately refactoring is not something that people outside of the development community tend to understand and it is considered a waste of time all too often. I think use of this metaphor may just help those people understand.

Sorting Elements with jQuery

Whilst refactoring a jQuery plugin today, I came across a method that placed a list item into an unordered list at a specific point, so that all the items remained in alphabetic order. This long method seemed completely convoluted and slow to me and I decided that there must be an easier way to keep the list in alphabetical order.

There are existing plugins for sorting elements but I never like to just pile on the 3rd party plugins as that means more javascript files to include in a page. Besides, I was sure it should not be difficult.

It soon occured to me that jQuery has the built-in ability to return the elements as an array, using the .get() method and from there, it was not too long before I had my streamlined code to sort the list element alphabetically:

var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

I utilise the javascript array.sort method to sort the elements in the array and then using the jQuery append() method,  reorder them in the actual list element.