Blog

38 posts 2009 16 posts 2010 50 posts 2011 28 posts 2012 15 posts 2013 7 posts 2014 10 posts 2015 5 posts 2016 4 posts 2017 7 posts 2018 2 posts 2019 17 posts 2020 7 posts 2021 7 posts 2022 11 posts 2023 7 posts 2024 4 posts 2025

9 reasons why I prefer MySQL to MS SQL Server

2 min read 0 comments Report broken page

In the past, I used MySQL for any of my DBMS needs. It wasn’t really an informed decision based on solid facts, actually I had never really given it any thought. It was what most developers used, it was what vBulletin used (one of the main projects of my company is based on vBulletin), it was what most hosts had pre-installed, in other words, it was the popular choice and I went with the crowd.

Unlike most decisions taken that way, this one turned out to be correct (so far at least). In the university where I study (yeah, I do that too occasionally :P ), there is a great and extremely useful class on Database Systems offered in my semester. The only drawback is that it’s done on MS SQL Server. Consequently, I had to work with it quite a lot, and my conclusion was that MySQL is far superior (mostly syntax-wise as I don’t have the deep knowledge required to judge them fairly for other things, so don’t expect a deep analysis about performance or security - as far as I’m concerned, they are equally good at those). Here are a few reasons:

  1. No ENUM datatype. Yeah, of course I can define a column with a char/varchar type and add a constraint to only allow for particular strings, but this kinda defeats the purpose of memory saving that the ENUM datatype in MySQL offers.
  2. No INSERT IGNORE. Instead you have to go through hell to simulate that in MS SQL Server.
  3. I hate it that I can’t use “USING(columnlabel)” in a JOIN query and I have to use “ON(table1.columnlabel = table2.colmnlabel)” all the time. Yeah, I know that the first one isn’t standard, but it’s shorter, cleaner, more elegant, and …you can still use “ON(…)” if you don’t like it. Having more options is never bad, is it?
  4. With MySQL you may insert multiple rows at once elegantly (“INSERT INTO tablename (…), (…), …”), without using the “INSERT INTO tablename SELECT (…) UNION ALL SELECT (…) UNION ALL …” hack. Moreover, the elegant MySQL way also happens to be the standard, a standard that SQL Server doesn’t follow.
  5. Triggers can only run per statement, and not per row. This isn’t really important, since for most cases, it’s more efficient to define a per statement trigger anyway, but it doesn’t do any harm to have an extra option, does it?
  6. Paging is dead-easy on MySQL: SELECT * FROM foo LIMIT 10,20 . With MS SQL Server you have to jump through hoops to do the same thing, especially if your query is not trivial.
  7. In MySQL, when you want to convert an integer to a hex string, you just call HEX(). In SQL Server you have to call an undocumented function and do some string manipulation to do the exact same thing.
  8. MySQL runs on every platform, whereas with MS SQL Server you’re stuck with Windows.
  9. Last but not least, MySQL is free (and when it’s not free, it’s at least cheap) and opensource :-)

Creating the perfect slider

3 min read 0 comments Report broken page

I’ve previously discussed many times the color picker I have to create, and blogged about my findings on the way. An essential component of most color pickers is a slider control.

I won’t go through much techincal details or JavaScript code in this article (after all the usability guidelines presented don’t only apply to JavaScript applications, and this is why I used Adobe Kuler as a good or bad example for some of them), it’s been done numerous times before and I prefer being a bit original than duplicating web content. You can google it and various implementations will come up if you need a starting point.

Some might argue that I suffer from NIH syndrome, but I prefer to code things my way when I think I can do something even a bit better. After all, if nobody ever tries to reinvent the wheel, the wheel stands no chances of improvement. In this case, I wanted to build the most usable slider ever (at least for color picking uses), or -from an arguably more conservative point of view- something significantly more usable than the rest (if you think about it, the two statements are equivalent, the first one just sounds more arrogant :P ).

I started by thinking about the way I personally use sliders and other form controls, and what bothers me most in the process. Then I combined that with the previously-done accessibility guidelines and the best slider implementations I’ve encountered (from a usability perspective), and here is what I came up with.

Requirements for the perfect slider control

  1. It should be ARIA-compatible, so that disabled users can easily utilize it.
  2. It should be focusable, so that you can Tab to it.
  3. Of course the thumb should be draggable (why would you call it a slider otherwise anyway?)
  4. Of course the slider should be labeled so that the user knows what to use it for.
  5. Normal, hover and focus states should be different (at least in browsers supporting the :hover and :focus pseudo-classes)
  6. You should be able to click somewhere in the rail and have the thumb instantly move there. Many slider implementations use animations for that, and even though I admit it raises the wow factor, I don’t think it’s good for usability. When I choose something, I want it to be instantly selected, I don’t want to wait for the pretty animation to finish, even if it’s short. Other implementations don’t move the slider to the point of the rail that you clicked, but just a bit towards it. I find that very annoying. I clicked there because I want the slider to go there, not towards there! If I wanted to increment/decrement it a bit, I’d use other methods (read below).
  7. It should be keyboard-navigable. I think the ideal key-mappings are:
    • Left and right arrow keys for small adjustments
    • Page up/down and Ctrl + left and right arrow keys for big adjustments.
    • Esc to focus out (blur)
    • Home and End to navigate to the minimum and maximum respectively
  8. It should respond to the mousewheel (and this is where all current implementations I’ve tested fail misreably) when focused. Small adjustments for normal mousewheel movement, big adjustments if the Ctrl key is pressed as well. The pitfall to that is that you can’t cancel the default action (zoom in/out) in Safari. Why the Ctrl key and not Alt or Shift? Because we are accustomed to using the Ctrl key as a modifier. Alt and Shift are used more rarely. Especially designers (and for most color pickers they are a significant part of the target audience) are used in using the Ctrl key together with the mousewheel, since that’s a popular way for zooming or scrolling in most Adobe CS applications. Another important consideration when designing a mousewheel-aware slider, is to bind the event to the document element once the slider thumb is focused and unbind it when the slider thumb is blurred. Why? Because in most such cases, we don’t like to have to keep out mouse pointer on the slider to adjust it with the mousewheel. It being focused should suffice for letting the app know that this is what we want to adjust.
  9. The exact numerical choice of the user should be visible, not only in an indicator that is positioned in a static place, but also above the slider thumb and have it move as the slider thumb moves. I don’t want to have to look at two different places to see what I have selected! (the slider thumb and the indicator) Why above the slider thumb? Because if it’s below, the mouse pointer is likely to hide it. This movable indicator should be hidden once the user focuses out (as long as we provide another one that is positioned statically). Adobe Kuler does this fairly well, although it suffers from a few issues: When you click on the slider rail, the indicator doesn’t show up.
  10. The user should be able to click at some point in the rail and start dragging right away, without lifting their mouse button in the meantime. Even though this sounds common-sense, I’ve seen many implementations that fail at it (including Kuler’s).

So, that’s it! What do you think? Could you come up with anything else to add?


Cross-browser imageless linear gradients v2

2 min read 0 comments Report broken page

A while ago, I posted a script of mine for creating 2-color cross-browser imageless linear gradients. As I stated there, I needed them for a color picker I have to create. And even though 2-color gradients are sufficient for most components, in most color spaces, I had forgotten an important one: Hue. You can’t represent Hue with a 2-color gradient! So, I had to revise the script, and make it able to produce linear gradients of more than 2 colors. Furthermore, I needed to be able to specify a fully transparent color as one of the gradient colors, in order to create the photoshop-like 2d plane used by the picker (and no, a static image background like the one used in most JS color pickers wouldn’t suffice, for reasons irrelevant with this post). I hereby present you Cross-browser, imageless, linear gradients v2!

The API has stayed just the same, with the following differences:

  • You may specify the keyword “transparent” instead of a #RRGGBB color (that was such a pain to implement btw!).

  • When creating a Gradient object, color strings are now defined in an array. Example:

    var g = new Gradient(200, 100, [‘#000000’, ‘#ff1166’, ‘#23ff46’], true);

  • When calling g.paint() it now takes 2 arguments instead of 3: The new color array (or null if you don’t want that to change) and the direction (true for vertical, false for horizontal). For example:

    g.paint([‘#000000’, ‘#ff1166’, ‘#23ff46’], true);

  • 2 new methods have been added: g.setColorAt(index, color) and g.direction(newDirection). The first allows you to set a particular gradient color (index starting from 0) and the second to alter or toggle the direction (if you specify a direction parameter, you set the direction, if you call it with no parameters, it toggles from horizontal to vertical).

  • The fields g.startColor and g.endColor have been replaced by the array g.colors.

Update: v2.0.1 Fixed a small bug with the ‘transparent’ keyword that affected multi-color gradients in browsers != IE when the transparent color wasn’t first or last.

Enjoy:

gradient.js (5.1 KB)

gradient-min.js (2.7 KB)

Test page


Java pretty dates

1 min read 0 comments Report broken page

First of all, sorry for not posting as frequently as before. I’m feverishly working on a new project with a really tight deadline and I don’t have as much time as I previously did.

For reasons that are irrelevant to this post, I have to write lots of Java code. So, sorry if I disappoint my fellow readers, but this post isn’t about JavaScript or CSS, it’s about Java. I wanted to display “pretty dates” (a bit like Twitter’s, for example “yesterday”, “5 minutes ago”, “last year” and so on) in a few places and I couldn’t find a Java implementation, so I decided to code my own.

For anyone that might need it, here it is:

import java.util.Date;

/**

  • Class for human-readable, pretty date formatting

  • @author Lea Verou */ public class PrettyDate { private Date date;

    public PrettyDate() { this(new Date()); }

    public PrettyDate(Date date) { this.date = date; }

    public String toString() { long current = (new Date()).getTime(), timestamp = date.getTime(), diff = (current - timestamp)/1000; int amount = 0; String what = "";

    /** * Second counts * 3600: hour * 86400: day * 604800: week * 2592000: month * 31536000: year */

    if(diff > 31536000) { amount = (int)(diff/31536000); what = "year"; } else if(diff > 2592000) { amount = (int)(diff/2592000); what = "month"; } else if(diff > 604800) { amount = (int)(diff/604800); what = "week"; } else if(diff > 86400) { amount = (int)(diff/86400); what = "day"; } else if(diff > 3600) { amount = (int)(diff/3600); what = "hour"; } else if(diff > 60) { amount = (int)(diff/60); what = "minute"; } else { amount = (int)diff; what = "second"; if(amount < 6) { return "Just now"; } }

    if(amount == 1) { if(what.equals("day")) { return "Yesterday"; } else if(what.equals("week") || what.equals("month") || what.equals("year")) { return "Last " + what; } } else { what += "s"; }

    return amount + " " + what + " ago"; } }

Hope someone finds it useful. :)


Better usability in 5 minutes

3 min read 0 comments Report broken page

In this post I’m going to share some tips to increase a site’s usability that are very quick to implement. Not all of them are cross-browser, but they are the icing on the cake anyway, nobody would mind without them.

This is a personal favorite. When you use CSS to style a button, or when you use an image (either as a background image or in the tag) to depict a fancy button, it will remain the same when being pressed in some or all browsers (depending on the case). You can use this easy trick to let the user know that he actually clicked something that is, indeed, clickable:

.mybutton:active { position:relative; top: 1px; left: 1px; }

which actually moves the button 1 pixel to the right and 1 pixel to the bottom when it’s being clicked. Try it, it’s actually quite convincing.

Other, equally quick options are: making the border inset, giving to the text a text-indent of 1px, reversing a gradient background (if you already use the reversed version somewhere else in the site, it is quick since you don’t have to use an image editor just for that), or a combination of them.

2. Smooth transitions

This is a webkit-only tip, but as I said, it’s just the icing on the cake, so who cares? If a smooth transition is crucial to your design, by all means, write a script for that or use a library. If you were planning to go the CSS-only way anyway, this will significantly increase the user experience for webkit users.

Let’s suppose that the links in your page are normally blue, and red on hover. To make the transition from blue to red smooth for webkit users, only 2 lines are needed in the CSS:

a { color:blue; transition-property: color; transition-duration: 1s; }

a:hover { color:red; }

The first one (transition-property) tells the browser which CSS property to smoothly transition and the second one (transition-duration) how long you want the whole effect to last. It’s important to place those in the normal CSS rule and not the one with the :hover pseudoclass, because otherwise there will be no transition when the user mouses out of the element. Please note that you currently need to also include browser prefixes for these properties or just use -prefix-free.

3. Add dingbats to buttons that depict their functionality

We all know that most browsers don’t like dingbat-only fonts. However, there are some dingbats that are available in most web-safe unicode fonts. For instance, review the following examples:

Without dingbats:

Next Previous Done Favorite

With dingbats:

Next → ← Previous ✔ Done ♥ Favorite

There are named html entities for some of them, others have to be used by their hex unicode index like ꯍ  (you have to test the last ones a lot, since not all are web-safe enough).

You can find many such dingbats with their unicode hex codes in http://www.copypastecharacter.com/ and http://www.alanwood.net/unicode/dingbats.html.

Of course, if you have the time, by all means, use normal icons. If you don’t however, I find symbols to be a handy alternative. Sometimes I also use them as icon placeholders in work in progress until I find the time to design real icons.

4. Zebra rows

This won’t work on IE and Firefox 3. You can increase readability of tables and some types of lists by slightly alternating the background color of the rows. You’ve probably seen this effect numerous times and it’s usually done via JavaScript or the server side code that generates the table. You can quickly do it with plain CSS3 however, if you don’t mind it not working in IE and older browser versions or don’t have the time for a complete cross-browser solution:

table.stats tr { background:white; }

table.stats tr:nth-child(odd) { background:#f4f4f4; }

5. Highlight the current target

This won’t work in IE and older browser versions. If a particular page has lots of content, navigable by anchors (for example a FAQ page), you can use the CSS3 :target pseudo-class to let the user know where they landed:

h3:target { background:#FFFBCC; }

The h3 will only get a #FFFBCC background when it’s actually the landing point for the user. For example, if it has the id “foo”, it will get an #FFFBCC background when the user navigates to #foo.

That’s all folks

Did it actually take more than 5 minutes? ;)


Help me: take the color survey

1 min read 0 comments Report broken page

If you are a creative professional, or just passionate about colors, please take my survey:

http://bit.ly/colorsurvey

It will greatly help me to make a future project of our company more usable (some of its features at least) and it only takes a few minutes (it contains 10-19 questions, depending on your responses).

Any suggestions, corrections, questions etc are of course welcome.

Thanks a lot in advance to everyone that takes the survey! :D

Of course, when it ends and I find the time to analyze the results, I’ll post them here for anyone interested. (Hint: That means that if you are interested in the results, you can promote the survey yourself as well, since more responses = more accurate results)


Advocacy of JavaScript

3 min read 0 comments Report broken page

I frequently meet these “hardcore” developers that deep (or not so deep) inside them, tend to underestimate JavaScript developers and boast about their own superiority. I’m sure that if you spent an important percentage of your career working with JavaScript and are even barely social, you definitely know what I’m talking about. It’s those desktop application programmers or these back-end developers that tend to consider JavaScript a toy, and try to convince you to engage in “more serious stuff” (if they appreciate you even a little; if they don’t they just mock you endlessly and/or look down on you).

Funnily enough, when most of these people are required to write JavaScript for some reason, one of the following happens:

  1. They write 2000-style code, which is usually the reason that most of them underestimate JavaScript so much: They think that everybody codes in JavaScript like themselves.
  2. They desperately look for “a good library” because “it’s not worth wasting my time to learn that stuff”.
  3. They actually learn the darn language and the relevant browser quirks and change their attitude towards JavaScript developers.

Douglas Crockford did it much better than me, but I would like to take my turn in arguing against their most frequent claims, if I may.

“Javascripters are not really developers.”

Oh r’ly? Is it because JavaScript doesn’t follow what you’ve learned to expect from most languages? Well, newsflash: Assembly doesn’t either and every programming language is actually an abstraction to it. It’s in fact much harder to write the same thing in a language that lacks what we’ve learned to expect. Think about low level coding: Even the simplest tasks seem hard. At a smaller extent, it’s the same with JavaScript: Things that are easy to do in other languages, are a pain in JavaScript, even if we leave out the implementation differences across browsers. For instance, in Java there is a built-in class for most common tasks. JavaScript isn’t that rich, and it penalizes you for every external library you use, by forcing your users to download extra Kilobytes of code. JavaScript is probably the only modern language in which short code isn’t only elegance, but also a necessity.

Also, in other languages, you only have to deal with one implementation. Even when using Java to code for multiple operating systems, the differences are minor for most applications. With JavaScript, you are dealing with at least 5 implementations with many differences and bugs to circumvent. Writing a piece of code that works in one browser is not good enough, you have to make it work across all major browsers, in all their versions that still have significant market share. And yeah, this is most of the times just as dreadful as it sounds, if not more.

Of course, I’m not implying that everyone who wrote a script in JavaScript is a developer, just like everyone that wrote a Hello World application in C++ is not a programmer. JavaScript is notorious for being used mostly by amateurs for the following reasons:

  1. Most people that ever wrote a webpage needed something that could only be done with JavaScript. Most of these people weren’t developers and didn’t have any interest in programming.
  2. Because of (1) there are many JavaScript tutorials and books around for accomplishing simple tasks, most of them being leftovers from the 2000 era and promote bad code practices. During that era, people didn’t care about nice code, usability, accessibility and cross-browser functionality. They just wanted to get the job done spending the least possible time and they only cared if it worked in Internet Explorer.
  3. Most people just copy and paste stuff from the tutorials mentioned in (2), leading to duplicate functionality, bad code, bad usability, complete absence of accessibility and buggy results in browsers other than the target one. This caused JavaScript to be related to these vices although these things were actually caused by abusing the language.

“Javascript is a toy, not a real programming language”

It may have been a toy in the 2000 era where your mind is still stuck. Currently, browser vendors are constantly adding new features to it, in order to make it able to compete with a fully-fledged programming language and competent front-end developers have been pushing JavaScript to an extent that was unimaginable when it was first introduced. If you are not convinced, pay a visit to Chrome Experiments (as the name suggests, you are advised to use Google Chrome when viewing them).

JavaScript is not a light version of Java, nor is it a light version of any programming language. It has a soul of it’s own, so stop comparing it to other languages and pointing out the areas where it lacks. Open your eyes instead to see the areas where it’s superior to all other languages you probably know (lambda for instance).

“How can I respect a language that only lives inside a browser?”

Newsflash: You are wrong, again. You can code in JavaScript for the server, create Windows executable files (.exe), create  plugins and extensions for a plethora of applications, and actually even Flash’s ActionScript is based on ECMAScript, a standard that was derived from and currently controls JavaScript implementations.

Disclaimers

Ah, these are always necessary in rants :)

  1. I didn’t have any particular individual in mind when writing this post, so if you think it’s about you, get over it. My memory is too bad to do so anyway. ;)
  2. I am not implying that JavaScript is the best programming language around. I actually don’t think there is such a language. My point was that JavaScript is not inferior to the others. That doesn’t mean I consider it superior either.
  3. I don’t claim to be a programming guru (anyone who does so is usually ignorant anyway), nor do I claim to be always right. Feel free to argue, if you have thought a valid counterargument. :)

Extend Math.log to allow for bases != e

1 min read 0 comments Report broken page

As Math.log currently stands, it’s a bit useless. It only calculates natural logarithms (base e).  We can easily modify it however, to calculate logarithms of any base:

Math.log = (function() {
	var log = Math.log;
	return function(n, a) {
		return log(n)/(a? log(a) : 1);
	}
})();

We can now specify the base as a second parameter, or still use the default one (Math.E) if we don’t specify one, so older scripts won’t break or if we want a shortcut to the natural logarithm. ;)


100% Cyan in CMYK is NOT rgb(0,255,255)!!

2 min read 0 comments Report broken page

As I mentioned in an earlier post of mine, I have to create a color picker, so I’ve already started to write the code for the Color class it’s going to use. I need it to natively support RGB, HSL, Lab and CMYK. And the latter part is causing unexpected trouble.

It seems that there is the notion out there that conversion from CMYK to RGB is easy. Newsflash: It’s not. As every graphic designer knows, the CMYK color gamut is smaller than the the RGB color gamut (even the sRGB color gamut). You can’t take a CMYK color and convert it to an out-of-CMYK-gamut RGB color! That’s nonsense! And it’s precisely what most conversion algorithms and color pickers out there do! Even Adobe Kuler!!! Since yesterday, I’ve studied dozens of algorithms and color pickers that claim to do CMYK -> RGB conversion, and every single one of them is wrong.

You can test a color picker that claims to support CMYK, or a CMYK <–> RGB conversion algorithm in the following simple way: Test how it converts the color CMYK(100%, 0, 0, 0) to RGB. If the result is rgb(0,255,255) then the algorithm is crap. rgb(0, 255, 255) is neither the same color, nor is it even in the CMYK color gamut! So basically, these algorithms convert a CMYK color to an RGB color that is outside of the CMYK color gamut! A color that cannot be represented with CMYK is supposed to be the result of a CMYK->RGB conversion? This is madness!

So far the only CMYK -> RGB converter that I’ve seen and does it right, is the one used by Adobe CS products (Photoshop, Illustrator, etc). And that makes me wonder why Kuler does it the wrong way, since they have already figured the algorithm! It’s crazy!

What’s even more strange is that I can’t even find which sRGB colors are usually out of the CMYK color gamut, so that I can adjust the algorithm I use properly (even if it just clipped the color to the nearest in-gamut one, it would be an improvement). I’ve been searching since yesterady even for that with no luck. I hope I don’t end up using the wrong algorithm myself too…


Cross browser, imageless linear gradients

2 min read 0 comments Report broken page

I have to write a color picker in the near future and I wanted it to have those little gradients on top of the sliders that show you the effect that a slider change will have on the selected color. Consequently, I needed to create imageless gradients, in order to easily change them. My very first thought was creating many div or span elements in order to show the gradient. I rejected it almost instantly, for ovbious reasons (*cough* performance *cough*). My second thought was SVG for the proper browsers, and gradient filters for IE. As it turned out, inline SVG was too much of a hassle and I didn’t want to use Data URIs. My final thought was canvas for the proper browsers and gradient filters for IE.

Since I consider such a script very entertaining, I didn’t google it at all, I started coding right away. Time to have fun! :D After finishing it though, I googled it just out of curiosity and didn’t like the other solutions much (either the solution itself, or the code), so I decided to post it in case it helps someone. I also made a little test page, so that you may test out how it works. :)

The script is a class for the creation of linear 2-color gradients in any browser. It’s used like this:

var g = new Gradient(200, 100, '#000000', '#ff1166', true);
document.body.appendChild(g.canvas);

You can create and manipulate the Gradient object at any point (during or after DOM parsing) but you have to insert the element somewhere in the DOM after the DOM has finished parsing (which is common sense).

All the parameters in the constructor are optional and can be manipulated later. Their order is width, height, startColor, endColor, vertical.

Some notes:

  • Its object oriented and doesn’t throw any strict warnings
  • Tested in IE6, IE7, IE8, Firefox 3, Safari 4b and Opera 9.6. Probably works with older versions of Firefox, Opera and Safari as well (as long as they support <canvas>), I’m just not able to test in them currently.
  • All it’s methods return the object, so they can be chained.
  • You can modify it to support RGBA as well, but you’d have to use a different format for IE (extended hex) and a different one for the proper browsers. I didn’t need that and it would make the script unnecessarily complex, so I didn’t implement it.

Limitations (all these limitations are enforced by IE’s gradient filter):

  • Only does linear gradients
  • The gradient can be either vertical or horizontal. No other angles.
  • The only color format supported is #RRGGBB.

Properties

canvas (HTMLElement)

The HTML Element that is being used to render the gradient. Either a <canvas> or a <span>. You have to use it at least once, in order to insert the element in the DOM. I preferred not to do this automatically, since it would be too restrictive.

startColor (String)

The current start color of the gradient.

endColor (String)

The current end color of the gradient.

vertical (Boolean)

True if the gradient is vertical, false if it’s horizontal.

width (Number)

The width of the gradient in pixels

height (Number)

The height of the gradient in pixels

Methods

paint(startColor, endColor, vertical)

Used to change the colors and/or the orientation of the gradient. All parameters are optional.

resize(width, height)

Used to change the size of the gradient. Both parameters are optional.

flip()

Reverses the gradient (swaps endColor with startColor)

rotate()

Rotates the gradient by 90 degrees clockwise (should I add CCW too?)

Download

Hope you find it useful :)


Mockup viewer bookmarklet

1 min read 0 comments Report broken page

I usually view mockups in a browser, so that the impression I get is as close as possible to reality (I learned this the hard way: A mockup that seemed great in the neutral and minimalistic environment of a picture viewer, ended up looking way too fancy when viewed in a browser, something that I realized after having worked for 6 months on the site). If you do the same, I’m sure you’ll feel my pain: Every time I do that, I have to carefully scroll down just as much as to hide the margin that the browser adds, and left just as much as to center the image. Not to mention the click required to enlarge the image to full-size.

Not any more! I was so fed up today, that I wrote a little bookmarklet that does this. It enlarges the image to full size, removes the margins and scrolls the page left so that the image is centered. It works on any recent browser I’ve tested, and I think it will probably work in most browsers that web designers use (hint: not old IEs) :P

Enjoy.

Mockup viewer

JS code:

(function(){
	document.body.style.margin = 0;
	var inner = window.innerWidth || document.body.clientWidth, img = document.getElementsByTagName('img')\[0\];
	img.removeAttribute('width');
	img.removeAttribute('height');
	document.body.scrollLeft = (img.offsetWidth - inner)/2;
})();

If only it could also write the XHTML & CSS for the site… :P


CSS3 colors, today (MediaCampAthens session)

1 min read 0 comments Report broken page

Yesterday, I had a session at MediaCampAthens (a BarCamp-style event), regarding CSS3 colors. If you’ve followed my earlier posts tagged with “colors”, my presentation was mostly a sum-up of these.

It was my first presentation ever, actually, the first time I talked to an audience for more than 1 minute :P . This caused some goofs:

  • When introducing myself, I said completely different things than I intended to and ended up sounding like an arrogant moron :P
  • I tried not to look at the audience too much, in order to avoid sounding nervous, and this caused me to completely ignore 2 questions (as I found out afterwards)! How embarrasing!
  • At a certain point, I said “URL” instead of “domain” :P

Also, I had prepared some screenshots (you’ll see them in the ppt) and the projector completely screwed them up, as it showed any dark color as black.

Apart from those, I think it went very well, I received lots of positive feedback about it and the audience was paying attention, so I guess they found it interesting (something that I didn’t expect :P ).

Here is the presentation:

Please note that Slideshare messed up slide #8 and the background seems semi-transparent grey instead of semi-transparent white.

By the way, I also thought afterwards that I had made a mistake: -ms-filter is not required if we combine the gradient filter with Data URIs, since IE8 supports Data URIs (for images at least). Oops, I hate making mistakes that I can’t correct.

Here are some photos from my session. If I did it correctly, every facebook user can see them. If I messed things up, tell me :P


CMYK colors in CSS: Useful or useless?

2 min read 0 comments Report broken page

As someone who dealed a bit with print design in the past, I consider CMYK colors the easiest color system for humen to understand and manipulate. It’s very similar to what we used as children, when mixing watercolors for our drawings. It makes perfect sense, more than HSL and definately more than RGB. I understand that most of us are so accustomed to using RGB that can’t realise that, but try to think for a moment: Which color system would make more sense to you if you had no idea and no experience at all with any of them?

Personally, even though I have lots more experience with RGB, given the fact that most of my work will be displayed on screen and not printed on paper, when I think of a color I want, I can instantly find out the percentages of Cyan, Magenta, Yellow and blacK needed to create it. I can’t do that with HSL or RGB, I’d have to play a little bit with the color picker’s sliders. I sometimes start by specifying a color in CMYK and then tweaking it via RGB or HSL to achieve the exact color I need (since the CMYK gamut is smaller than the RGB gamut) and I find that much faster than starting with RGB or HSL right away.

Also, when you don’t have a color picker, it’s much easier to create beautiful colors with CMYK than it is with RGB. For example the CMYK magenta (0% Cyan, 100% Magenta, 0% Yellow, 0% blacK) is a much better color than the RGB Magenta (255 Red, 0 Green, 100% Blue).

Given the above, I’ve always thought how much I wanted to be able to specify CMYK colors in my CSS. I agree that sometimes this would result in crippling myself, since as I said above the CMYK gamut is smaller, but it has other significant advantages that I think it would make it a useful option for some people. There are algorithms available for CMYK to RGB conversion, and the browser could use those to display the specified color on the screen. Then, if the user decided to print the page, The CMYK colors could be used as-is for the printer. Another advantage, as none of the current CSS color formats allow us to control that. People who don’t find the CMYK color system easier for them to understand, they could still use it for their print stylesheets.

Also, graphic designers who decided to switch to web design would find it much easier to specify color values in a format they are already comfortable with.

To sum it up, the advantages that I think this option would provide us are:

  1. A color system that’s easier for most people to understand and manipulate.
  2. The colors you get when combining “easy” CMYK values (0%, 50%, 100%) are more beatuful than the ones you get with “easy” RGB values (0, 128, 255). Bored people and people without a taste in color selection would create more beatuful websites this way and our eyes wouldn’t hurt.
  3. We would be able to specify how our colors will get printed, something that is not currently possible at all. Extremely useful for print stylesheets.
  4. It would be easier for graphic designers to switch to web design.

And the format is very easy to imagine:

background-color: cmyk(0, 100, 50, 0);

or

background-color: cmyk(0%, 100%, 50%, 0%);

or

background-color: cmyk(0, 1, 0.5, 0);

So, what do you think? Useful or useless?

Edit: As it turns out, I’m not crazy! The W3 already considers this for CSS3 with the 3rd format (from 0 to 1)! However, no browser supports it yet, not even Webkit nightlies… :(

Translations


On native, single-input, multiple file uploads

2 min read 0 comments Report broken page

If you are following the current news on web development, you probably heard that the new Safari 4 has a great feature: It natively allows the user to select multiple files via a single input control, if you specify a value for the attribute multiple:

<input type="file" multiple>

or, in XHTML:

<input type="file" multiple="multiple" />

You might not know that Opera supported multiple file uploads for a while now, based on the earlier Web Forms 2.0 standard in a slightly different (and more flexible) format:

<input type="file" min="1" max="9999″ />

Can we use those currently?

Sure we can, but we should provide fallbacks for the other browsers. Using these features will put pressure on the other browser vendors to implement them as well and generally, native is always better.

How can we find out whether the browser supports them?

Opera

Opera supports accessing those min and max properties as properties of the element. So, it’s quite trivial to check whether Opera-style multiple inputs are supported:

var supportsMin = (function(){
	var fi = document.createElement('input');
	fi.type = 'file';
	return fi.min === '' && fi.max === '';
})();

Safari 4

In Safari 4 the check would be equally simple, if it supported accessing the multiple attribute as a property. Then we could easily check whether it’s boolean and conclude that Safari-style multiple inputs are supported:

var supportsMultiple = (function(){
	var fi = document.createElement('input');
	fi.type = 'file';
	// The second check is probably redundant but what if in the future an implementor
	// decides to make the file inputs to handle multiple selections by default?
	// Yeah, it's not likely, but it's not entirely impossible.
	return fi.multiple === false || fi.multiple === true;
})();

However, that’s currently not the case. The good news are that I reported this as a bug today, and the Webkit team fixed it, so it will be possible in the next Webkit nightly!

Combining the two

You can easily combine these two together with the workaround you prefer:

// Create a file input that allows multiple file selection
var fi = document.createElement('input');
fi.type = 'file';

if(fi.multiple === false || fi.multiple === true) { fi.multiple = true; } else if(fi.min === ‘’ && fi.max === ‘’) { fi.min = 1; fi.max = 9999; } else { // Our preferred workaround here }

What about Mozilla?

Ok, we all know that IE will probably take years to implement similar functionality. But usually, the Mozilla team implements new and exciting stuff quite fast.

As it turns out, there is a relevant ticket sitting in their Bugzilla for a while now. If you want them to implement it, vote for it so that it’s priority increases.

If they do implement it in the way suggested, the code posted above will work for that too, without any changes - The advantages of feature detection baby! ;)


Check whether the browser supports RGBA (and other CSS3 values)

2 min read 0 comments Report broken page

When using CSS, we can just include both declarations, one using rgba, and one without it, as mentioned in my post on cross-browser RGBA backgrounds. When writing JavaScript however, it’s a waste of resources to do that (and requires more verbose code), since we can easily check whether the browser is RGBA-capable, almost as easily as we can check whether it suppports a given property. We can even follow the same technique to detect the support of other CSS3 values (for instance, multiple backgrounds support, HSLA support, etc).

The technique I’m going to present is based on the fact that when we assign a non-supported CSS value on any supported CSS property, the browser either throws an error AND ignores it (IE-style), or simply ignores it (Firefox-style). Concequently, to check whether RGBA is supported, the algorithm would be:

  1. Get the color (or backgroundColor, or borderColor or any property that is widely supported and accepts color values) value of the style object of any element that exists in the page for sure (for instance, the first script tag) and store it in a variable.
  2. Assign an RGBA color to the color property of that element and catch any errors produced.
  3. Assign to a variable whether the color of that element did change (boolean true or false).
  4. Restore the previous color to the color property, so that our script doesn’t interfere with the designer’s decisions.
  5. Return the stored result.

and it would result in the following code:

function supportsRGBA()
{
	var scriptElement = document.getElementsByTagName('script')[0];
	var prevColor = scriptElement.style.color;
	try {
		scriptElement.style.color = 'rgba(1,5,13,0.44)';
	} catch(e) {}
	var result = scriptElement.style.color != prevColor;
	scriptElement.style.color = prevColor;
	return result;
}

Performance improvements

The code above works, but it wastes resources for no reason. Every time the function is called, it tests RGBA support again, even though the result will never change. So, we need a way to cache the result, and return the cached result after the first time the function is called.

This can be achieved in many ways. My personal preference is to store the result as a property of the function called, named 'result':

function supportsRGBA()
{
	if(!('result' in arguments.callee))
	{
		var scriptElement = document.getElementsByTagName('script')[0];
		var prevColor = scriptElement.style.color;
		try {
			scriptElement.style.color = 'rgba(0, 0, 0, 0.5)';
		} catch(e) {}
		arguments.callee.result = scriptElement.style.color != prevColor;
		scriptElement.style.color = prevColor;
	}
	return arguments.callee.result;
}

Making it bulletproof

There is a rare case where the script element might already have rgba(0,0,0,0.5) set as it’s color value (don’t ask me why would someone want to do that :P ), in which case our function will return false even if the browser actually supports RGBA. To prevent this, you might want to check whether the color property is already set to rgba(0,0,0,0.5) and return true if it is (because if the browser doesn’t support rgba, it will be blank):

function supportsRGBA()
{
	if(!('result' in arguments.callee))
	{
		var scriptElement = document.getElementsByTagName('script')[0];
		var prevColor = scriptElement.style.color;
		var testColor = 'rgba(0, 0, 0, 0.5)';
		if(prevColor == testColor)
		{
			arguments.callee.result = true;
		}
		else
		{
			try {
				scriptElement.style.color = testColor;
			} catch(e) {}
			arguments.callee.result = scriptElement.style.color != prevColor;
			scriptElement.style.color = prevColor;
		}
	}
	return arguments.callee.result;
}

Done!