Blog Archives

Animating Table Rows with jQuery

Posted in AuroraCMS, Code, Product Reviews, Tips and Tricks

Animating table rows in the browser is problematic. You see, they aren’t block elements and as such don’t have a height or width property. Instead they take their constraints from the content inside them, and the elements that contain them. For rows this typically means they’re constrained by the containing table, and filled by the contained columns.

Today I wanted to slide a row up, and then when it had finished sliding I wanted to remove it from the DOM. Essentially giving it a nice effect when something is deleted.

Given that the height of a row is controlled by it’s content, I figured the easiest way to do this would be to wrap all of the content inside each column with a block element, in this case a div, and then resize those.

jQuery makes this extremely easy :

var el = $(options.element_prefix + id);
el.children("td").each(function() {
    $(this).wrapInner("< div />").children("div").slideUp(function() {el.remove();})
});

NOTE : The div tag in the wrapInner() is malformed because it won’t display properly otherwise. Please remove the space between the opening bracket and ‘div’.

It’s all pretty easy to understand. Essentially my root element is a row, and so for each td in that row wrap it’s content in a div. Then for the child divs in each td, run the slideUp() method. The callback in the slideUp() method says after the animation is done, remove the row. Given the speed of computers these days, no one will notice that the last few columns quite likely just vanish instead of complete their animation.

jQuery: Check For Non-Empty Input Fields

Posted in Code

– Check out some of our more recent Ruby on Rails blog posts. If you’d like to hire our team, get in touch

I was writing some code today and I wanted to prompt the user to check if they wanted to delete a row of data only if there was some data they might not want deleted. Typically to do this I would loop through all the input fields and if any of them weren’t blank I would run the check. I figured that there must be a better way with callbacks or selectors, and after a little thinking I wrote this jQuery snippet :

row.find('input[value!=""]').length > 0

This basically says count the number of inputs with a non-blank value you find, inside the given row.

Just like my last post, it’s nothing amazing but it sure is a better way of doing things. If you look into the andSelf() method then you could also easily chain selects and other input types.

I’m also interested if someone has a better way to approach this problem?

JavaScript and String Building

Posted in Code

In most languages there is a means of building strings and printing out messages. Many will find the printf command all too familiar. In the JavaScript space however things have been a little slow to develop.

We have our strings and to build them up we merely start adding them together but as our code gets more elaborate this gets harder and harder. The biggest problem is usually trying to figure out how to escape quotes and inverted commas as we swap back and forth between plain strings and JavaScript variables.

I’ve often thought there must be a better way and working with the Dojo toolkit there is. It can be found in the method “dojo.string.substitute”. This mirrors the idea used in other languages of passing the method a template string and an object of values to substitute in. Whilst Dojo allows for numerous ways of passing the data such as arrays and functions the one that interests me the most is a standard JavaScript object which is effectively a hash map of name and value pairs.

Here’s a simplified version of the Dojo function that only uses objects for the value map.

var tfg = {
  string:{
    substitute: function(/*String*/ template, /*Object*/ valueMap){
      return template.replace(/\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\}/g, function(match, key){
            return (valueMap[key])?valueMap[key]:"";
        });
    }
  }
}

The old way of doing things might look like this:

var data = {name:"bob", occupation: "builder"};
var string = "His name is "+data.name+" and is occupation is "+data.occupation+".";

Here we merely add the different parts of the string and string values together. Simple enough in a string this size but as it grows and we start working with HTML syntax things get more complicated.

Using the substitute way:

var data = {name:"bob", occupation: "builder"};
var template = "His name is ${name} and is occupation is ${occupation}.";
var str = tfg.string.substitute(template, data);

Here anything surrounded by the format “${something}” is replaced with the value found in “data.something”.

A major advantage of this approach is when we start looking at fetching JSON data sets from a remote server via Ajax. We almost always have to process the return values into something to display and if it is looping through a list of objects we can now define the template once and repeatedly create a string with our substitute method. Here’s a simple idea using JQuery for the loop.

var result = [{name:"a",company:"1"},{name:"b",company:"2"}];
var template = "<tr><td>${name}</td><td>${company}</td></tr>";
var rows = $.map(result, function(index, item){
  return tfg.string.substitute(template, item);
})
var tableBodyString = rows.join("\n");

Here we looped through the items substituting each new set of values and pushing the result into an array. At the end we merge the array into a single string with “join” and have the body of a HTML table ready to be used in the page.

This approach is fast, easier to read and much cleaner to implement when looping through data.

MochiKit 1.4 is Released

Posted in Websites or Tools

I’m a big fan of Javascript frameworks that help me get things done, I’m a huge fan of anything that helps me get things done easier. My favourite framework though is jQuery after having tried a few just over a year ago I settled on jQuery as a better choice than Prototype and thankfully I’ve been proven right.

John Resig, the creator of jQuery is also a bit of a proponent for another framework called MochiKit. The idea of MochiKit is to “Make Javascript Suck Less” and as such doesn’t really offer many out there features that others might, it more concentrates on filling in functionality gaps that are present in the Javascript language.

These things include better comparator functions, which enable sorting and so on, also there are handy formatting functions, asynchronous functions and data functions for handling JSON. DOM manipulation looks to be very good, though whether it’s easier than jQuery is probably up to personal choice. Basically MochiKit seems to fill in the gaps of Javascript and do exactly what it says it does, make programming with Javascript suck less by giving you the functions you always wished you had.

I plan on checking this out and feel like it’s probably a worth addition to anybodys’ toolbox that is writing client side code.

Advanced Javascript

Posted in Industry Trends, Websites or Tools

When I started writing web applications I spent the vast majority of my time writing server side presentation code. As I progressed and people found out I knew a little bit about databases I shifted towards spending most of my time between designing and implementing data code and server side presentation code.

Now I would say I spend the majority of my time between writing server and client side presentation code, in other words I write a lot more time writing Javascript now than I ever have before and things don’t look like changing.

The majority of my work is with jQuery, but we have projects deployed using standard Javascript and Prototype as well so it pays to have as good an understanding of Javascript as possible. With that in mind I found a great site aimed at teaching some advanced uses of the language. It was written by John Resig who is one of the real leaders in using Javascript in interesting ways, he’s well known for developing the jQuery library but also has his finger in other pies most notable of which is probalby Firebug.

I remember when I started writing web applications that Javascript was almost laughed at, but now I absolutely enjoy writing it and is a massively important player on the web. I think people stopped expecting the user interaction of a web application to naturally lack that of a desktop application a little while ago and Javascript and frameworks like jQuery and Prototype allowed that to happen.

Twitter

The latest @rubyfive podcast is up, our own @sj26 receiving a mention for Ruby 1.9.3 performance improvements. http://t.co/hfx3EPMz

@frontiergroup about 6 days ago #

Search Posts

Featured Posts

Categories

Archives

View more archives