Hard-earned webdev knowledge at your fingertipsCode Crafting BlueprintsTumblr (3.0; @codecraftingblueprints)https://codecraftingblueprints.com/Make CSS fun again with SASS!<p>CSS is powerful, with few changes you can make your website look completely different. You can easily separate design from markup and create amazing designs. Although CSS is simple I used to have a hard time structuring my documents and I often ended up with lots of duplicated rules. That ended when I found SASS, which in my opinion is the biggest revolution of web development ever.</p> <h2>So, what is SASS?</h2> <p>Sass stands for &#8220;Syntactically Awesome Stylesheets&#8221; and comes in two flavors. SASS, the original format with indented syntax and SCSS which is CSS compatible. Since I&#8217;m an old school user I&#8217;ll focus on the SASS format in this article.</p> <p>This quote comes from the <a href="http://sass-lang.com/">official site</a> and describes the purpose well:</p> <blockquote> <p>Sass is a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.</p> </blockquote> <h2>Nice huh, but why would you use it?</h2> <p>Before I&#8217;ll show some examples I really hope to sell this so you so here are some benefits:</p> <ul><li>I&#8217;ve saved hundreds and hundreds of hours in the 3 - 4 years that I&#8217;ve used SASS.</li> <li>I have never used the <code>find and replace</code> function in a CSS file since then.</li> <li>I have never scrolled down a 10000 lines long file trying to find a specific rule.</li> </ul><h2>import files</h2> <p>In SASS a file named style.sass would be compiled to a file called style.css. If you prepend the filename with an underscore the file won&#8217;t be compiled at all and you can include it within another file. This makes is easy to keep a logic structure of rules, for example:</p> <pre><code>@import 'reset' @media only screen and (min-width: 768px) @import 'tablet' @media only screen and (max-width: 480px) @import 'mobile' </code></pre> <p>The file above is named <code>style.sass</code> and includes all the rules in the file called <code>_reset.sass</code>. As mentioned before SASS uses syntactical whitespace and nesting so the rules within the file called <code>_tablet.sass</code> would only be applied inside the first media query. Sass will compile <code>style.sass</code> into a single file but you can structure the rules in as many files that you want.</p> <h2>Variables</h2> <p>You can use even use variables to define rules. This was the feature i missed the most while I was hacking CSS. Define colors, margins, paddings or anything else you want to be able to easily change.</p> <pre><code>$link_color: #007bc0 a:link, a:visted color: #{$link_color} </code></pre> <p>You can even perform calculations:</p> <pre><code>$link_hover_color: $link_color - #111 a:hover, a:active color: #{$link_hover_color} </code></pre> <p>This makes it very easy to change colors</p> <h2>Mixins</h2> <p>Mixins is a really powerful feature of SASS which makes it possible to reuse blocks of rules on any given selector. Are your tired of retyping the same vendor prefixes over and over again? I sure was. Check out this example:</p> <pre><code>@mixin border_radius($top, $right: '', $bottom: '', $left: '') @if $right == '' -moz-border-radius: #{$top}px #{$top}px #{$top}px #{$top}px -webkit-border-radius: #{$top}px #{$top}px #{$top}px #{$top}px border-radius: #{$top}px #{$top}px #{$top}px #{$top}px @else -moz-border-radius: #{$top}px #{$right}px #{$bottom}px #{$left}px -webkit-border-radius: #{$top}px #{$right}px #{$bottom}px #{$left}px border-radius: #{$top}px #{$right}px #{$bottom}px #{$left}px </code></pre> <p>This mixin defines a set of rules for any element. Use it like this:</p> <pre><code>#call-to-action @include border_radius(10px) </code></pre> <p>If you want different radius for different corners, then just add more arguments:</p> <pre><code>#call-to-action @include border_radius(10px, 4px, 16px, 12px) </code></pre> <p>Mixins makes it fun to try out new features of CSS since you can generate all the vendor prefixes dynamically, but it doesn&#8217;t stop there. Imagine the relief of removing all the duplication in a bloated CSS file.</p> <h2>Other resources</h2> <ul><li><a href="http://sass-lang.com/">SASS&#8217; official site</a></li> <li><a href="https://github.com/nex3/sass">SASS source code</a> on Github</li> <li><a href="http://compass-style.org/">Compass</a> a framework built upon sass.</li> </ul><h2>Conclusion</h2> <p>I hope I&#8217;m a good enough writer to make you see how powerful this is. As stated before this saves a lot of time and makes CSS fun.</p> <p>Happy SASSing!</p> <p>Written by: <a href="/ola-karlsson" rel="author">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 19 Apr 2012 14:36:44 -0400SASSCSSFrontendolkarlsBetter Inputs with HTML5<p>Form elements are the backbone of all web applications. It&#8217;s through these that we&#8217;re able to collect input from our users. Up until recently we&#8217;ve had to live with a pretty limited set of form elements and it&#8217;s quite remarkable what we&#8217;ve been able to do with them.</p> <p>We&#8217;ve essentialy been stuck with 4 types of elements:</p> <ul><li>Input</li> <li>Textarea</li> <li>Select</li> <li>Button</li> </ul><p>Of these 4 elements the most versitile is the <code>&lt;input&gt;</code> element. Depending on its type attribute it can serve in several different shapes such as a text field, a checkbox, a submit button, etc.</p> <p>Sure it&#8217;s versitile but there are still plenty of cases where we could really use better ones.</p> <h2>New Input Types</h2> <p>With the advent of HTML5 we suddenly have a lot of new, improved, input types at our disposal. Some of them still have such scarse browser adoption that they&#8217;re not a good option yet. But there are several that we can use right away to enhance the User Experience and they even degrade gracefully for older browsers.</p> <h2>Enhancing your inputs - HTML5 Style</h2> <h3>Improved Email Field</h3> <p>Our first candidate is email. Think about how often you enter your email into fields on various web sites. Then think about how awkward it is to do that on your smart phone when you have to switch mode on the keyboard to access the @-key.</p> <p>Luckily it&#8217;s easy to enhance that input with the new input type called, you probably guessed… That&#8217;s right: <code>email</code>.</p> <pre><code>&lt;input type="email" name="email-address" id="email-address /&gt; </code></pre> <p>It might not come as a big suprise that those who benefits most from this input type are smart phone users. What it does for those is to automatically display the email specific keyboard which has the @-key already visible.</p> <p>Another benefit is that the first letter doesn&#8217;t default to being upper case as it is on inputs of type <code>text</code> in iOS. This is really great because most of us normally wouldn&#8217;t write our email-addresses starting with a capital letter. At least for me, that just looks plain weird.</p> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2if8EbP1qfjouz.png" alt=""/><figcaption>The Email enhanced keyboard in iOS</figcaption></figure></p> <p>As an extra perk, this input type also triggers some rudimantary email validation on submit in some browsers. Here&#8217;s how it looks in Google Chrome.</p> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2n5fS4q1qfjouz.png" alt=""/><figcaption>The validation message is in Swedish but says: &#8220;Enter a Email address&#8221;</figcaption></figure></p> <p>If you want to prevent the browser from performing this validation you can add the attribute <code>formnovalidate</code> to the submit button.</p> <pre><code>&lt;input type="submit" value="Send" formnovalidate /&gt; </code></pre> <h3>Better URL input</h3> <p>A related input type to <code>email</code> is <code>url</code>. It works the exact same way, including validation, but brings up the url enhanced keyboard on smart phones.</p> <pre><code>&lt;input type="url" name="your-url" /&gt; </code></pre> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2l6CEB81qfjouz.png" alt=""/><figcaption>The URL enhanced keyboard in iOS</figcaption></figure></p> <h2>A better search form</h2> <p>Another new input type is search. What this does exactly is a bit unclear, and the W3C specification is very vauge on how it should behave but it potentially bare a lot of promise.</p> <p>One trait seems to be that it gets a different style in some browsers. A style with rounded corners.</p> <p>In Google Chrome it gets a small x on the right hand side, which you can click to delete the inputed text. It also displays a dropdown with recent searches.</p> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2mh01NC1qfjouz.png" alt=""/><figcaption>The Search Input in Google Chrome</figcaption></figure></p> <p>The special styling in Webkit browsers (Chrome and Safari) can make custom styling of the input really hard. Fortunately you can disable this styling with this CSS rule.</p> <pre><code>-webkit-appearance: none; </code></pre> <p>It reverts the search input to look like an ordinary text input and you are yet again free to style it in any way your heart desires.</p> <p>Check out <a href="http://wufoo.com/html5/types/5-search.html">The search Type</a> for a more in-depth view on what this input type does in different browsers.</p> <h3>Entering phone numbers have never been easier</h3> <p>Entering phone numbers on a phone and not having access to the special numpad that&#8217;s built into the phone is plain dumb! There&#8217;s a reason that the numpad is designed the way it is - it makes it easier to dial numbers, duh!</p> <p>So do your mobile users a favor and make sure that whenever you want them to enter phone numbers, use the input type <code>tel</code>.</p> <pre><code>&lt;input type="tel" name="phone-number" /&gt; </code></pre> <p>This brings up the thumb-friendly keypad. At least in iOS.</p> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2pgEd9W1qfjouz.png" alt=""/><figcaption>The telephone numpad in iOS</figcaption></figure></p> <h3>Crunching numbers in style</h3> <p>Quite often, at least in web applications, you need the user to enter numbers. And guess what! There&#8217;s a special input type for that too. It&#8217;s called <code>number</code> and it brings up the keyboard in number mode on smart phones.</p> <pre><code>&lt;input type="number" name="magic-number" /&gt; </code></pre> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2pzveEJ1qfjouz.png" alt=""/><figcaption>The iOS keyboard in number mode</figcaption></figure></p> <p>Sure it&#8217;s nice to have the keyboard with the numbers already showing. After all it saves you one keypress to switch to this mode. But didn&#8217;t we have an even better numpad that we could use - at least for integers?</p> <p>Sure you could use the tel type. But unless it really is a phone number you want them to enter that&#8217;s not really appropriate.</p> <p>But there is actually another way to elicit the numpad, at least on Mobile Safari.</p> <p>There&#8217;s a new attribute in HTML5 called <code>pattern</code>. It takes a regular expression as its value that determines what a valid input is. If you enter <code>[0-9]*</code> it will tell the browser that only numbers are valid entries in this particular input and that will also make Mobile Safari bring up the numpad.</p> <pre><code>&lt;input type="number" name="magic-number" pattern="[0-9]*" /&gt; </code></pre> <p>(Kudos to <a href="http://davidgoss.co.uk/2012/02/06/better-numerical-inputs-for-mobile-forms/">David Goss</a> for this neat little trick)</p> <p>But what about desktop browsers? Well in some browsers, specifically Chrome, Safari and Opera, the numeric input type will render as a spinner. You can either click the small arrows to increase or decrease the value. Or you can use the arrow keys on the keyboard to do the same.</p> <p><figure><img src="http://media.tumblr.com/tumblr_m2c2qlFlwH1qfjouz.png" alt=""/><figcaption>The number input in Google Chrome</figcaption></figure></p> <h2>Can I use these now?</h2> <p>Yes, you can! The beauty of all these new input types is that if a browser doesn&#8217;t support them, it will just revert to a common, plain, vanilla text box. And no harm is done.</p> <p>This is really good because it means that using these input types are totally safe. And I&#8217;m sure that especially your mobile users will thank you for it.</p> <h2>References</h2> <h3>Books</h3> <p><a href="http://html5forwebdesigners.com">HTML5 for Web Designers</a> by Jeremy Keith (You can also read it online)</p> <p><a href="http://introducinghtml5.com/">INTRODUCING HTML5</a> by Bruce Lawson and Remy Sharp</p> <h3>Online</h3> <p><a href="http://wufoo.com/html5/">The Current State of HTML5 Forms</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 12 Apr 2012 04:09:00 -0400HTMLsvennerbergHow to keep yourself and your customer happy<p>The phone rings and an excited voice is heard on the other side of the line. I&#8217;ve got this amazing idea! It&#8217;s a totally untapped market and I already have the investors lined up waiting to pay up. Can you build this service and I&#8217;ll pay you later or maybe you rather have some of the stocks?</p> <h2>$elling your time</h2> <p>There are three different types of projects that I often stumble upon. It could be clear, unclear or a complete mess. The strategies differ depending on how well the project is defined:</p> <ul><li><p>If the project is well specified, has a clear goal and no loose threads then go for a fixed price but be sure to specify what&#8217;s included.</p></li> <li><p>If it&#8217;s unclear, make the customer specify the missing parts. Help them by asking many questions and charge for the time spent.</p></li> <li><p>If the project is nothing more than an idea without substance then maybe you can help them write the specification and charge for it. Don&#8217;t give a fixed price because this could take time.</p></li> </ul><p>Don&#8217;t forget to get the customers signature on the specification. This makes the project real for both you and the customer.</p> <p>If you use a fixed rate and it&#8217;s a big project send a partial invoice at the start.</p> <h2>Planning</h2> <p>Before you launch your editor, itching to start coding, you have to plan the project. This is where most time is saved, it is not by using the newest and coolest ruby gems out there.</p> <p>Try to break up the project in small well defined units with a clear goal. This could be something like: list products, user registration or search. Make them so small that you could finish the whole part within days.</p> <h2>Roll up your sleeves and start coding…not yet</h2> <p>There is one more important thing to do before you can do any real work. And that is hosting.</p> <p>No matter how big or small the project is, make sure you have somewhere to host it. You should publish new releases often, several times a day actually.</p> <p>The customer must be able to see the progress you&#8217;re making. This pushes the project forward and keep both parts motivated. It also makes you confident that the code works &#8220;for real&#8221;.</p> <h2>Coding</h2> <p>If you&#8217;ve done the planning right this is a no-brainer. Just do what you must to get the parts finished. If you encounter some problems make sure to let the customer know about it.</p> <h2>Conclusion</h2> <p>The key to a profitable, fun and stable project is planning. Planning might not be the sexiest part of the project but it sure is the stage where you save the most time.</p> <p>It&#8217;s important to get payed but it&#8217;s even more important to over deliver. Remember your last project should always be your best.</p> <p>Written by: <a rel="author" href="/ola-karlsson">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 05 Apr 2012 11:58:00 -0400tipsolkarlsMake Click Areas Comfortably Large<p>Have you ever been browsing a web site on your smart phone or tablet and found that on some sites, the links are so tiny and so tightly packed, that it&#8217;s near impossible to click the right one?</p> <p>I have definitely been there and it&#8217;s equally frustrating each time. As the use of smart phones and tablets increases, so does the importance of having big enough target areas to interact with. But it&#8217;s not only important for mobile browsing. The truth is that it benefits desktop users as well.</p> <h2>Fitts&#8217;s Law</h2> <p><a href="http://en.wikipedia.org/wiki/Fitts's_law" title="About Fitts's law on Wikipedia">Fitts&#8217;s Law</a> is a classic rule of thumb in Usability. The law can be expressed in a fairly complex mathematical way but in a nutshell it states that <strong>the larger and closer a target is, the easier and faster it is to click it</strong>.</p> <p><img src="http://media.tumblr.com/tumblr_m1k8d4IkzB1qfjouz.png" alt=""/></p> <p>It&#8217;s not exactly Rocket Science, but still it highlights the importance of having, not only big enough targets, but also to position them intelligently.</p> <p>If you want to know more about Fitts&#8217;s Law there&#8217;s an excellent explanation over at <a href="http://particletree.com/features/visualizing-fittss-law/" title="Visulizing Fitts's Law">Particle Tree</a>.</p> <h2>Designing for Touch</h2> <p>For touch devices, such as smart phones and tablets, a big enough touch target is even more important than on desktop. While a mouse pointer is a precision instrument with a click area of just 1 x 1 pixel, a human finger is more of a sledge hammer. The avarage size of the pad of a human index finger is 1.6 to 2&#160;cm which translates to about 45-57 pixels on a screen.</p> <p>You&#8217;ve probably experienced the frustration yourself when trying to click small links that are tightly packed on a smart phone. It can be really hard to hit the right target and that&#8217;s not the experience you want people to have with your web site.</p> <p><figure><img src="http://media.tumblr.com/tumblr_m1k8g6vaj51qfjouz.jpg" alt=""/> Image credit: <a href="http://www.flickr.com/people/75227967@N00/">sochacki.info</a> </figure></p> <h3>Recommended touch target sizes</h3> <p>Apple iOS Human Interface Guidelines state that a touch target should be at least 44 x 44 points large. (The reason they&#8217;re using points instead of pixels is that points can be used for both standard and retina displays).</p> <p>Microsoft&#8217;s Windows Phone UI Design and Interaction Guide suggest that the size of the touch target should be 34 pixels with an absolute minimum of 26 pixels and Nokia&#8217;s Developer Guidelines state that the touch target should be at least 1 x 1&#160;cm.</p> <p>I actually I think that Nokia has the best guidelines since it states its minimum dimensions in cm. I mean 44 pixels can be very different on different screens and devices.</p> <h3>What you don&#8217;t have in size you can make up in space</h3> <p>Another interesting aspect of this is that if you absolutely do need to have relatively small touch targets you can partly compensate that by increasing the space between the targets. By doing that you limit the chance of missed targets.</p> <p>The rule is: <strong>The smaller the target, the bigger the gap</strong>.</p> <p><img src="http://media.tumblr.com/tumblr_m1k9s8NiHV1qfjouz.png" alt=""/></p> <h2>In Practice</h2> <p>Enough already, I think you get why it&#8217;s important to have big enough click/touch targets. The question is, how is it done in practice?</p> <p>The first thing to recognize is that the clickable area could be well outside the visible area of the object.</p> <h3>Regular links</h3> <p>For links in a list, the easiest way is to increase the padding. Instead of having a padding on the list-item you should have it on the link itself. In this example I simply add a 10 pixel padding to a link. Watch how that dramatically increases its clickable area (The faint red background indicates the clickable area).</p> <pre><code>li a { padding: 10px; } </code></pre> <p><img src="http://media.tumblr.com/tumblr_m1m4gwsku61qfjouz.png" alt=""/></p> <h3>Checkboxes and Radiobuttons</h3> <p>For checkboxes and radiobuttons, which often are really small, the trick is to put them inside a label and add a generous padding to them. By connecting the checkbox and the label via the <code>id</code> and the <code>for</code> attributes, the entire area of the label toggles the checkbox.</p> <h4>HTML</h4> <pre><code>&lt;label for="foo"&gt; &lt;input type="checkbox" name="foo" id="foo" value="bar" /&gt; A padded checkbox &lt;label&gt; </code></pre> <h4>CSS</h4> <pre><code>label { display: block padding: 10px; } </code></pre> <p><img src="http://media.tumblr.com/tumblr_m1m1t65p3B1qfjouz.png" alt=""/></p> <p>In this case the padded click area is over 50 times larger than the checkbox.</p> <p>Of course there are other elements that this could be applied to as well but these two examples should be enough to give you an idea of how to go about it.</p> <h2>References</h2> <h3>Online</h3> <p><a href="http://uxdesign.smashingmagazine.com/2012/02/21/finger-friendly-design-ideal-mobile-touchscreen-target-sizes/">Finger-Friendly Design: Ideal Mobile Touchscreen Target Sizes</a></p> <p><a href="http://www.lukew.com/ff/entry.asp?1085">Touch Target Sizes</a></p> <p><a href="http://www.smashingmagazine.com/2010/02/13/the-definitive-guide-to-styling-web-links/">The Definitive Guide To Styling Web Links</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 29 Mar 2012 02:03:00 -0400UsabilityHTMLCSSsvennerberg"It is far better to adapt the technology to the user than to force the user to adapt to the..."“It is far better to adapt the technology to the user than to force the user to adapt to the technology.”<br/><br/> - <em>Larry Marine</em>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Tue, 27 Mar 2012 06:49:22 -0400svennerbergWhat to do when all else fails?<p>So your brand new project is finally live. It&#8217;s looking great, your customer is happy and users are starting to pour in. Just when you&#8217;re about to start up the next project your customer calls you and says that something might be wrong, it&#8217;s no biggie but check when you can. You put it on your todo list and continue to work on the other project.</p> <p>When your about to go home the customer calls again. He is not as relaxed this time. The application is clearly not working as expected and he needs you to fix this asap. It looks like you don&#8217;t need to make plans for tomorrow.</p> <p>As you wake up the day after from your iPhone&#8217;s email notification alarms and constant vibrations, you remember, this will be a busy day.</p> <p>It can be hard to keep the cool as bug reports floods your inbox and the client calls every minute with weird questions and even more weird &#8220;solutions&#8221;.</p> <p>This is clearly an exaggeration but it can sometimes be very hard to spot and crush that bug, so where to start?</p> <p>My suggestion would be to start to look at external parts of your app, that could be cron jobs, services or anything else that isn&#8217;t trigged by a web request. I often find that these are the weakest link of the system. These things can easily hangup and even die.</p> <p>If you have a chained dependency, meaning one script must be done before the other should run. Then make sure that there is enough time for the first one to finish. Could it be that as the data grows the script takes longer time to finish? A better and more scalable solution would be that the first script calls the second one when it&#8217;s done.</p> <p>Make a dump of your production database and import the data on your local machine. Does it look right, is there a <code>null</code> value where you don&#8217;t expect it to be?</p> <p>The next step would be to debug your application. Logging is your best friend here. Try to set up some global error handling mechanism to log all exceptions that are thrown. Include all parameters sent to the app in the log message.</p> <p>Define a test case based on the parameters of the failing request and continuously hit the app with those parameters and try to recreate the issue. If you succeed you&#8217;re probably close to a solution.</p> <p>Take breaks! I know, there is nothing more frustrating than leave a problem unsolved but the fact is that your mind is constantly working on the issue even if your doing something else. I have sometimes solved nasty bugs within minutes after just ignoring the problem for awhile.</p> <p>Keep up the spirit and good hunting.</p> <p>Written by: <a rel="author" href="/ola-karlsson">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 22 Mar 2012 15:57:00 -0400tipsolkarlsMake Clickable Things Look Clickable<p>This is really a no-brainer but nevertheless important, and actually something a lot of sites get wrong.</p> <p>Imagine that you have an affiliate site for the travel industry. You write beautiful articles which vividly describes exotic places where people could spend their holidays. Sprinkled in the text you have affiliate links to traveling agencies, which in case you didn&#8217;t know, have pretty decent kick-backs on refered customers that leads to a sale.</p> <p>Now, the sole purpose of that article is to make people click those links. After all, that&#8217;s how you make money of the site. One thing you should definitely do is to make sure that people notices them. Because if the contrast between the links and the body text is to low, it doesn&#8217;t matter how eloquently you describe the destination. If they can&#8217;t see &#8216;em, they won&#8217;t click &#8216;em.</p> <p>This might sound like common sense but you would be surprised to know how many sites that get this wrong. Often I think, for aesthetic reasons.</p> <h2>What to do about it</h2> <p>You don&#8217;t have to take it as far as usability guru Jakob Nielsen who infamously claimed that links should be blue and underlined (which they are on his site useit.com by the way). I don&#8217;t want to take it that far but do make sure that your links stand out from the rest of the text.</p> <p>Your safest bet is probably to have them underlined. It carries a really strong affordance for clickability (check the Fast Facts Section for more on affordance). But you could also have them in a different color, a different background color and/or styled in some other way. Just make sure that they stand out from the rest of the text.</p> <p>Don&#8217;t forget that as much as 8% [kolla fakta] of all men are color blind so having something more than just the color to distinguish links is a good idea.</p> <h2>Not just text links</h2> <p>The same thinking goes for other things that are clickable such as buttons, checkboxes, select lists, images etc. etc. Make sure that they actually look clickable.</p> <p>For buttons that can mean to look like physical buttons with a 3d effect making them stand out from the page and look more like physical objects.</p> <p><img src="http://media.tumblr.com/tumblr_m0sn95rrf11qfjouz.png" alt="sasda"/></p> <p>The button on the left could just as well be a banner or a header, while the button on the right is begging to be clicked.</p> <h2>Provide clues</h2> <p>Also make sure to provide other clues such as the cursor changes to a pointing hand and that something happens with the object when it&#8217;s being hovered. This is easily achieved with the :hover pseudoclass in the CSS.</p> <pre><code>.clickable-item:hover { cursor: pointer; background-color: #ff9; } </code></pre> <h2>Don&#8217;t forget to design for touch</h2> <p>On touch devices there are no such things as a hover. It&#8217;s therfor extra important to make clickable objects look clickable.</p> <h2>Fast Facts</h2> <h3>Affordance</h3> <p>The term Affordance was popularized by Donald Norman in his seminal book <strong>The Psychology of Everyday Things</strong>. He later changed the term to <strong>Percieved Affordance</strong> since too many misunderstood what he meant by it. (Actually his latest term for this is <strong>Signifiers</strong> but that term hasn&#8217;t gained much traction yet)</p> <p>Percieved Affordance means what properties of an object we can learn by just looking at it. For example a door knob communicates with its shape that it can be grabbed and turned. In a similar way we can by just looking at a pair of scissors see that the shape of the two &#8220;holes&#8221; looks like somewhere you can put your thumb and your hand.</p> <p>The door knob affords grabbing and turning and the pair of scissors affords sticking your hands in the holes. In the same way a underlined link and a raised button affords clicking (or touching).</p> <h2>References</h2> <h3>Online</h3> <p><a href="http://www.useit.com/alertbox/20040510.html">Guidelines for Visulizing Links</a></p> <p><a href="http://www.jnd.org/dn.mss/affordances_and.html">Don Norman on Affordance</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 15 Mar 2012 11:08:00 -0400UsabilitysvennerbergWhy Still Sooo Slow? An Introduction to Database Indexes <p>So you&#8217;ve already implemented these <a href="https://codecraftingblueprints.com/post//speed-is-of-the-essence">frontend performance tricks</a>, right? I hope it made a huge difference, but what to do if your site still feels sluggish and slow? How about buying a new expensive dedicated server and add hardware every year or so? That might be necessary but there is a lot you can do on the data layer and this article will give you an introduction to database indexes.</p> <h2>What is a database index anyways?</h2> <p>Simply put it&#8217;s a table of contents just like the ones in books. It holds information about where the data is stored which helps the database to find it faster.</p> <p>Every time a row gets inserted, updated or deleted the index needs to be updated and this will slow down the write process. But at the same time increase the read speed.</p> <h2>Benchmark</h2> <p>I&#8217;ve created a database with a single table called <code>users</code> with the following fields:</p> <ul><li><code>first_name</code>, <code>varchar</code></li> <li><code>last_name</code>, <code>varchar</code></li> <li><code>email</code>, <code>varchar</code></li> <li><code>company_id</code>, <code>int</code></li> </ul><p>I then filled the table with 100000 rows and ran the following query 100 times:</p> <p><code>SELECT u.first_name, u.last_name, u.email FROM users u where company_id = 100094</code></p> <p><strong>4.299390</strong> seconds later the benchmark was done. Do you think an index will decrease the time spent running the test? Let&#8217;s try.</p> <p>I added an index to the <code>company_id</code> field and ran the same benchmark again and guess what, it only took <strong>0.010680</strong>. That&#8217;s an <strong>40256%</strong> speed increase, if my math is correct :).</p> <p>As you can see from this trivial example there is a lot you can do on the data layer to increase performance. There is of course more to cover on database indexes and here are some good resources:</p> <ul><li><a href="http://en.wikipedia.org/wiki/Database_index">Wikipedia</a></li> <li><a href="http://www.w3schools.com/sql/sql_create_index.asp">W3schools</a></li> </ul><p>If your interested in how to run similar tests then grab a copy of the <a href="https://gist.github.com/2003001">mysql benchmark script</a> and play around.</p> <p>Written by: <a href="/ola-karlsson" rel="author">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 08 Mar 2012 15:46:00 -0500performancedatabaseolkarlsThe Proper Way to Include CSS<p>You already know that the CSS should be separated from the HTML not to violate the separation of concerns. You probably also know that it should be inserted in the <code>&lt;head&gt;</code> part of the page. But what is the best way to include it? There is after all two ways of doing it.</p> <ul><li>Via <code>&lt;link&gt;</code></li> <li>Via <code>@import</code></li> </ul><p>At first glance it might seem that it wouldn&#8217;t matter, but as it turns out it does. In fact it does matter a lot!</p> <p>Using <code>@import</code> to include CSS can cause a blank white screen, just like if you would have inserted the CSS at the bottom of the page.</p> <p>It does this becuase CSS inserted via <code>@import</code> is always downloaded last. Since the browser won&#8217;t render anything until it loaded all the CSS, the page is completely blank until the CSS has finally downloaded.</p> <p>But why does the browser wait until all the CSS is loaded? Because it&#8217;s lazy! It doesn&#8217;t want to risk having to rerender the content, something it have to do if the CSS will alter the styling (which it probably will).</p> <h2>Actual Performance vs Percieved Performance</h2> <p>It&#8217;s important to understand that this behavior doesn&#8217;t affect the actual performance of the page. In fact in some cases the actual performance is faster. What it does affect is the <strong>percieved performance</strong>.</p> <p>With the CSS being loaded first, the browser will render the content of the page as it&#8217;s being downloaded. This is called <strong>Progressive rendering</strong> and it gives the user the impression that the page is loading faster.</p> <h2>The rule</h2> <p>What it boiles down to is this:</p> <p><strong>Always use <code>&lt;link&gt;</code> in the <code>&lt;head&gt;</code> of the document to include CSS.</strong></p> <pre><code>&lt;link type="text/css" rel="stylesheet" media="screen" href="style.css" /&gt; </code></pre> <h2>Related</h2> <p><a href="/post//css-in-the-head">CSS in the <code>&lt;head&gt;</code></a></p> <h2>References</h2> <h3>Books</h3> <p><a href="http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/">High Performance Web Sites - Essential Knowledge for Frontend Engineers</a> by Steve Souders</p> <h3>Online</h3> <p><a href="http://www.stevesouders.com/blog/2009/04/09/dont-use-import/">Don&#8217;t use @import</a></p> <h2>Bonus Fact</h2> <p>This best practice is taken from rule no 5 in Steve Souders excellent book <a href="http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/">High Performance Web Site</a>. This book contains 14 rules for faster-loading pages and is a must read if you&#8217;re serious about web site performance.</p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 01 Mar 2012 18:34:47 -0500CSSPerformancesvennerbergOpenSearch<p>Have you seen the little Google icon next to the search field in Safari and Firefox? With a few simple tricks you can have your own site listed as a dedicated search engine within these browsers. So let&#8217;s get to it.</p> <p>Create a new file named <code>opensearchdescription.xml</code> and put in the root of your website.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"&gt; &lt;ShortName&gt;Web Search&lt;/ShortName&gt; &lt;Description&gt;Use Example.com to search the Web.&lt;/Description&gt; &lt;Url type="text/html" method="get" template="/search?q={searchTerms}" /&gt; &lt;/OpenSearchDescription&gt; </code></pre> <p>The elements you&#8217;ll need to change is:</p> <ul><li>ShortName — Your sites name</li> <li>Description — A description of your search engine</li> <li>Url — The url of the search results page</li> </ul><p>And a link to the xml file inside the head tag of your webpage like this:</p> <pre><code>&lt;link rel="search" href="http://example.com/opensearchdescription.xml" type="application/opensearchdescription+xml" title="Content Search" /&gt; </code></pre> <p>Head over to your site using Safari or Firefox and click the little icon next to the search bar and see your site listed. Click add <code>yoursite.com</code> to use it as a search engine. Type in a search phrase and press enter. If you have added the right url inside the <code>Url</code> tag in the <code>opensearchdescription.xml</code> file then you should be taken to your sites search result page.</p> <p>The OpenSearch functionality is a bit different in Google Chrome since it has a combined search field and address bar. Start by typing <code>yoursite.com</code> and press tab. The bar changes and says &#8216;Search yoursite.com&#8217;. Fill in your search term and press enter.</p> <p>This is a very easy and useful way enhance your site. There are many more options to include to your <code>opensearchdescription.xml</code> file such as icons and tags. I highly encurage you to read the full specification over at the <a href="http://www.opensearch.org/Home">offical site</a>.</p> <p>Written by: <a rel="author" href="/ola-karlsson">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 23 Feb 2012 13:54:00 -0500powertipusabilityolkarlsPut scripts at the bottom<p>You’ve added your favorite JavaScript Libraries: jQuery, jQueryUI, a couple of plugins a few shims and on top of that your own js-files plus Google Analytic. When you load the page you&#8217;re surprised to see that it takes a while for something to render. In fact you realize that you&#8217;ve got the famous blank white screen.</p> <p>What&#8217;s going on here you say to yourself. Duh, you’ve put all the scripts in the <code>&lt;head&gt;</code> of the document. No wonder the page takes some time to load.</p> <p>But wait a minute! Isn’t the <code>&lt;head&gt;</code> Where you supposed to put the js? You know, so that all the scripts are available when the DOM has loaded. I’m sorry to break the news but <strong>the <code>&lt;head&gt;</code> is a horrible place to put scripts!</strong> Putting them there leads to two things:</p> <ul><li>Content below the script will not render until the scripts are downloaded and parsed.</li> <li>Assets like images, other script files and so on are blocked from being downloaded until the scripts are ready.</li> </ul><p>There&#8217;s a couple of reasons why this is happening.</p> <h2>Dependencies</h2> <p>The first reason is that the browser wants to make sure that a script added earlier in the document is loaded properly before adding the next in line because they can have dependencies. Just like your js code is probably dependent on a js library like jQuery.</p> <h2>Better safe than sorry</h2> <p>The second reason is that normally, the browser downloads files in parallell, meaning that 2 or more files download at the same time (even more if you spread out the files across CDN&#8217;s). But when a script file is downloaded this behavior is actually disabled, effectively blocking all other downloads until the script is done.</p> <p>But why, you might ask. What can possible happen? Well the browser lives by the motto: <strong>&#8220;Better safe than sorry!&#8221;</strong>. It can&#8217;t be sure that the script being downloaded won&#8217;t alter the content of the page with <code>document.write</code> (Something you should never do by the way). It wants to be absolutely sure that the page will render properly.</p> <h2>Put them at the bottom</h2> <p>The <code>&lt;head&gt;</code> is actually the worst place you can put your scripts. Putting them there will delay all the other content from being rendered.</p> <p>The best place is therefore to put your scripts at the bottom, just before the closing <code>&lt;body&gt;</code> tag. Doing this, the CSS and the HTML can be downloaded and rendered, giving the visitor something to look at before the script blocking begins (<a href="/post//css-in-the-head">Assuming that you&#8217;ve put your CSS at the top</a>).</p> <p>This also has the added benefit that you know that the DOM is ready when the scripts execute, removing the need to listen for a load event.</p> <p>So if you haven&#8217;t done so already, go ahead and move those <code>&lt;script&gt;</code> tags to the bottom of the page for an <strong>easy and instant performance boost of your site</strong>.</p> <h2>References</h2> <h3>Books</h3> <p><a href="http://www.amazon.com/High-Performance-Web-Sites-Essential/dp//">High Performance Web Sites - Essential Knowledge for Frontend Engineers</a> by Steve Souders</p> <p><a href="http://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/">High Performance JavaScript</a> by Nicholas C. Zakas</p> <h3>Online</h3> <p><a href="http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5/">High Performance Web Sites: Rule 6 – Move Scripts to the Bottom</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 16 Feb 2012 03:42:00 -0500JavaScriptPerformancesvennerbergSpeed is of the essence!<p>Every asset on a webpage needs to be downloaded by the browser and that takes time. The browser is also limited to between <strong>two</strong> and <strong>six</strong> concurrent transfers, depending on which browser is used. That means that if your web page has 18 assets (images, stylesheets or javascript files), the browser starts with the first two assets and enqueues the rest. When asset number one is downloaded it opens a new transfer and starts with asset number three and so on. This is usually where you should start to optimize a slow site.</p> <h2>Minimize the number of http requests</h2> <p>Combine all your css files into one css file and all the javascript files into one javascript file. There is a really good open source build script that&#8217;ll help you do that. Check out <a href="http://github.com/h5bp/ant-build-script">HTML5 boilerplate&#8217;s build script</a>.</p> <h2>CSS Sprites</h2> <p>If you are using alot of background images in your css files then you should combine all or most of them into a single file. Then use the css <code>background-position</code> to select the visible area of your image. There is not enough room to dive into css sprites in this article, but here is a <a href="http://css-tricks.com/css-sprites/">good one</a> that&#8217;ll help you get started.</p> <h2>Use a far cache expiring date</h2> <p>Another good way to minimize request is the tell the browser that the downloaded file won&#8217;t change for a very long time. This means that after the download is complete the file is always served from the local cache.</p> <p>Setting up expiring dates is often done in your virtual host configuration and you may have to install some software depending on which web server you are using.</p> <p>This is an example for Apache which has <code>mod_expires</code> enabled:</p> <pre><code>&lt;FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$"&gt; ExpiresActive On ExpiresDefault "access plus 1 year" &lt;/FilesMatch&gt; </code></pre> <p>All the files with the extension listed in the <code>FileMatch</code> expression will be cached one year from when the request is made.</p> <p>This is the perfect solution as long as you never update any of these files again, but that might not be the case.</p> <h3>Expire the cache</h3> <p>The easiest way to expire the cache is to append a version number to all your static assets, like this: <code>body-bg-v2.png</code>. If need to update that file you&#8217;ll need to change it&#8217;s name to <code>body-bg-v3.png</code>. That can be a real pain since you&#8217;ll need to rename all your files which have changed, including the background images within your css files. Good thing you&#8217;re using css sprites, right?</p> <p>As you can see, there is some hassle to set all of this up but it&#8217;s really worth it. The user will have a much better experience while visiting your site.</p> <p>Written by: <a rel="author" href="/ola-karlsson">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 09 Feb 2012 12:24:00 -0500PerformanceUsabilityolkarlsKnow Your Doctype<p>The doctype is the piece of code that should sit at the top of all other markup in an HTML-document. It doesn&#8217;t do a whole lot, but it does one important thing. It tells the browser which flavor of HTML you&#8217;ve choosen to use on your web page.</p> <p>The doctype might look something like this&#8230;</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; </code></pre> <p>&#8230;at least if XHTML 1.0 is your kind of flavor.</p> <p>Then why is it important to tell the browser what kind of markup to expect? Isn&#8217;t HTML just HTML?</p> <p>As it turns out it&#8217;s very important to tell the browser which type of HTML to use or <strong>you might suffer from slower rendering and unexpected interpretation of your markup</strong>.</p> <h2>Quirky browsers</h2> <p>Traditionally browser have had to be very forgiving when parsing HTML. They&#8217;ve had to because back in the day, nobody knew what good HTML looked like, not even the browser manufactures who instead competed over who could come up with the craziest HTML tag. Remember the <code>&lt;blink&gt;</code> and the <code>&lt;marqee&gt;</code> tag?</p> <p>It was regular wild west and people tossed together HTML tags with no regards to semantic meaning or concerns about if it was valid or not.</p> <p>Even if the HTML was sloppy and contained errors, the browser would still do its best to render the page according to it. To do that it actually switches to a different mode, <strong>Quirks Mode</strong>, sometimes referred to as <strong>Compability Mode</strong>. In Quirks Mode the browser is much more forgiving and tries hard to render badly formatted HTML. The problem is that this takes a lot more CPU than rendering valid HTML, and the results are pretty unpredictable.</p> <h2>Avoid this by Stating the Doctype</h2> <p>Of course today it&#8217;s a whole different story. There are now best practices and defined standards on how to use HTML and even most browser manufactures does its best to implement the standards properly.</p> <p>But it&#8217;s important to declare the proper doctype. If you omit it, the browser will automatically switch to Quirks Mode since it will assume that you don&#8217;t know what you&#8217;re doing. The result is that the page will take longer to parse and the HTML can be interpreted in unexpected ways. It will for example use Microsofts faulty box-model in IE6, which will probably mess upp your entire layout. (For a long list of examples check out the article <a href="http://www.cs.tut.fi/~jkorpela/quirks-mode.html">What happens in Quirks Mode</a>.)</p> <h2>What Doctype to Choose</h2> <p>It&#8217;s not that important which doctype you actually use. The most important thing is that you make a conscious decision about this and that you use a valid doctype.</p> <p>Personally I wouldn&#8217;t go with anything else than HTML5 these days, and that has its advantages. It&#8217;s the only doctype that I can actually write from memory.</p> <pre><code>&lt;!doctype html&gt; </code></pre> <h2>Further reading</h2> <p><a href="http://www.w3.org/QA/2002/04/valid-dtd-list.html">A list of doctypes from W3C</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 02 Feb 2012 07:59:00 -0500HMTLsvennerberg"Good design is all about making other designers feel like idiots because that idea wasn’t theirs"“Good design is all about making other designers feel like idiots because that idea wasn’t theirs”<br/><br/> - <em>Frank Chimero</em>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Wed, 01 Feb 2012 12:38:00 -0500olkarls.htaccess Tricks<p>This article will show you my most common <code>.htaccess</code> tricks. A <code>.htaccess</code> is a file that is placed in the root of your website and allows to override the Apache configuration.</p> <h2>No duplicated content</h2> <p>You should make your site respond to both <code>yoursite.com</code> and <code><span>www.</span>yoursite.com</code> because some people still writes those wwws into the browser. This leaves one problem though. All the content is duplicated, meaning your sites content is competing with it self.</p> <p>In the time of sharing craziness where everybody hunts retweets, likes and links, the problem becomes more obvious.</p> <p>If ten people links to: <code><span>yoursite</span>.com/really-great-article/</code> and another five links to <code><span>www.</span>yoursite.com/really-great-article/</code> then Google will rank those two urls individually. Since most search engines consider links to be the best ranking factor you need to get all the links you can and be sure that they are pointing to the correct location.</p> <h2>.htaccess to the rescue</h2> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^YOURSITE\.COM$ [NC] RewriteRule ^(.*)$ <span>http://</span>YOURSITE.COM/$1 [R=301,L] </code></pre> <p>That <code>.htaccess</code> rule will permanently redirect everything that doesn’t begin with <code>YOURSITE.COM</code> to <code>YOURSITE.COM</code>. So if I linked to <code><span>www.</span>yoursite.com/really-great-article/</code> the visitor and the search engines who follows that link will end up on <code><span>yoursite</span>.com/really-great-article/</code> instead.</p> <p>Google follow these redirects and understand that the url has moved to the other location.</p> <p>So go ahead and add that rule to every site you own now.</p> <h2>Static site fixes</h2> <p>The following examples is a little more specific. I mostly use Ruby on Rails when I’m lashing out web apps but sometimes I use <a href="http://github.com/blahed/frank">Frank</a>. That’s an excellent Ruby framework for generating static html sites. Then the following examples comes in handy.</p> <p>What if the actual url in the example above is <code>yoursite.com/really-great-article/index.html</code>. Then you need to remove the filename. Fortunatly that’s easy:</p> <pre><code>RewriteCond %{THE_REQUEST} /index\.(html|php) [NC] RewriteRule ^(.*/)?index\.(html|php)$ /$1 [R=301,L] </code></pre> <p>Every url containing either <code>index.html</code> or <code>index.php</code> will be redirected to the folder it’s contained within. If you’re using other extensions then that just add them between the paranteses.</p> <h2>FourOohFour</h2> <p>If the document can’t be found Apache shows a generic default page that is pretty cruel to you grafical profile and it wont show your navigation, so the user is stuck. It’s also important to understand where your visitors are coming from and you should add a tracking code everywhere, even to your 404 pages.</p> <p>Just create a file called 404.html in the root of you website and add the following rule to the .htaccess file.</p> <pre><code>ErrorDocument 404 /404.html </code></pre> <p>This is just a small introduction and I’ve only just scratched the surface. If you thirst after more <code>.htacess</code> tricks point your browser to the <a href="http://httpd.apache.org/docs/current/howto/htaccess.html">offical site</a> to learn more.</p> <p>Written by: <a rel="author" href="/ola-karlsson">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 26 Jan 2012 10:37:00 -0500SEOUsabilityolkarlsCSS in the Head<p>When optimizing a page you&#8217;re obviously thinking about where to add different assets on it. Stuff that is needed up front is placed at the top and stuff that is needed later can be placed further down. After all, we want the page to show something as fast as possible!</p> <p>The percieved performance in this case is the most important factor. We therefore want the page to load progressively, meaning: The page renders from top to bottom as content is being downloaded.</p> <p>Lets say you&#8217;re building an image gallery to show off your fabolous collection of Ninja Toasters(!?). When the user clicks a toaster a lightbox will open and display a bigger image of the toaster.</p> <p>Now, the CSS for the lightbox isn&#8217;t needed for rendering the page. It&#8217;s actually not needed until the user clicks an image. Therefore we could include it at the bottom of the page to let other content load first right. You know so that the page will render faster? Wrong! Contrary to common sense it will actually delay the rendering of the page in a lot of web browsers.</p> <p>But why does it delay the rendering? Keeping the browser from downloading it before other content ought to make the rendering faster. This is really counter intuitive at first glance, but listen to this:</p> <p><em>The browser doesn&#8217;t want to risk having to re-render the page, it therefore waits until all CSS is loaded before rendering anything!</em></p> <p>Fortunally there&#8217;s a really simple solution to this, just follow this simple rule: <strong>Include all CSS in the &lt;head&gt; of the page</strong>.</p> <h2>References</h2> <h3>Books</h3> <p><a href="http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/">High Performance Web Sites - Essential Knowledge for Frontend Engineers by Steve Souders</a></p> <h3>Online</h3> <p><a href="http://developer.yahoo.com/performance/rules.html#css_top">Best Practices for Speeding Up Your Web Site</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 19 Jan 2012 09:27:22 -0500CSSPerformancesvennerberg"Learn the rules so you know how to break them properly."“Learn the rules so you know how to break them properly.”<br/><br/> - <em>Dalai Lama</em>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Fri, 13 Jan 2012 03:05:04 -0500svennerbergNever Allow Access to Destructive Actions Through a GET Request<p>You&#8217;ve worked hard for a long time but finally your web application is ready and you&#8217;re eager to roll it out. Your site has an administration area where you can handle all the data your site contains.</p> <p>The user section of the administraion area contains links like this: <code>&lt;a href="http://yoursite.com/delete_user?id=123"&gt;Delete user&lt;/a&gt;</code>.</p> <p>If an authenticated administrator would click that link it would delete the user with id 123. This is fine right? We know that the user is logged in and the only way to access the link is through the administration section of the application. <strong>Wrong!</strong> This is a very insecure way to handle destructive actions.</p> <p>There&#8217;s a lot of people out there with the sole purpose to hack or destroy your site and you should never leave anything to the slump.</p> <p>What if I&#8217;m an evil hacker and I send an email to someone who handles your sites administration containing this code <code>&lt;a href="http://yoursite.com/delete_user?id=123"&gt;Checkout this really funny clip&lt;/a&gt;</code>. Ok, I know, you need to trust people not to click everything clickable right?</p> <p>Well, then consider this:</p> <p>I post on a forum where I know the adminstator hangs out, containing this image tag <code>&lt;img src="http://yoursite.com/delete_user?id=123" alt="The Cutest Kitten in the Universe" /&gt;</code>. The second the administrator opens that url; the user is gone.</p> <p>Urls are also easy to mask, either via a redirect rule in a .htaccess file or simply by creating a server side script. Then it&#8217;s impossible to see where the link goes while hovering it.</p> <p>The point I&#8217;m trying to make is that a GET request doesn&#8217;t care which element it&#8217;s included in. If a requests is sent the request is sent.</p> <h2>So, How to solve this mess?</h2> <p>Never allow any GET request to handle data modifications. It really is that simple. You should also demand some sort of confirmation before deleting stuff because everybody can make a mistake right?</p> <p>According to the specifications GET should be used for retrieve information.</p> <blockquote> <p>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.</p> <p>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI.</p> </blockquote> <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">RFC2616 (HTTP 1.1) reference</a></p> <p>Written by: <a rel="author" href="/ola-karlsson">Ola Karlsson</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 12 Jan 2012 15:30:00 -0500SecurityolkarlsSeparation of Concerns<p>Have you ever found yourself in a situation where you have a site where the HTML, the CSS and the JavaScript are all tangled together and it becomes a nightmare to make even the tiniest site-wide change?</p> <p>What you&#8217;ve experienced is what is commonly referred to as <strong>Spaghetti code</strong>. To avoid falling into this trap you should follow one simple rule:</p> <p><strong>Always separate HTML, CSS and JavaScript into different files.</strong></p> <p>Remember that <strong>HTML is for content</strong> (and structure), <strong>CSS is for design</strong> and <strong>JavaScript is for behavior</strong>. By separating them into different layers you gain several things. It becomes:</p> <ul><li>Easier to maintain</li> <li>Increased performance</li> <li>Better accessibility</li> <li>A good foundation for SEO</li> </ul><h3>Maintainability</h3> <p>First of all, your code becomes more maintainable. If there&#8217;s something wrong with the design, it&#8217;s probably in the CSS. If on the hand your super cool drag and drop interface stops working, something is probably wrong in the JavaScript files. In other words, it&#8217;s easier to find errors.</p> <p>Imagine wanting to change the entire design of your site to a ninja unicorn theme (shudder). Having your HTML, CSS and JavaScript in a big mess you basically need to rewrite the whole site. But if you been a good coder and kept them separated, all you need to do is to change the CSS. Simple, right?</p> <h3>Performance</h3> <p>In most cases the site loads faster if you have the layers separated. And we all know how important speed is!</p> <p>JavaScript and CSS files are static assets that can be effectively cached by the browser. What it means is that the browser doesn&#8217;t have to download them more than once. You save both bandwidth and rendering time.</p> <h3>Accessibility</h3> <p>By separating the different layers you also benefit the accessibility of the site. It&#8217;s in fact the foundation of <em>Progressive Enhancement</em> (and graceful degradation). This means that even if the user interact with your site using a less capable device (for example: disabled JavaScript, screen reader, old browser, you name it) it can still access the content because the device can simply ignore the parts it doesn&#8217;t support and render what it can.</p> <p>HTML is the solid foundation of the web. By making sure that you keep the content there (semantically marked up of course) and that neither the CSS, nor the JavaScript is in its way, you can be sure that every browser on this planet can access your content.</p> <h3>SEO</h3> <p><em>Web crawlers</em>, the evil robots of Search Engines that constantly crawles the web on their endless hunt for content to index, is another reason you want to separate the layers. A web crawler is basically a blind user. It doesn&#8217;t care about your fancy styles or your crazy JavaScript animations. All it cares about is your content - your HTML.</p> <p>So you better make sure that your content is semantically marked up with valid HTML and that the CSS and JavaScript is out of its way. Having done this, you&#8217;re on your merry way towards SEO nirvana.</p> <h2>A Bad Example (Warning Anti Pattern!)</h2> <p>In this example, the separation of concerns is violated. Both content, style and behavior are meshed together in an awful soup.</p> <h3>HTML</h3> <pre><code>&lt;a href="/some/url/" onclick="someFunction(); return false;" style="font-size: 12px; color: #f00;"&gt;A bad link&lt;/a&gt; </code></pre> <h2>Good Example</h2> <p>In this good example the same thing is done with a clear separation between content, style and behavior.</p> <h3>HTML</h3> <pre><code>&lt;a href="/some/url/" id="some_link"&gt;A good link&lt;/a&gt; </code></pre> <h3>CSS</h3> <pre><code>#some_link { font-size: 12px; color: #f00; } </code></pre> <h3>JavaScript</h3> <pre><code>document.getElementById('some_link').addEventListener('click', someFunction, false); </code></pre> <h2>Conclusion</h2> <p>I hope that this article have convinced you that keeping a clear separation is the way to go. So save yourself a lot of grief and separate these three levels as much as possible or you might as well end up in <strong>Spagetti Code Hell</strong>.</p> <h2>References</h2> <h3>Online</h3> <p><a href="http://dev.opera.com/articles/view/4-the-web-standards-model-html-css-a/">The Web Standards model - HTML, CSS and JavaScript</a></p> <p><a href="http://en.wikipedia.org/wiki/Separation_of_concerns">Separation of concerns on Wikipedia</a></p> <h3>Books</h3> <p><a href="http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/">DOM Scripting by Jeremy Keith, FriendsofEd 2005</a></p> <p><a href="http://www.amazon.com/Bulletproof-Web-Design-flexibility-protecting/dp/">Bulletproof Web Design by Dan Cederholm, New Riders 2006</a></p> <h2>Bonus Fact</h2> <p>The concept of Separation of Concerns is not limited to HTML, CSS and JavaScript. It applies just as much to general software development where you want to keep different things separated. For example the data, the business logic and the User Interface.</p> <p><a href="http://en.wikipedia.org/wiki/Separation_of_concerns">Separation of concerns on Wikipedia</a></p> <p>Written by: <a href="/gabriel-svennerberg">Gabriel Svennerberg</a></p>https://codecraftingblueprints.com/post/https://codecraftingblueprints.com/post/Thu, 12 Jan 2012 14:31:00 -0500CSSHTMLJavaScriptsvennerberg