JQuery: AddClass to positive and negative values in a table

Okay,

Today I had one of those moments where something that seems very simple throws you a curveball…

Having done a day of training with the brilliant “Remy Sharp “:http://remysharp.com/ I thought I’d throw a bit of JQuery into the mix and have coloured positive/negative values in a flash… Unfortunately the course I did with Remy was more about animation etc than inline styling so I turned to Google to kick this out the door.

And what a shambles. I found people string matching on negative values, people adding spans loaded with inline styles and loads more!

So, here’s my quick solution next time you have to display financial information in a table but first a few caveats…

1. I’m using JQuery in the page already for tablesorting etc so don’t think i’m using it JUST for this. Sensibly you won’t load JQuery for such a simple task.

2. I could determine the values using the presentation using PHP but as I want to output csv’s etc using the same source this just felt like heavy lifting for no good reason.

3. In my opinion this is just a tweak not an important part of the page’s content or presentation so I’m happy to have this as part of a JS only enhancement.





And that's it. It seems quite robust and works quickly so I'm happy but feel free to expose my mistakes in the comments :)

I hope this helps another JQuery novice like myself out.

Leave a Reply

Your email address will not be published. Required fields are marked *