Wednesday, November 14, 2012
Days of a Month
Given the month number, m [1, 12], and the 4-digit year, this calculates the days of the month.
return m != 2 ? (((m < 8 && m % 2 != 0) || (m > 7 && m % 2 == 0)) ? 31 : 30) : (!(year % 400 == 0 || year % 100 != 0 && year % 4 == 0) ? 28 : 29);
Monday, June 25, 2012
Google IO 2012
Tuesday, April 3, 2012
Android: Cutting edge tech 2 years behind
Some History
When Apple came out with the iPhone in January, 2007, it certainly was a game-changer, but being the first of its kind also meant that some lessons would only be learned with time. Some things were foreseeable. Clearly Apple was planning to roll out more apps as time went by. Some other things escaped Apple's foresight. During the first 2 years Apple modified the OS to devote more resources to call handling, changed the keyboard to allow multi-touch key presses, and introduced much desired features like a dedicated Gmail account type button in Settings.Android's roll-out was in many ways analogous to that of iPhone OS. The first Android phone didn't reach the market until September, 2008, and although then the difference in capabilities between the two platforms was vast they've matured technologically to the point where they are more or less evenly capable. For the record, this article's focus is not the difference in original roll-out dates of the platforms.
Android's Permanent 2-year Lag
The case of the virgin customer is unique. Whatever the phone selected the customer is likely to be pleasantly surprised to find what a phone has become. And if the customer is like most mobile phone owners he'll be tied to that piece of hardware for 2 years or pay a premium to change it. So why does this only affect Android negatively? Strategy, or lack, thereof.When a customer purchases an iPhone he can't make a wrong choice. There's only one choice (in 2 colors, 2 memory capacities). There won't be any guilt associated with having selected the wrong device. Even better: he can rely on Apple's track record to hope that, although the hardware will look two generations less tasty in 2 years, the manufacturer won't consider his phone obsolete during that time and he'll be entitled to prompt bug fixes and releases of the best features his hardware can handle. Warm and fuzzy at no extra cost. Your phone may come to be 2 years old, but it will never feel quite that old.
If the customer purchases an Android device the experience is the opposite. Many flavors to choose from, from a choice of manufacturers, most with a good portion of bloatware, some with spyware right out of the box. Of course no one will tell this to the customer before the purchase, so some guilt is included for free with every purchase. But wait, there's more! Even after Google tried to get manufacturers to make a commitment to keep the phones regularly up to date with reasonably recent features and bug fixes the task is easier said than done and probably not policed. Your phone may come to be 2 years old, and it will most definitely feel 2 years old.
But but but... Ice Cream Sandwich (Android 4.0) is awesome! Yes. But it was ready last year. When you finally find a phone with it on your carrier it will already be last year's OS. It will have bloatware. It's software, so it will have bugs. But fear not: since you will never see an update from the manufacturer they will never be fixed on your phone.
Wake up, Google!
Monday, June 6, 2011
The 10 JavaScript Mistakes you’re Making
JavaScript is relatively easy to learn. However, gotchas abound in this tricky language. Are you sure that you’re not following any bad practices? Today, I’ll point out ten big mistakes you could be making.
Mistake 1 - You’re Using Global Variables
If you’re just getting started with JavaScript, you probably think it’s a great thing that all variables are global. Actually, if you’re just getting started, you might not know what that means. Global variables are variables that are accessible from anywhere in your JavaScript, even in different files loaded on the same page. Sounds great, doesn’t it? Any variable you might every want to change is always accessible.
Actually, no.
The reason this is a bad idea is because it’s easy to overwrite values unintentionally. Say you’ve got a web store, and you’re using JavaScript to display the price of all the items in the shopping cart (of course, you’ll recalculate this on the server side; this just enhances the user experience). Here’s some code you might have:
var total = 0, // total price
tax = 0.05; // 5%
Now, let’s say that you’re also using some code you found online to display some tweets on the page … or to make a sharp little gallery for your products. They might have some code like this:
var total = 15; // number of tweets pulled from twitter
Or,
var tax = function () { /* ... */ }; // Trigger Animation eXperience functionNow, you’re in trouble: two important variables have been overwritten, and you might not even realize it; your code will be producing errors, and you’ll pay dearly in time and hair to get things working again.
So what’s the solution? In a word, encapsulation; but there are many ways to do this. Firstly, you could just write all your code within a self-invoking, anonymous function:
(function () {
var total = 0, tax = 0.05;
// other code
}());This way, absolutely no code outside the function can get to the values you have inside the function. This works for “personal” code, but it’s not so great for functionality that you want to distribute. For example, if we wanted to create a shopping cart totaller that others could use, using the module pattern would be great:
var cartTotaler = (function () {
var total = 0; tax = 0.05;
// other code
return {
addItem : function (item) { },
removeItem : function (item) { },
calculateTitle : function () { }
};
}());One more thing about global variable: note that if you don’t use the var keyword when creating a variable, the JavaScript engine will create a global variable by default. So:
(function () {
tax = 0.05;
}());
var totalPrice = 100 + (100 * tax); // 105The variable tax is available outside the function because it’s not declared with the var keyword. Watch out for this.
Mistake 2 - You’re Not Using Semicolons
Every statement in JavaScript must end with a semicolon. It’s that simple. The issue here is that is you don’t put it in, the compiler will: this is called semicolon insertion. So the question is, if the compiler will insert them for you, why waste your time?
Well, in some places, it’s absolutely necessary; for example, you must put semicolons between the statements in a for-loop’s condition, or you’ll get a syntax error. But what about at the end of lines?
The JavaScript community is really divided on this. I’ve read very well-respected professionals on both sides of the debate. Here’s my argument: whenever you’re relying on the JavaScript compiler to change your code (even in what seems like a small way), you’re in dangerous waters.
For example, look at this simple function:
function returnPerson (name) {
return
{
name : name
};
}This looks like it should return a cute little object … but in reality, the JavaScript compiler assumes you meant to put a semicolon after return, and will therefore return nothing; that object will get ignored. Your solution would be to do this:
Editor’s Note- Another way to look at it: unless you’re aware of every single situation where they can successfully be omitted, don’t risk it.
return {
name : name
};I’m going to go with “diligently insert semicolons”; honestly, it becomes habit pretty quickly. Also, as a web developer, you’ll probably use other languages (like PHP) where semicolons are required. Why switch back and forth when you don’t have to?
Mistake 3 - You’re Using ==
If you left your computer right now and walked until you met any random JavaScript developer (that might take a while), and asked him/her to give you one common JavaScript mistake, this is probably what he/she would say: “using double-equals instead of triple-equals.” What’s this mean?
Try this:
if (1 == 1) {
console.log("it's true!");
}You’d expect that to work, right? Well, now try this:
if (1 == '1') {
console.log("it's true!");
}Yes, you got “it’s true!” output to the console … and yes, that’s a bad thing. What’s going on here is that the == equality operator is coercing the values: this means it’s actually changing them to try to make the two values more similar. In this case, it’s converting the string “1” to the number 1 … so that our if-statement condition passes.
The solution here is to use ===; this doesn’t perform any type coercion, so the values are what you expect them to be. Of course, this all goes for the != and !== operators as well.
Now, for your amusement, here’s a few of the incredible inconsistencies that you’ll get if you use double-equals:
'' == '0' // false
'0' == '' // true
false == '0' // true
' \t\r\n ' == 0 // true
Mistake 4 - You’re using Type Wrapper Objects
JavaScript kindly (um?) gives us some type wrappers for easy (um?) creation of primitive types:
new Number(10);
new String("hello");
new Boolean(true);
new Object();
new Array("one", "two", "three");
First off, this is just super inconvenient. All these things can be done with many fewer keystrokes:
10;
"hello";
true;
{};
["one", "two", "three"];
But, wait, there’s more: these two things aren’t exactly equal. Here’s Douglas Crockford on the topic:
For example,
new boolean(false)produces an object that has avalueOfmethod that returns the wrapped value.- JavaScript: The Good Parts, page 114
This means that if you run typeof new Number(10) or typeof new String("hello"), you’ll get ‘object’—not what you want. Plus, using wrapper objects can cause behaviour that you’re not expecting if you’re used to primitive values.
So why does JavaScript provide these objects? It’s because they’re used internally. Primitive values don’t actually have methods (because they aren’t object); so, when you call a method on a primitive object (such as "hello".replace("ello", "i")), JavaScript creates a wrapper object for that string, does what you want, and then discards the object.
Leave the typed wrappers up to JavaScript and use the primitive values.
Note: this should go without saying, but I want to make this clear for the newbies: I’m not saying you shouldn’t use constructor functions and new (although some do recommend that). This advice specifically applies to primitive value types—numbers, strings, and booleans—arrays, and blank objects.
Mistake 5 - You’re not Property-Checking when Using For-In
We’re all familiar with iterating over arrays; however, you’ll probably find yourself wanting to iterate over the properties of an object. (Digression: the items in an array are actually just numbered properties in an object.) If you’ve done this before, you’ve used a for-in loop:
var prop, obj = { name: "Joe", job: "Coder", age: 25 };
for (var prop in obj) {
console.log(prop + ": " + obj[prop]);
}If you run the above code, you should see this output:
name: Joe
job: Coder
age: 25
However, browsers will include properties and methods from further up the prototype chain. Most of the time you won’t want to see these when enumerating properties. You should be using the hasOwnProperties to filter out properties that aren’t actually on the object:
Function Dog (name) {
this.name = name;
}
Dog.prototype.legs = 4;
Dog.prototype.speak = function () {
return "woof!";
};
var d = new Dog("Bowser");
for (var prop in d) {
console.log( prop + ": " + d[prop] );
}
console.log("=====");
for (var prop in d) {
if (d.hasOwnProperty(prop)) {
console.log( prop + ": " + d[prop] );
}
}
// Output
// name: Bowser
// legs: 4
// speak: function () {
return "woof!";
// }
// =====
// name: BowserSometimes, you’ll want to let the properties through, but filter out any methods. You can do that by using typeof:
for (var prop in d) {
if (typeof d[prop] !== 'function') {
console.log( prop + ": " + d[prop] );
}
}Either way, always be sure to clarify your for-in statements to avoid unwanted results.
Mistake 6 - You’re Using with or eval
Thankfully, most sources for learning JavaScript today don’t teach you about with or eval. But if you’re using some older material—or using a less-than-reputable source (because sometimes good material is hard to find on the web)—you might have found with and eval and given them a try. Terrible move, web developer.
Let’s start with with. Two main reasons not to use it:
- It really slows down the execution of your JavaScript.
- It’s not always clear what you’re doing.
Point one stands on its own, so let’s look at the second. Quickly, here’s how with works: You pass an object to a with statement; then, inside the with statement block, you can access properties of the object as variables:
var person = { name: "Joe", age : 10 };
with (person) {
console.log(name); // Joe
console.log(age); // 10
}But, what if we have a variable with the same name as a property of the object we’re with-ing? Basically, if both a variable and a property with the same name exist, the variable will be used. The other gotcha is that you can’t add a property to the object inside a with statement: if no property or variable exists, it will be made a variable of the scope outside the with statement:
var person = { name: "Joe", age : 10 },
name = "Billy";
with (person) {
console.log(name); // Billy
job = "Designer";
}
console.log(person.job); // undefined;
console.log(job); // DesignerSo, how about eval? In a nutshell, you can pass a string of code to the function and it will execute the code.
eval( "Console.log('hello!');" );Sounds harmless, even powerful, right? Actually, that’s the main problem: it’s too powerful. There’s obviously no reason to just hand it a hard string that you write directly into your code, because 1) why not just write the code? And 2) eval is slower, just like with. Therefore, the primary use of eval is to execute code that you don’t have at runtime. You could be getting this from the server, or taking code directly from the user. Do you really want to give your website users complete control of your code? I hope not. Also, it opens your site up to unnumbered hackers: using eval is basically a sign that says ”I’m away, and the key is under the mat.” If you love yourself or your users: don’t use it.
Mistake 7 - You’re Not Using a Radix When Using parseInt
JavaScript has a great little helper function called parseInt that allows you to convert a string that contains a number to a number:
parseInt("200"); // 200
parseInt("043"); // 35Um, what happened there? Shouldn’t that second example be 43? Actually, parseInt will work with more than just decimal values: so, when parseInt sees a string that starts with a 0, it assumes that it’s an octal number (base 8). That’s why it’s a mistake not to pass a radix; this tells parseInt what base the number is in (it always outputs a decimal number).
parseInt("020", 10); // 20
parseInt("100", 2); // 4Mistake 8 - You’re Not Using Braces on if and while statements
One of the most obvious beauties of JavaScript is its flexibility. But sometimes, that can come back to fight you. That’s certainly the case with braces on if- and while-statement blocks. These braces are optional if you only have one line of code in the block:
if (true)
console.log("inside the if statement");
This is great, because you can even put them on the same line:
var arr = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"],
i = arr.length - i;
while (i) console.log( arr[i--] );
But this isn’t smart for a couple of reasons: firstly, it can become unclear:
if (true)
console.log("inside the if-statement.");
console.log("outside the if-statement.");
See what I mean? That second line isn’t in the if-statement, but it sure looks like it. Braces would make that clear. Also, if you ever want to add a line to the block, you have to remember to add the braces as well. Just adding them in the first place is so much easier. Do it.
Mistake 9 - You’re Adding Elements to the DOM Individually
All right, all right: this isn’t really JavaScript itself. But, in 99 of 100 cases, JavaScript means using the DOM. While there’s a lot of mistakes you can make when working with the DOM, this is a big one.
I fondly remember the day when I inserted my first DOM element via JavaScript. It’s fun to do, and oh-so-useful, but it unfortunately is a strain on the page: inserting a DOM element forces the browser to completely repaint the page, so if you have a whole bunch of elements to add, adding them one by one is a bad idea:
var list = document.getElementById("list"),
items = ["one", "two", "three", "four"],
el;
for (var i = 0; items[i]; i++) {
el = document.createElement("li");
el.appendChild( document.createTextNode(items[i]) );
list.appendChild(el); // slow, bad idea
}Here’s what you should do instead: use document fragments. Document fragments are a container to hold DOM elements; then instead of inserting each element individually, you can insert them all at once. The document fragment isn’t a node in itself and there will be nothing to show for it in the DOM: it’s just an invisible net for holding DOM elements before you put them into the DOM. So, here’s how you do it:
var list = document.getElementById("list"),
frag = document.createDocumentFragment(),
items = ["one", "two", "three", "four"],
el;
for (var i = 0; items[i]; i++) {
el = document.createElement("li");
el.appendChild( document.createTextNode(items[i]) );
frag.appendChild(el); // better!
}
list.appendChild(frag);Faster, quicker, cleaner—what’s not to love?
Mistake 10 - You’re Not Learning JavaScript
Many people don’t take the time to learn JavaScript right.
JavaScript does not equal jQuery. Did I just shock your sock off? If you found yourself guilty of committing several of the mistakes listed above, you probably need to do some serious JavaScript studying. JavaScript is a language that you can use almost without learning it, which means that so many people don’t take the time to learn it right. Don’t be one of those people: there are so many awesome JavaScript tutorials out there that you have no excuse for not learning the language. If all you know is jQuery (or Mootools, or whatever), you’re really putting yourself in a bad spot.
Mistake 11 - You’re Following all the Rules
Rules are made to be broken.
The last and final mistake you’re making is that you’re following all the rules. Yes, even some of the rules I’ve listed here. As with anything, rules are made to be broken. If you’re relatively new to JavaScript, you should probably avoid with fervour all the mistakes I’ve outlined for you today. But the truth is that if you understand why it’s recommended not to do something, that thing becomes a tool that you might use in just the right circumstance. For example, eval is preached against loudly, but it’s the only tool you can use to parse JSON from a server. Of course, there are many security checks in place when you do it (you should probably use a library). But the point is that you shouldn’t be afraid to knowledgeably use the “bad practices” I’ve listed above if the need arises. It’s the same close-mindedness that causes you to make these mistakes in the first place is the same close-mindedness that keeps you from using them when they are the right tool.
Of course, never make mistake 10 -
Conclusion
If you’re new to JavaScript, hopefully you’re a better JavaScript developer now. If you consider yourself a JavaScript pro (then how are you even still reading this?), what have I missed? Let us all know in the comments!
Thursday, February 10, 2011
Internet Explorer 9 Looks Promising
http://msdn.microsoft.com/en-us/library/gg131029(VS.85).aspx
Thursday, February 3, 2011
Friday, January 21, 2011
Thursday, January 20, 2011
Thursday, November 4, 2010
The 30 CSS Selectors you Must Memorize
So you learned the base id, class, and descendant selectors – and then called it a day? If so, you’re missing out on an enormous level of flexibility. While many of the selectors mentioned in this article are part of the CSS3 spec, and are, consequently, only available in modern browsers, you owe it to yourself to commit these to memory.
1. *
* {
margin: 0;
padding: 0;
}
Let’s knock the obvious ones out, for the beginners, before we move onto the more advanced selectors.
The star symbol will target every single element on the page. Many developers will use this trick to zero out the margins and padding. While this is certainly fine for quick tests, I’d advise you to never use this in production code. It adds too much weight on the browser, and is unnecessary.
The * can also be used with child selectors.
#container * {
border: 1px solid black;
}
This will target every single element that is a child of the #container div. Again, try not to use this technique very much, if every.
View Demo
2. #X
#container {
width: 960px;
margin: auto;
}
Prefixing the hash symbol to a selector allows us to target by id. This is easily the most common usage, however be cautious when using id selectors.
Ask yourself: do I absolutely need to apply an
idto this element in order to target it?
id selectors are rigid and don’t allow for reuse. If possible, first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class.
View Demo
3. .X
.error {
color: red;
}
This is a class selector. The difference between ids and classes is that, with the latter, you can target multiple elements. Use classes when you want your styling to apply to a group of elements. Alternatively, use ids to find a needle-in-a-haystack, and style only that specific element.
View Demo
4. X Y
li a {
text-decoration: none;
}
The next most comment selector is the descendant selector. When you need to be more specific with your selectors, you use these. For example, what if, rather than targeting all anchor tags, you only need to target the anchors which are within an unordered list? This is specifically when you’d use a descendant selector.
Pro-tip – If your selector looks like
X Y Z A B.error, you’re doing it wrong. Always ask yourself if it’s absolutely necessary to apply all of that weight.
View Demo
5. X
a { color: red; }
ul { margin-left: 0; }
What if you want to target all elements on a page, according to their type, rather than an id or classname? Keep it simple, and use a type selector. If you need to target all unordered lists, use ul {}.
View Demo
6. X:visited and X:link
a:link { color: red; }
a:visted { color: purple; }
We use the :link pseudo-class to target all anchors tags which have yet to be clicked on.
Alternatively, we also have the :visited pseudo class, which, as you’d expected, allows us to apply specific styling to only the anchor tags on the page which have been clicked on, or visited.
View Demo
7. X + Y
ul + p {
color: red;
}
This is referred to as an adjacent selector. It will select only the element that is immediately proceeded by the former element. In this case, only the first paragraph after each ul will have red text.
View Demo
8. X > Y
div#container > ul {
border: 1px solid black;
}
The difference between the standard X Y and X > Y is that the latter will only select direct children. For example, consider the following markup.
<div id="container">
<ul>
<li> List Item
<ul>
<li> Child </li>
</ul>
</li>
<li> List Item </li>
<li> List Item </li>
<li> List Item </li>
</ul>
</div>
A selector of #container > ul will only target the uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.
For this reason, there are performance benefits in using the child combinator. In fact, it’s recommended particularly when working with JavaScript-based CSS selector engines.
View Demo
9. X ~ Y
ul ~ p {
color: red;
}
This sibling combinator is similar to X + Y, however, it’s less strict. While an adjacent selector (ul + p) will only select the first element that is immediately proceeded by the former selector, this one is more generalized. It will select, referring to our example above, any p elements, as long as they are followed by a ul.
View Demo
10. X[title]
a[title] {
color: green;
}
Referred to as an attributes selector, in our example above, this will only select the anchor tags that have a title attribute. Anchor tags which do not will not receive this particular styling. But, what if you need to be more specific? Well…
View Demo
11. X[href='foo']
a[href='http://net.tutsplus.com'] {
color: #1f6053; /* nettuts green */
}
The snippet above will style all anchor tags which link to http://net.tutsplus.com; they’ll receive our branded green color. All other anchor tags will remain unaffected.
Note that we’re wrapping the value in quotes. Remember to also do this when using a JavaScript CSS selector engine. When possible, always use CSS3 selectors over unofficial methods.
This works well, though, it’s a bit rigid. What if the link does indeed direct to Nettuts+, but, maybe, the path is nettuts.com rather than the full url? In those cases we can use a bit of the regular expressions syntax.
View Demo
12. X[href*='nettuts']
a[href*='tuts'] {
color: #1f6053; /* nettuts green */
}
There we go; that’s what we need. The star designates that the proceeding value must appear somewhere in the attribute’s value. That way, this covers nettuts.com, net.tutsplus.com, and even tutsplus.com.
Keep in mind that this is a broad statement. What if the anchor tag linked to some non-Envato site with the string tuts in the url? When you need to be more specific, use ^ and &, to reference the beginning and end of a string, respectively.
View Demo
13. X[href^='http']
a[href^='http'] {
background: url(path/to/external/icon.png) no-repeat;
padding-left: 10px;
}
Ever wonder how some websites are able to display a little icon next to the links which are external? I’m sure you’ve seen these before; they’re nice reminders that the link will direct you to an entirely different website.
This is a cinch with the carat symbol. It’s most commonly used in regular expressions to designate the beginning of a string. If we want to target all anchor tags that have a href which begins with http, we could use a selector similar to the snippet shown above.
Notice that we’re not searching for
http://; that’s unnecessary, and doesn’t account for the urls that begin withhttps://.
Now, what if we wanted to instead style all anchors which link to, say, a photo? In those cases, let’s search for the end of the string.
View Demo
14. X[href$='.jpg']
a[href$='.jpg'] {
color: red;
}
Again, we use a regular expressions symbol, $, to refer to the end of a string. In this case, we’re searching for all anchors which link to an image — or at least a url that ends with .jpg. Keep in mind that this certainly won’t work for gifs and pngs.
View Demo
15. X[data-*='foo']
a[data-filetype='image'] {
color: red;
}
Refer back to number eight; how do we compensate for all of the various image types: png, jpeg,jpg, gif? Well, we could create multiple selectors, such as:
a[href$='.jpg'],
a[href$='.jpeg'],
a[href$='.png'],
a[href$='.gif'] {
color: red;
}
But, that’s a pain in the butt, and is inefficient. Another possible solution is to use custom attributes. What if we added our own data-filetype attribute to each anchor that links to an image?
<a href="path/to/image.jpg" data-filetype="image"> Image Link </a>
Then, with that hook in place, we can use a standard attributes selector to target only those anchors.
a[data-filetype='image'] {
color: red;
}
View Demo
16. X[foo~='bar']
a[data-info~='external'] {
color: red;
}
a[data-info~='image'] {
border: 1px solid black;
}
Here’s a special one that’ll impress your friends. Not too many people know about this trick. The tilda (~) symbol allows us to target an attribute which has a spaced-separated list of values.
Going along with our custom attribute from number nine, above, we could create a data-info attribute, which can receive a space-separated list of anything we need to make note of. In this case, we’ll make note of external links and links to images — just for the example.
"<a href="path/to/image.jpg" data-info="external image"> Click Me, Fool </a>
With that markup in place, now we can target any tags that have either of those values, by using the ~ attributes selector trick.
/* Target data-info attr that contains the value 'external' */
a[data-info~='external'] {
color: red;
}
/* And which contain the value 'image' */
a[data-info~='image'] {
border: 1px solid black;
}
Pretty nifty, ay?
View Demo
17. X:checked
input[type=radio]:checked {
border: 1px solid black;
}
This pseudo class will only target a user interface element that has been checked - like a radio button, or checkbox. It's as simple as that.
View Demo
18. X:after
The before and after pseudo elements kick butt. Every day, it seems, people are finding new and creative ways to use them effectively. They simply generate content around the selected element.
Many were first introduced to these classes when they encountered the clear-fix hack.
.clearfix:after {
content: '';
display: block;
clear: both;
visibility: hidden;
font-size: 0;
height: 0;
}
.clearfix {
_display: inline-block;
_height: 1%;
}
This hack uses the :after pseudo element to append a space after the element, and then clear it. It's an excellent trick to have in your tool bag, particularly in the cases when the overflow: hidden; method isn't possible.
For another creative use of this, refer to my quick tip on creating shadows.
According to the CSS3 Selectors specification, you should technically use the pseudo element syntax of two colons
::. However, to remain compatible, the user-agent will accept a single colon usage as well.
19. X:hover
div:hover {
background: #e3e3e3;
}
Oh come on. You know this one. The official term for this is user action pseudo class. It sounds confusing, but it really isn't. Want to apply specific styling when a user hovers over an element? This will get the job done!
Keep in mind that older version of Internet Explorer don't respond when the
:hoverpseudo class is applied to anything other than an anchor tag.
You'll most often use this selector when applying, for example, a border-bottom to anchor tags, when hovered over.
a:hover {
border-bottom: 1px solid black;
}
Pro-tip -
border-bottom: 1px solid black;looks better thantext-decoration: underline;.
20. X:not(selector)
div:not(#container) {
color: blue;
}
The negation psuedo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.
Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:
*:not(p) {
color: green;
}
View Demo
21. X::psuedoElement
p::first-line {
font-weight: bold;
font-size: 1.2em;
}
We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line, or the first letter. Keep in mind that these must be applied to block level elements in order to take effect.
A pseudo-element is composed of two colons:
::
Target the First Letter of a Paragraph
p::first-letter {
float: left;
font-size: 2em;
font-weight: bold;
font-family: cursive;
padding-right: 2px;
}
This snippet is an abstraction that will find all paragraphs on the page, and then sub-target only the first letter of that element.
This is most often used to create newspaper-like styling for the first-letter of an article.
Target the First Line of a Paragraph
p::first-line {
font-weight: bold;
font-size: 1.2em;
}
Similarly, the ::first-line pseudo element will, as expected, style the first line of the element only.
'For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.' - Source
View Demo
22. X:nth-child(n)
li:nth-child(3) {
color: red;
}
Remember the days when we had no way to target specific elements in a stack? The nth-child pseudo class solves that!
Please note that nth-child accepts an integer as a parameter, however, this is not zero-based. If you wish to target the second list item, use li:nth-child(2).
We can even use this to select a variable set of children. For example, we could do li:nth-child(4n) to select every fourth list item.
View Demo
23. X:nth-last-child(n)
li:nth-last-child(2) {
color: red;
}
What if you had a huge list of items in a ul, and only needed to access, say, the third to the last item? Rather than doing li:nth-child(397), you could instead use the nth-last-child pseudo class.
This technique works almost identically from number sixteen above, however, the difference is that it begins at the end of the collection, and works its way back.
View Demo
24. X:nth-of-type(n)
ul:nth-of-type(3) {
border: 1px solid black;
}
There will be times when, rather than selecting a child, you instead need to select according to the type of element.
Imagine mark-up that contains five unordered lists. If you wanted to style only the third ul, and didn't have a unique id to hook into, you could use the nth-of-type(n) pseudo class. In the snippet above, only the third ul will have a border around it.
View Demo
25. X:nth-last-of-type(n)
ul:nth-last-of-type(3) {
border: 1px solid black;
}
And yes, to remain consistent, we can also use nth-last-of-type to begin at the end of the selectors list, and work our way back to target the desired element.
26. X:first-child
ul li:first-child {
border-top: none;
}
This structural pseudo class allows us to target only the first child of the element's parent. You'll often use this to remove borders from the first and last list items.
For example, let's say you have a list of rows, and each one has a border-top and a border-bottom. Well, with that arrangement, the first and last item in that set will look a bit odd.
Many designers apply classes of first and last to compensate for this. Instead, you can use these pseudo classes.
View Demo
27. X:last-child
ul > li:last-child {
color: green;
}
The opposite of first-child, last-child will target the last item of the element's parent.
Example
Let's build a simple example to demonstrate one possible use of these classes. We'll create a styled list item.
Markup
<ul>
<li> List Item </li>
<li> List Item </li>
<li> List Item </li>
</ul>
Nothing special here; just a simple list.
CSS
ul {
width: 200px;
background: #292929;
color: white;
list-style: none;
padding-left: 0;
}
li {
padding: 10px;
border-bottom: 1px solid black;
border-top: 1px solid #3c3c3c;
}
This styling will set a background, remove the browser-default padding on the ul, and apply borders to each li to provide a bit of depth.
To add depth to your lists, apply a
border-bottomto eachlithat is a shade or two darker than theli's background color. Next, apply aborder-topwhich is a couple shades lighter.
The only problem, as shown in the image above, is that a border will be applied to the very top and bottom of the unordered list - which looks odd. Let's use the :first-child and :last-child pseudo classes to fix this.
li:first-child {
border-top: none;
}
li:last-child {
border-bottom: none;
}
There we go; that fixes it!
View Demo
28. X:only-child
div p:only-child {
color: red;
}
Truthfully, you probably won't find yourself using the only-child pseudo class too often. Nonetheless, it's available, should you need it.
It allows you to target elements which are the only child of its parent. For example, referencing the snippet above, only the paragraph that is the only child of the div will be colored, red.
Let's assume the following markup.
<div><p> My paragraph here. </p></div>
<div>
<p> Two paragraphs total. </p>
<p> Two paragraphs total. </p>
</div>
In this case, the second div's paragraphs will not be targeted; only the first div. As soon as you apply more than one child to an element, the only-child pseudo class ceases to take effect.
View Demo
29. X:only-of-type
li:only-of-type {
font-weight: bold;
}
This structural pseudo class can be used in some clever ways. It will target elements that do not have any siblings within its parent container. As an example, let's target all uls, which have only a single list item.
First, ask yourself how you would accomplish this task? You could do ul li, but, this would target all list items. The only solution is to use only-of-type.
ul > li:only-of-type {
font-weight: bold;
}
View Demo
30. X:first-of-type
The first-of-type pseudo class allows you to select the first siblings of its type.
A Test
To better understand this, let's have a test. Copy the following mark-up into your code editor:
<div>
<p> My paragraph here. </p>
<ul>
<li> List Item 1 </li>
<li> List Item 2 </li>
</ul>
<ul>
<li> List Item 3 </li>
<li> List Item 4 </li>
</ul>
</div>
Now, without reading further, try to figure out how to target only 'List Item 2'. When you've figured it out (or given up), read on.
Solution 1
There are a variety of ways to solve this test. We'll review a handful of them. Let's begin by using first-of-type.
ul:first-of-type > li:nth-child(2) {
font-weight: bold;
}
This snippet essentially says, 'find the first unordered list on the page, then find only the immediate children, which are list items. Next, filter that down to only the second list item in that set.
Solution 2
Another option is to use the adjacent selector.
p + ul li:last-child {
font-weight: bold;
}
In this scenario, we find the ul that immediately proceeds the p tag, and then find the very last child of the element.
Solution 3
We can be as obnoxious or as playful as we want with these selectors.
ul:first-of-type li:nth-last-child(1) {
font-weight: bold;
}
This time, we grab the first ul on the page, and then find the very first list item, but starting from the bottom!
View Demo
Conclusion
If you're compensating for older browsers, like Internet Explorer 6, you still need to be careful when using these newer selectors. But, please don't let that deter you from learning these. You'd be doing a huge disservice to yourself.
Secondly, when working with JavaScript libraries, like the popular jQuery, always try to use these native CSS3 selectors over the library's custom methods/selectors, when possible. It'll make your code faster, as the selector engine can use the browser's native parsing, rather than its own.
Thanks for reading, and I hope you picked up a trick or two!
Thursday, October 28, 2010
Wednesday, October 20, 2010
Monday, October 18, 2010
Send email using Gmail as a free SMTP with Java Mail
This can be simplified to be tested with a Linux sendmail server or Apache James on Windows. Just make sure you test this on a network that won't block your test calls otherwise you'll go crazy trying to debug and won't find a problem in your code or configuration. Also make sure to poke the right holes through your firewall.
Wednesday, October 13, 2010
Usability Resources to Win Arguments
Today’s post is a big one and it’s most definitely one for your bookmarks menu, because from time to time when speaking with clients it becomes necessary to have material to backup the statements which you are making.
Sometimes clients will suggest things such as forcing all users to register with a six page long form before they can even access the site. They aren’t web professionals, it’s not their fault for not knowing that this isn’t a good idea from a usability perspective.
If you’re going to convince them that this is a bad idea, however, then you’re going to need some rock solid material to back that up. While an element of trust is always important to a working relationship, you have to respect that sometimes clients will just need to see the facts in front of them to fully understand that what you’re saying is correct.
So, what we’ve done for you today is compiled a list of some of the biggest, most compelling usability articles which address common issues. Hopefully this should help you during tough conversations about what does and doesn’t work on a a website.
Bookmark this post, come back to it, use it in meetings and educate your clients on the things which work for other websites, so that they might also work for them.
How Not Forcing Users to Register Increased Sales by $300million
A truly fascinating article covering how one ecommerce site removed forced user-registration during the checkout process, with a result of a $300million increase in revenue. Very impressive.
10 Useful Usability Findings and Guidelines
- Form labels work best above the field
- Users focus on faces
- Quality of design is an indicator of credibility
- Most users do know how to scroll
- Blue is the best color for links
- The ideal search box is 27 characters wide
- White space improves comprehension
- Effective user testing doesn’t have to be extensive
- Informative product pages stand out
- Most users are blind to advertising
Browser Resolution Stats by Google
A big diagram by google showing browsers sizes overlaid on top of a web page and where you should place call to actions to ensure that they are immediately visible without the need to scroll.
The myth of the page fold: evidence from user testing
“People tell us that they don’t mind scrolling and the behaviour we see in user testing backs that up. We see that people are more than comfortable scrolling long, long pages to find what they are looking for. A quick snoop around the web will show you successful brands that are not worrying about the fold either.”
247 web usability guidelines
A massive post of usability articles covering:
- Home page usability: 20 guidelines to evaluate the usability of home pages.
- Task orientation: 44 guidelines to evaluate how well a web site supports the users tasks.
- Navigation and IA: 29 guidelines to evaluate navigation and information architecture.
- Forms and data entry: 23 guidelines to evaluate forms and data entry.
- Trust and credibility: 13 guidelines to evaluate trust and credibility.
- Writing and content quality: 23 guidelines to evaluate writing and content quality.
- Page layout and visual design: 38 guidelines to evaluate page layout and visual design.
- Search usability: 20 guidelines to evaluate search.
- Help, feedback and error tolerance: 37 guidelines to evaluate help, feedback and errors
An Introduction to Using Patterns in Web Design
A fascinating article covering the use of patterns for usability in web design, or “chunks” as the author calls them!
F-Shaped Pattern For Reading Web Content
Eye-tracking visualizations show that users often read Web pages in an F-shaped pattern: two horizontal stripes followed by a vertical stripe.
Top Ten Mistakes in Web Design
The ten most egregious offenses against users. Web design disasters and HTML horrors are legion, though many usability atrocities are less common than they used to be.
Weblog Usability: The Top Ten Design Mistakes
Blogs are often too internally focused and ignore key usability issues, making it hard for new readers to understand the site and trust the author.
Top-10 Application-Design Mistakes
Application usability is enhanced when users know how to operate the UI and it guides them through the workflow. Violating common guidelines prevents both.
Mega Drop-Down Navigation Menus Work Well
Big, two-dimensional drop-down panels group navigation options to eliminate scrolling and use typography, icons, and tooltips to explain the user’s choices.
10 Usability Crimes You Really Shouldn’t Commit
A big post by Chris Spooner covering forms, logo links, link states, alt attributes, background images, content, link text and text alignment.
101 Five-Minute Fixes to Incrementally Improve Your Web Site
An absolutely huge post covering quick improvements for usability across so many different levels. This is great one for picking out things that your client’s site might need to have done to it!
Blasting the Myth of the Fold
Another article slamming the idea that nothing below the fold ever gets seen. Users know how to scroll. The fold is relevant for a few things, but it is not the be-all and end-all.
UX Myths
A great site which is regularly updated with a list of (sometimes funny) myths of user experience issues, these include things such as “all pages should be accessible in 3 clicks” and “the home page is your more important one”.
Eyetracking points the way to effective news article design
Real eye tracking tests carried out and showing interesting results with regards to the effectiveness of laying out new articles and blog posts.
Label Placement in Forms
A detailed case study showing that the optimum placement for label forms is to the top-right of the form field.
12 Standard Screen Patterns
A great rouncup of some standard screen layouts which may pursuade clients away from spherical invisible navigation, or similar.
“Mad Libs” Style Form Increases Conversion 25-40%
This interesting article covers how well forms work when arranged as blanks within sentences rather than simple linear pages.
Breadcrumbs In Web Design: Examples And Best Practices
“On websites that have a lot of pages, breadcrumb navigation can greatly enhance the way users find their way around. In terms of usability, breadcrumbs reduce the number of actions a website visitor needs to take in order to get to a higher-level page, and they improve the findability of website sections and pages.”
Inline Validation in Web Forms
A study by A List Apart on inline validation in forms with live user videos showing the differences between standard forms vs inline validation.
This post was authored exclusively for WDD by John O’Nolan, a core contributor to the WordPress UI Team, writer and entrepreneur based in Surrey in the United Kingdom. John loves to talk to people, so why not follow @JohnONolan on twitter too?
What about you? Do you have any really great articles like these which you think would be a good addition to the list? Drop us a line in the comments below so that everyone can benefit from them!
If you find an exclusive RSS freebie on this feed or on the live WDD website, please use the following code to download it: H0Oa9C
Tuesday, October 5, 2010
Finding all class declarations in an HTML document
(class|styleClass)=\"[^\"]+\"
It means find a string with the following properties:
- Starts with a space character (granted, this may not catch all cases, but you can tweak it).
- Then look for "class" or "styleClass", which is a way to declare it in JSF
- Now an "=" and double quotes
- Followed by anything except double quotes (this keeps it from including the subsequent attributes in the find)
- Ends in double quotes
Thursday, July 8, 2010
30+ Very Useful HTML5 Tutorials, Techniques and Examples for Web Developers
HTML5 is being developed as the next major revision of HTML (HyperText Markup Language). The major market and internet leaders are already switching to the HTML 5 platform. With Apple and Google both pushing the standards in order to facilitate more advanced web development, we should see HTML 5 implementations popping up in the next year or two as more companies get on board with the advanced features.
With the constant drop of Flash usage in web and internet applications, HTML5 is opening new doors to web designers and developers. In this scenario, it is indeed imperative for every web developer to know about basic tutorials, tricks and terms of HTML5.
Here we present before you, a comprehensive list of more than 30 HTML5 tutorials and techniques that you can’t afford to miss if you are a web developer.
Create Offline Web Application On Mobile Devices With HTML5
A comprehensive article from the technical library of IBM by IT Architect Dietmar Krueger. In this article, the author describes and explains how challenging it i s to write application for operating systems and mobile platforms. Instead of relying on learning the platform specific languages like Objective-C with Cocoa (on iPhone), the author takes the open way of developing things through HTML5. A very clearly explained and in-depth article.
HTML 5 Demos and Examples
HTML 5 experimentation and demos I’ve hacked together. Click on the browser support icon or the technology tag to filter the demos (the filter is an
OR filter).WTF is HTML5
One page overview of HTML5 – very useful!
Building a live news blogging system in PHP, Spiced with HTML5
This tutorial show you how to build a news website in HTML5 and CSS3. Every line of code is explained for both HTML and CSS
Designing A Blog With HTML5
Much of HTML 5’s feature set involves JavaScript APIs that make it easier to develop interactive web pages but there are a slew of new elements that allow you extra semantics in your conventional Web 1.0 pages. This tutorial investigate these by setting u a blog layout.
Semantics in HTML 5
HTML 5, the W3C’s recently redoubled effort to shape the next generation of HTML, has, over the last year or so, taken on considerable momentum. It is an enormous project, covering not simply the structure of HTML, but also parsing models, error-handling models, the DOM, algorithms for resource fetching, media content, 2D drawing, data templating, security models, page loading models, client-side data storage, and more.
There are also revisions to the structure, syntax, and semantics of HTML, some of which Lachlan Hunt covered in “A Preview of HTML 5.”
In this article, let’s turn solely to the semantics of HTML. It’s something the author has been interested in for many years, and something which he believe is fundamentally important to the future of HTML.
HTML5 Web Applications
HTML 5 browser compatibility overview.
Dive into HTML5
Dive Into HTML 5 seeks to elaborate on a hand-picked Selection of features from the HTML5 specification and other fine Standards. I shall publish Drafts periodically, as time permits. Please send feedback. The final manuscript will be published on paper by O’Reilly, under the Google Press imprint. Pre-order the printed Work and be the first in your Community to receive it.
When Can I Use
Here you will find very useful compatibility tables for features in HTML5, CSS3, SVG and other upcoming web technologies.
HTML5 & CSS3 Readiness
How to Draw with HTML 5 Canvas
Among the set of goodies in the HTML 5 specification is Canvas which is a way to programmatically draw using JavaScript. We’ll explore the ins and outs of Canvas in this article, demonstrating what is possible with examples and link
Have a Field Day with HTML5 Forms
Forms are usually seen as that obnoxious thing we have to markup and style. I respectfully disagree: forms (on a par with tables) are the most exciting thing we have to work with.
Here we’re going to take a look at how to style a beautiful HTML5 form using some advanced CSS and latest CSS3 techniques. I promise you will want to style your own forms after you’ve read this article.
Coding Up a Web Design Concept into HTML5
Code a Backwards Compatible, One Page Portfolio with HTML5 and CSS3
HTML5 is the future of web development but believe it or not you can start using it today. HTML5 is much more considerate to semantics and accessibility as we don’t have to throw meaningless div’s everywhere. It introduces meaningful tags for common elements such as navigations and footers which makes much more sense and are more natural.
This is a run through of the basics of HTML5 and CSS3 while still paying attention to older browsers. Before we start, make note of the answer to this question.
Coding A HTML 5 Layout From Scratch
While it is true HTML5 and CSS3 are both a work in progress and is going to stay that way for some time, there’s no reason not to start using it right now. After all, time’s proven that implementation of unfinished specifications does work and can be easily mistaken by a complete W3C recommendation. That’s were Progressive Enhancement and Graceful Degradation come into play.
How to Make an HTML5 iPhone App
You’ve been depressed for like a year now, I know. All the hardcore Objective-C developers have been having a hay-day writing apps for the iPhone. You might have even tried reading a tutorial or two about developing for the iPhone, but its C—or a form of it—and it’s really hard to learn.
You can also do it with the skill set you probably already have: HTML(5), CSS, and JavaScript.
This tutorial show you how to create an offline HTML5 iPhone application. More specifically, I’ll walk you through the process of building a Tetris game.
Create An Elegant Website With HTML 5 And CSS3
Learn five macro-steps to build an effective website using brain, pencil, paper, Photoshop, HTML and CSS. But technology doesn’t stop, luckily, and we have other two great allies for the future to design better website: HTML 5 and CSS3.
Coding a CSS3 & HTML5 One-Page Website Template
See how to create a HTML5 web template, using some of the new features brought by CSS3 and jQuery, with the scrollTo plug-in. As HTML5 is still a work in progress, you can optionally download a XHTML version of the template here.
Design & Code a Cool iPhone App Website in HTML5
HTML5 is definitely the flavor of the month, with everyone in the design community getting excited about its release. In this tutorial we’ll get a taste of what’s to come by building a cool iPhone app website using a HTML5 structure, and visual styling with some CSS3 effects.
HTML 5 and CSS 3: The Techniques You’ll Soon Be Using
In this tutorial, we are going to build a blog page using next-generation techniques from HTML 5 and CSS 3. The tutorial aims to demonstrate how we will be building websites when the specifications are finalized and the browser vendors have implemented them. If you already know HTML and CSS, it should be easy to follow along.
HTML5 for Beginners. Use it now, its easy!
HTML5 for Beginners. Use it now, its easy! This article cover some of the HTML5 basics in a funny way…
Rocking HTML5
This presentation is an HTML5 website and it is a very informative and easy to use overview of the HTML5 elements.
Building Web Pages With HTML 5
Depending on who you ask, HTML 5 is either the next important step toward creating a more semantic web or a disaster that’s going to trap the web in yet another set of incomplete tags and markup soup.
The problem with both sides of the argument is that very few sites are using HTML 5 in the wild, so the theoretical solutions to its perceived problems remain largely untested.
That said, it isn’t hard to see both the benefits and potential hang-ups with the next generation of web markup tools.
HTML5 Cheat Sheet
HTML 5 Visual Cheat Sheet is an useful cheat sheet for web designers and developers designed by me. This cheat sheet is essentially a simple visual grid with a list of all HTML tags and of their related attributes supported by HTML versions 4.01 and/or 5. The simple visual style I used to design this sheet allows you to find at a glance everything you are looking for.
html5test.com
This is a browser test with a lot of detail. Very useful.
HTML5 Canvas Experiment
Time for us to play with this technology. We’ve created a little experiment which loads 100 tweets related to HTML5 and displays them using a javascript-based particle engine. Each particle represents a tweet – click on one of them and it’ll appear on the screen. (click on the image to see it in action)
HTML 5 Cheat Sheet (PDF)
html5 Pocketbooks
OK You have seen that HTML 5 is here, but should you use it?
Generally I think it depends on the site you are working on. If it is a high traffic commercial website you may want to hold it back a bit. However if it is a personal blog I believe it is time to get started and learn how to use the new features in HTML 5.
Actually HTML5 is used more than you may think already. You should check out the sites featured on HTML 5 Gallery and view source to see what they’re doing. Also there is already a HTML 5 Wordpress theme available.
Other interesting posts on this topic
- 23 Essential HTML 5 Resources @ carsonified.com
- 70 Must-Have CSS3 and HTML5 Tutorials and Resources @ webappers.com
- 15 Useful HTML5 Tutorials and Cheat Sheets @ webdesignledger.com
- 22 Examples of Fresh Html 5 Websites @visionwidget.com
Feed provided by tripwrire magazine, Visit this post here: Permalink