Sublime Text and SublimeLinter

Sublime TextThis is a quick update about a text editor called Sublime Text and a plugin called SublimeLinter that lets you turn on linting and highlighting for over 15 different languages.

I had been going back and forth between Notepad (really), Notepad++ and Adobe Dreamweaver for coding and website development. I couldn’t stick with one editor because I wasn’t satisfied with ANY of them. Notepad is way too basic. Notepad++ is not bad but there is something about it that rubs me the wrong way. I think it’s actually more complex than I need it to be and I’ll probably never use half the functions it has. It’s pretty much the same thing with Dreamweaver, but lately I had been using it as my main editor just because I really like how it lets me organize projects instead of dealing with files individually.

Then I heard about Sublime Text and decided to try it out. First, let me just say that it is not free, but what you get from it is priceless in my opinion. My first impression was that it looked very nice, seemed user-friendly and made me feel like it did everything I needed it to do without overwhelming me with extra crap. When I found out that it had a sidebar where I could organize different projects I was sold. I started gradually finding out about other very useful features that none of the other editors I mentioned have. For example, split editing lets you edit multiple files side by side. I like to have my HTML file on the left column and my CSS file on the right column. I don’t know how I ever lived without that. Of course it has tabs as well; this is 2013 after all. It also lets you make multiple selections and edits simultaneously. And a bunch of other stuff guaranteed to increase productivity. Hey I’m not getting paid to write this so I’ll stop here! If you want to find out about all the features it has to offer, just check out their website: www.sublimetext.com

SublimeLinter

One thing that I noticed after installing Sublime Text was that the text in my SASS/SCSS files were not being color-coded. I had experienced the same thing with Notepad++ and DreamWeaver. Actually most text editors don’t support color-coding these file types out of the box. It’s usually necessary to download and install some kind of plugin to get this functionality, so I set out trying to find one for Sublime Text. It was then that I came across SublimeLinter. Coupled with node.js (more on that later) it turned out to provide yet another functionality  that I don’t know how I ever lived without: examining Javascript for syntactic discrepancies. It basically checks if the code you’ve written is valid and suggests fixes if it’s not. As I understand it, this is the main functionality of linters. In fact, although a vanilla install of SublimeLinter will provide a lot of capabilities that Sublime Text doesn’t provide out of the box, node.js is also required for color-coding SASS/SCSS files!

Sublime Text

Features of Sublime Text

This is the description of SublimeLinter found on their GitHub page:

SublimeLinter is a plugin that supports “lint” programs (known as “linters”). SublimeLinter highlights lines of code the linter deems to contain (potential) errors. It also supports highlighting special annotations (for example: TODO) so that they can be quickly located.

SublimeLinter has built in linters for the following languages:

  • C/C++ – lint via cppcheck
  • CoffeeScript – lint via coffee -s -l
  • CSS – lint via built-in csslint
  • Git Commit Messages – lint via built-in module based on A Note About Git Commit Messages.
  • Haml – syntax check via haml -c
  • HTML – lint via tidy (actually tidy for HTML5)
  • Java – lint via javac -Xlint
  • JavaScript – lint via built in jshintjslint, or the closure linter (gjslint) (if installed)
  • Lua – syntax check via luac
  • Objective-J – lint via built-in capp_lint
  • Perl – lint via Perl::Critic or syntax+deprecation check via perl -c
  • PHP – syntax check via php -l
  • Puppet – syntax check via puppet parser validate
  • Python – native, moderately-complete lint
  • Ruby – syntax check via ruby -wc
  • XML – lint via xmllint

Installation

The easiest way to install SublimeLinter is through Package Control:

  • Follow the instructions on this page and then restart Sublime Text.
  • From the menu bar choose Preferences -> Package Control.
  • Choose “Install Package” from the list that pops up.
  • Type SublimeLinter into the text box and it will install automatically.

SublimeLinter should technically be up and running now, but we’re not done yet. SublimeLinter is still not checking our Javascript for syntactic discrepancies and even our SASS/SCSS is not being color-coded. I recommend checking out the README from within Preferences -> Packages Settings -> SublimeLinter. The following section on Javascript-based linters is of special importance:

If you plan to edit files that use a JavaScript-based linter (JavaScript, CSS), your system
must have a JavaScript engine installed. Mac OS X comes with a preinstalled JavaScript engine called
JavaScriptCore, which is used if Node.js is not installed. On Windows, you **must** install the
JavaScript engine Node.js, which can be downloaded from [the Node.js site](http://nodejs.org/#download).

On Mac OS X, you **must** install Node.js if you plan to edit JavaScript or CSS files that
use non-ASCII characters in strings or comments, because JavaScriptCore is not Unicode-aware.

After installing Node.js, if the Node.js executable (“node” on Mac OS X, “node.exe” on Windows)
cannot be found by SublimeLinter, you may have to set the path to the executable in the
“sublimelinter_executable_map” setting. See the “Configuring” section below for info on
SublimeLinter settings.

node.js

After following these final instructions you should now be getting the full functionality out of Sublime Text and SublimeLinter. Nowadays I personally experience not only increased productivity and less frustration, but also more joy in working on my projects. It’s almost sublime!

FREEBIE FRIDAY! Resize images dynamically and proportionally with Javascript.

What is it and how does it work?

Here is a script I’ve created to resize images according to viewport height. It has been tested in Internet Explorer 10, Firefox 24.0, Chrome 30, Opera 12.16 and Safari 5.1.7. I’m making it available for free use, private or otherwise. Just download it from the link at the bottom of this post.

I originally created this to ensure that my layout would adapt itself to different screen resolutions. For example, I wanted an image that takes up 50% of the screen’s height on a 2560×1440 resolution to still take up 50% of the screen’s height on a 1280×720 resolution. Without this script the image would take up 100% of the screen’s height when the page is viewed on a display with 1280×720 resolution.

Eventually I realized that the script would be more effective if it resized images based not on screen resolution, but on viewport height. So I re-designed it to take into account OS and browser bars at the top and bottom of the screen — e.g. Windows taskbar, Mac dock/menu bars, browser toolbars and status bars. The result is that images will be shrunken accordingly when those are present. Bars at the left and right edges of the screen/browser are not taken into account, just as resizing the browser window horizontally does not affect image size: this script is only designed to resize images according to the viewport height.

Having the script do its thing based on viewport size rather than resolution also opened up another possibility: real-time adaptation upon browser resize. This is true fluid design. A script based solely on screen resolution will run on page load and stop there, but one based on browser window/viewport can be fluid since the window/viewport can always be resized, at least on a regular desktop or laptop computer.

How to implement it

Creating the images

Images should be designed on a canvas with the same dimensions as your chosen maximum resolution. This will ensure that they will scale down proportionally to take up the same percentage of a browser’s viewport as it does on the canvas. For example, if we wanted to design a webpage for a maximum resolution of 2560×1440 we should create our images on a canvas of those exact dimensions (e.g. create a new Photoshop file that is 2560×1440). And if we wanted a particular image to always take up 20% of the viewport’s height we should make it take up 20% of the canvas’s height (288px in this case).

Customizing the script

After deciding on a maximum resolution for your layout, the script is ready to be customized. Upon opening imgResize.js take a look at lines 4 and 5. It’s pretty self-explanatory: on line 4 the names of the image files to be resized can be entered and on line 5 the maximum resolution for which they were designed. It may sound counter-intuitive but you can actually increase these values down the line if you change your mind and decide that the images are too large. However, don’t decrease the values or the image will be displayed larger than their native sizes at the original maximum resolution — in other words, there will be a loss of quality.

Last steps

In your HTML markup add an id to each image that will be resized. It should look something like this:

<img src=”image1.jpg” id=”image1“>

Notice that the id name is the same as the image name, minus the extension. This is very important, otherwise the code will not work.

Finally add the following lines in your CSS styling:

#image1, #image2, #image3 {
    display: none;
}

Of course this is just an example; #image1, #image2, and #image3 could well have different names. The important thing is that they reference the images to be resized. What this step does is hide the images until the resizing script has run. This prevents them from “flashing” in their native dimensions before being resized. It’s not crucial to the functionality of the script but it adds a professional touch to the whole thing.

Inserting the script on your webpage

We want the script to execute automatically on page load so the user is immediately presented with a page tailor-made for the current size of his or her browser. We also want it to execute on page resize for real-time adaptation upon browser resize. To achieve these objectives we will be calling the script using the following code:

window.onload = function() {
    imgResize();
};

window.onresize = function() {
    imgResize();
};

We can place the above in the file containing the HTML (enclosed by <script> tags) or in its own .js file. Just make sure this code comes after the imgResize.js script itself — we can only instruct it to call something it already knows about! It’s also important to note that imgResize.js should come after any CSS styling.

Implementing it, summarized

  • Create images in a canvas of the same size as the maximum resolution for which the webpage will be optimized.
  • Edit lines 4 and 5 of imgResize.js – image file names and maximum resolution.
  • In the HTML markup add an id to every image that will be resized. Each id should have the same name as the image file it represents.
  • Style each id with display: none; in your CSS styling.
  • Use the following order inside the HEAD tags in your HTML markup:
    1. CSS styling
    2. imgResize.js
    3. window.onload = function() {    
          imgResize();
      };
      window.onresize = function() {    
          imgResize();
      };

Download

https://www.dropbox.com/s/h08851b0yb586ou/imgResize.zip

Internet Explorer Conditional Comments

Internet Explorer: the bane of any web developer trying to make their pages cross-browser compatible. Sure it has improved a lot with the last couple of versions, but because it has always been such a popular browser its older versions are still in use by an arguably large percentage of the public. Not long ago I was at the library only to find that their computers are still equipped with IE6! The problem of course is that these old versions don’t seem to follow any logic other than their own in interpreting HTML and CSS. How many times have you worked hard on a webpage when, after hours of toiling away at it, you decide to check it on an old version of IE only to find that it doesn’t know how to interpret what you’ve created at all and your masterpiece is displayed as something else entirely — something that probably doesn’t make any sense!? Worse yet, each version of IE will display a unique kind of mess.

The importance of cross-browser compatibility

Trying to write HTML and CSS in such a way that every browser will interpret it in the same way can be very difficult, possibly impossible and most likely very time consuming. This is the reason a lot of web developers throw in the towel and decide to ignore outdated browsers. I do agree that the web needs to move on and the less lip service we pay to outdated browsers the faster we will achieve that goal — but we don’t always have that choice. Sometimes clients demand that their websites be compatible with old browsers. Other times we can check statistics and see that the percentage of users accessing a website with outdated browsers really is significant — of course that percentage varies with each website and the type of audience that has an interest in it.

How IE conditional comments work

So it seems the problem is writing one absolute piece of code that is interpreted equally by every web browser, or at least every modern browser and Internet Explorer versions going back to 6 (everything else is probably negligible despite the site’s audience and this might need to be explained to certain clients). Then let’s eliminate the problem: we will not write an absolute piece of code for every browser; we will write code that is conditional. Since we are not worried about the outdated versions of any browsers besides IE6 these “conditional comments” will specifically target IE and will be ignored by any other browsers. It sounds almost like we will be programming using if-else statements. In principle that’s how conditional comments work, but in practice it just involves writing a couple extra lines of HTML, no programming knowledge required. These comments are only read by IE browsers. It’s as if its developers unleashed an unspeakable evil upon us and then felt guilty and decided to throw us a bone.

Writing conditional comments

Conditional comments can be used either within the head of your page (to present different stylesheets depending on the browser, for example) or directly in the body. They look like this:

<!--[if IE]>
According to the conditional comment this is IE.
<![endif]-->

Simple, isn’t it?  If the website is being accessed through IE (any version in this case) the text between the opening and closing comments will be displayed; otherwise it will be completely ignored.

If we wanted to target a specific version of IE, this is how it would look:

<!--[if IE 6]>
According to the conditional comment this is IE6.
<![endif]-->

<!--[if IE 7]>
According to the conditional comment this is IE7.
<![endif]-->

<!--[if IE 8]>
According to the conditional comment this is IE8.
<![endif]-->

<!--[if IE 9]>
According to the conditional comment this is IE9.
<![endif]-->

As of this writing we have conditional comments up to IE9 available to us. It’s just as well since IE10 seems to have finally caught up with the times.

“What if I want to target all IE versions under or above a specific one?” I’m glad you asked. In this case we would use lt (lower than), lte (lower than or equal), gt (greater than) or gte (greater than or equal) in our syntax. Like so:

<!--[if lte IE 9]>
According to the conditional comment this is all versions of IE up to and including version 9.
<![endif]-->

Finally it is also possible to target every browser except IE. There are two ways to do achieve this:

<![if !IE]>
According to the conditional comment this is not IE.
<![endif]>

<!--[if !IE]><!-->
According to the conditional comment this is not IE.
<!--<![endif]-->

Note that the first way required that we remove the dashes from the conditional comments! The second way looks more complicated but if you write your code in a program with color coding, or which in some way modifies your text to make it easier to visualize its different parts (comments in this case) the second method might be preferrable. Try it out and see which works better for you. The output to the browser will be exactly the same.

Similarly we have the option of target every browser except a certain version of IE. Once more, we have two ways of doing this, as shown below:

<![if !IE 6]>
According to the conditional comment this is not IE6.
<![endif]>

<!--[if !IE 6]><!-->
According to the conditional comment this is not IE6.
<!--<![endif]-->

Again, notice the missing dashes in the first method!

Finally, there might be times when we need to target more than one browser without using greater/less than [or equal]. For this we can use operators! Available in our arsenal are the subexpression operator (), the OR operator (|) and the AND operator (&). Here’s an example using OR:

<!--[if (IE 6)|(IE 7)]>
According to the conditional comment this is IE6 or IE7.
<![endif]-->

As with the other “not IE” conditional comments we have a choice of two different syntaxes when using “not IE” with operators. This is how they look:

<![if (!IE)|(gt IE 7)]>
According to the conditional comment this is either not IE or it is IE8+.
<![endif]>

<!--[if (!IE)|(gt IE 7)]><!-->
According to the conditional comment this is either not IE or it is IE8+.
<!--<![endif]-->

More tools that help development for different browsers/versions of IE

IE7.js is “a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. It fixes many HTML and CSS issues and makes transparent PNG work correctly under IE5 and IE6.”

Also check out my article about testing on different browsers and browser versions using VirtualBox and go make your pages cross-browser compatible!

Test on different browser versions with VirtualBox

As web developers it is imperative to be constantly checking the websites we are working on in different browsers since they each have their specific ways of interpreting the code we write. The point is to make sure that our sites are presentable for as many different users as possible. There are other factors to consider like operating system and screen resolution, but in this article I want to concentrate on browsers, specifically their different versions and how we can get them to co-exist in the same machine — something that a browser like Internet Explorer doesn’t normally allow.  One way of doing this is by setting up virtual machines. In this article you will learn how to do that using VirtualBox, an incredibly powerful program that is free and will, for our purposes, grant us separate environments in which to install several versions of each browser.

A consistently usable and attractive browsing experience

Although it is a good start to check our websites in different browsers as we are coding them it is perhaps even more important to check them on different versions of those browsers: we can usually count on all of the latest versions supporting — to varying degrees — new technologies like HTML5 and CSS3, but at the same time we can always count on a significant number of users not having the latest versions of those browsers installed. That means they may miss out on those features specific to HTML5 and CSS3. It is generally agreed upon that it is bad practice to tell users to upgrade their browsers. Much better and more effective is to make sure that our code smoothly “downgrades” in those situations, presenting those users with an experience that is still relatively attractive and completely usable.

browsers

As I’ve mentioned the dilemma is that certain developers do not actually allow us to install several versions of their browsers. This is notoriously true for Internet Explorer. I also experienced it with Firefox, but apparently there is a very simple way around this. I have not tried it with other browsers, but considering that Internet Explorer is one of the most used browsers out there, it is critical to test on its older versions as well. This is particularly true since this specific browser comes pre-installed with Windows and less tech-savvy people may never upgrade it.

How does VirtualBox work?

vbox_logoHaving access to several computers in which to install the different versions of our browsers might technically seem like the perfect solution — if it weren’t severely impractical assuming that we even had access to several physical machines and were allowed to overwrite their browser installations.

Enter VirtualBox: a “virtualizer” that allows us to install several virtual machines (in essence operating systems) in just one physical machine. VirtualBox is free, user-friendly, chock-full of features and in contrast to some other virtualizers/emulators it is FAST! Plus it supports shared folders and virtual USB controllers in addition to the usual floppy and CDROM drive support.

The list of operating systems to choose from is huge; in fact I can’t think of any OS that is missing. But it is not a completely free ride for pirates: you do need to have the installation disk for your desired OS. The installation will be done as if on a physical machine.

Installing and using VirtualBox

To begin, grab a copy of VirtualBox here. After you’ve installed it, setting up different virtual machines is pretty straight-forward: just click on “New” and follow the wizard. Once you’re up and running with an OS installed in your virtual machine, there are several things you can do to make your VirtualBox experience even easier:

  • Clone your virtual machines. This is the first thing you should do after installing an OS in your virtual machine. It means that you will have a fresh copy of the installation ready for your next project or in case you mess something up. Always have a fresh copy available to avoid having to install the OS again. You can clone a virtual machine simply by right-clicking it in the VirtualBox Manager and choosing “Clone…”
  • Set up shared folders. This is very important if you’re planning to use your virtual machines to check your websites on different browsers.1 Failing to set up virtual folders means that you will have to constantly be copying updated files of your website to each individual virtual machine — killing your time, creativity, and sanity! It couldn’t be much easier to share folders between your host and your virtual “guest” OS:
    1. First you will need to install “Guest Additions.” From your virtual machine’s window, go to “Devices -> Install Guest Additions…” and follow the wizard. You only need to do this once in VirtualBox; shared folders will then work for all of your virtual machines.
    2. Now you are ready to set up shared folders. Go to “Devices -> Shared Folders…” and add the folders you would like access to by clicking on the little folder with a plus sign. Make sure to check “Make Permanent” for each folder you add, otherwise they will not be available when you restart the virtual machine.
    3. The folders you’ve shared from your host machine should now be available in your virtual machine. If it is running Windows you can access them by going to Start -> Run…, typing “explorer” and hitting enter.  On the window that pops up click the + arrow next to “My Network Places,” then the + arrow next to “Entire Network.” Finally click the + arrow next to “VirtualBox Shared Folders” and select the folder that is revealed. Note the address of that folder. An alternative to these steps is to simply type in that address. It may vary in different versions of VirtualBox, but for me the address is “\Vboxsvr”
  • Shutting down your virtual machine. Actually don’t do it. There isn’t actually anything wrong with shutting down your virtual machine, but there is seldom a point. Saving the machine state instead, will make it much faster to start up again the next time you want to use that particular virtual machine. You can do this by going to Machine -> Close… and choosing “Save the machine state.” Also be aware that it’s not necessary to exit a virtual machine in order to use another: you can run as many of them as you want, simultaneously.

1 If your website is running off a server (e.g. Apache HTTP server) on your host machine it is not necessary to set up shared folders since you should be accessing the website through the server and not directly from its folder. To see a website that is on a server, simply go to its IP address.

I personally use DesktopServer for my server needs. It is aimed at developing WordPress websites, but works just as well for regular sites. Websites hosted on DesktopServer are usually accessed from fictional “.dev” domain names, but from the program’s window it is possible to assign an IP address to a site. Following are the directions, originally written by Stephen Carroll at the ServerPress forums:

  1. From DesktopServer’s main list of options, select “Import, export or share…”
  2. Select “Share…”, followed by clicking the next button. You’ll then be presented with a list of sites.
  3. Select the website you wish to share and select the “LAN” option (please make a note of the IP Address).
  4. Be sure to click next to save your options and automatically restart the server. You will now be able to access your site via the IP address on both your local and remote computers and mobile devices on you LAN. 

A few more things…

Optimizing webpages for mobile devices, part 2: CSS media queries, Javascript and mobile-specific websites

In part 1 of this article we went over the viewport meta tag. Although it can be useful in certain circumstances I feel that it is often unecessary. What’s worse, it’s hard to predict how it will behave on different browsers and it can in fact ruin some users’ experiences if not used very carefully.

If you really want your webpage to be able to transform itself to suit mobiles, as well as various other types of devices and specific features, you can  add special CSS rules that will automatically be applied to suit the situation. This can be done either with media queries or Javascript.

Lastly, if you prefer to create a completely separate webpage for mobile devices, you’re covered there too.  Mobile-specific websites are very popular and definitely worth considering as part of your strategy.

Media Queries

Media queries have become a very popular way of optimizing webpages for mobile devices since their introduction with the advent of CSS3. They work by telling a browser to apply special CSS rules depending on the type of device a webpage is accessed from and what media features it has. As you might have inferred from the previous sentence media queries, unlike the viewport meta tag, influence not only mobile devices, but also “regular” computers (heron referred to as “desktops”), printers, and anything else that can display the webpage.

Media queries can, for example, tell a browser to use a specific stylesheet for a webpage when it detects that it is being accessed from the “printer” media type (this happens when the browser is told to print the page). That stylesheet could remove ads and background images, for instance.

Below is an example of a media query that displays a webpage’s background in different colors depending on the “width” feature. This feature corresponds to the width of the browser window.

Media queries

As with “normal” CSS, media queries can be defined in several ways. However unlike regular CSS selectors, media queries cannot be defined inline in an HTML tag. The ways in which we can refer to media queries are:

  • From inside the document in which they will be used. As shown below, the code should be enclosed by the <style> tags, which in turn are enclosed by the <head> tags.

<head>
     <style type=”text/css”>
@media screen and (max-width: 480px) {
selector { property: value; }
}
     </style>
</head>

While the page has a maximum width of 480 pixels it will follow the rules inside the bracketes (selector { property: value; })

  • From an external stylesheet by importing said stylesheet into the document in which it will be used using the <style> tags. Again, the code should be enclosed by the <style> tags, which in turn are enclosed by the <head> tags. 
    • @import rules must always be placed before any other CSS content, including comments. They are not supported by really, really old browsers.

<head>
<style type=”text/css”>
          @import “480pxRules.css” screen and (max-width:        480px);
</style>
</head>

While the page has a maximum width of 480 pixels it will follow the rules defined in “480pxRules.css.”

  • From an external stylesheet by importing a stylesheet into the document in the “regular” manner using the <link> tag enclosed by the <head> tags. With this method media queries will be handled by the imported stylesheet instead of the document. The imported stylesheet can contain any combination of the two methods above (the parts which are in bold), and of course regular CSS.  Two things to note:
    • Remember that @import rules must be placed before any other CSS content and are not supported by very old browsers.
    • Rules of selectors that appear more than once are always overriden by the last definition. This means that media queries should always appear after all other CSS.
    • As a result of the above two rules any CSS imported into a document must not contain selectors that are repeated in said document or later import.

<head>
<link rel=”stylesheet” type=”text/css” media=”screen” href=”style.css” />
</head>

This is a usual stylesheet import. Testing for page width and applying the corresponding CSS rules is done either in “style.css” or in other stylesheets imported into “style.css.”

  • From an external stylesheet by importing said stylesheet into the document in which it will be used using the <link> tag. The code should be enclosed by the <head> tags.

<head>
     <link rel=”stylesheet” type=”text/css”      href=”480pxRules.css” media=”screen and (max-width: 480px)” />
</head>

While the page has a maximum width of 480 pixels it will follow the rules defined in “480pxRules.css.”

Although the different ways of referring to media queries might cause some confusion due to their different syntaxes, the overall “template” should make sense to anyone well versed in CSS. In any case, it’s just a matter of deciding which method to call the queries with and sticking to that general template while modifying media types and detectable media features to suit the situation. These variables are defined as such:

  • Media types: used to specify which type(s) of media the CSS rules will apply to. For example, in the examples above I have used the “screen” media type, which was primarily meant for color computer screens. However this media type also targets most smartphones nowadays, despite the fact that there also exists a “handheld” media type. If you don’t care about old “handheld” devices it’s enough to set your media type to “screen.” If you want to be safe, set it to “screen, handheld.” By leaving out media types entirely the CSS rules you define will apply to all media types. Here is W3C’s guide to media types and an article on the doomed “handheld” media typePro tip: instead of driving yourself crazy with 10 different stylesheets for each media type, focus on “screen” and possibly “print,” which are the two most used and useful media types.
  • Detectable media features: the most important part of media queries, these are the conditions we can screen for. “Max-width” and “min-width” are the most useful for our purposes; possibly also “orientation.” As with the viewport meta tag, each “width” variant has different uses when optimizing for mobile devices, but since media queries also apply to desktops, you will probably want to avoid the ones which refer to device-width, which always returns the resolution of the device. That’s fine for mobile devices since the browser usually takes up the entire screen space but if the user is on a desktop  it will return that device’s resolution regardless of the current window size. On the other hand “width,” “min-width” and “max-width” always return the width of the browser window.1

There is actually one last component that is very important. Don’t worry, it’s an easy one:

  • Logical operators: allows screening for both media type and multiple media features using the notand, and only operators. For example, “min-width” and “max-width” can be used together to specify that the CSS rules are only to be used when the window is between two different widths:

<head>
<link rel=”stylesheet” type=”text/css” href=”480to900pxRules.css” media=”screen and (min-width: 480px) and (max-width: 900px)” />
</head>

1 Media queries that refer to device-width are relevant if you actually want mobile devices to use different CSS rules than desktops. My HTC Desire has a resolution of 480px, which is the most common resolution for smartphones. CSS rules set for “max-device-width: 480px” will affect my Desire and most other smartphones. Desktop browsers would not be affected by these rules unless the actual screen monitor was 480 pixels wide, an uncommon sight to say the least. 

Javascript

Media queries are not the only way of specifying CSS rules based on different media types or features. Basically by using Javascript to get a desired value (width, for example) and then feeding them it into a specific function we can assign different CSS rules to differently sized windows and devices. That’s beyond the scope of this article, but Particletree wrote a very good article about it over 7 years ago! It is definitely worthy of consideration. With that thought, following are the pros and cons of both media queries and Javascript. I can’t recommend one or the other; read about both and pick what’s right for you!

Advantages of CSS media queries

  • Do not require Javascript to be enabled in the user’s browser.
  • Browsers that support CSS2 and CSS3 all interpret detection of media features and media types in the same way.

Disadvantages of CSS media queries

  • Detectable media features are CSS3, which means older browsers may not support them (media types were introduced in CSS2 so they have wider browser support).
  • As Rob Glazebrook pointed out in his article Using the CSS @import Rule Internet Explorer versions 4-7 cannot handle media types correctly. Still no confirmation if they work on IE8. Leave a comment if you’ve got the answer!
  • All CSS is loaded upon page load even if the conditions on which it depends are never met.

Advantages of Javascript

  • Older browsers that do not support CSS2 media types or CSS3 detectable media features can handle all of that through Javascript.
  • Allows checking for media types and features before loading the corresponding CSS files (assuming that CSS is not defined in the same document). This keeps unecessary CSS files from loading, but the Javascript itself slows down page loading. The conclusion is that this point is only relevant when every second counts, and then only if the amount of CSS to load for different situations is large enough that it pays off having the extra Javascript.

Disadvantages of Javascript

  • Users must have Javascript enabled in their browser.
  • Different browsers detect media features using different object/property combinations. According to Craig Buckler at Sitepoint “all the main browsers support document.documentElement.clientWidth anddocument.documentElement.clientHeight but it’s inconsistent. Either the window or document dimensions will be returned depending on the browser and mode.”
  • When the amount of special CSS rules is small, the extra Javascript doesn’t pay off with regards to page load times.

Mobile-specific websites

Because of the huge potential media queries and Javascript have in allowing you to control how your webpages are displayed under different circumstances, I would recommend getting familiar with and making use of them. At the same time it can be easy to get overwhelmed by the amount of possibilities. That’s never good, so if your aim is simply to create a good mobile experience to match what you’ve created for desktop users, a mobile-specific website just might be the answer.

As you might have guessed a mobile-specific website is completely separate from the main website, although it is usually a sub-domain of that site (for example, m.yourdomain.com). Everytime someone visits the main domain name (yourdomain.com), a function runs and checks what kind of device it’s being accessed from and then re-directs them to the appropriate site.

The code which checks the device type can be written in a variety of languages. Javascript is popular for this application but if your server supports a server-side language I would recommend that to ensure that it will work for all users. If you don’t want to write your own code I’ve come across a very nice solution called WURFL. What’s awesome about it is that it uses a “repository” (wurfl.xml), which contains the definitions of thousands of devices, and is constantly being updated. On their website it is stated that “WURFL is deployed by key Internet companies such as Facebook and Google” so I can’t imagine that there is a more effective way to do device detection, but I haven’t actually tried it myself. There are APIs available in several programming languages or you could write your own and just use their wurfl.xml file.

Conclusion

The viewport meta tag, media queries, Javascript, and mobile-specific websites — and that’s not to mention good design sense! With so many options and a growing number of users accessing webpages through iPhones, Android phones, tablets and other mobile devices there is no excuse not to give your visitors a great experience everytime.

Optimizing webpages for mobile devices, part 1: viewports and the viewport meta tag

Do you own an iPhone? How about an Android phone? iPad? There is a good chance that you or someone you know does. With more and more people using  smartphones and other mobile devices to browse the internet it is imperative that you as a web designer take a moment to consider your mobile users. If you haven’t been optimizing your pages for different desktop resolutions, that is usually the best place to start and may in fact be all you need to do. If you need to go deeper there are several options:

  • Use the viewport meta tag.
  • Screen for different window/device sizes and target them with specific CSS rules (media queries or Javascript).
  • Screen for mobile devices and present them with mobile-specific pages.

This is part 1 of a 2-part article on mobile device optimization, where we will also discuss different monitor resolutions and screen sizes on desktop and laptop computers (hereon referred as “desktop”).

Read on to find the advantages and disadvantages of optimizing your webpages, learn about viewports and how to use the viewport meta tag. In part 2 we will go over media queries, Javascript and mobile-specific websites.

You don’t have to optimize for mobile devices

If you don’t have the time or desire to optimize your webpage for mobile devices, you can rest assured that it will display fine on mobile devices as long as:

OR

  • All of your layout and content is inside a container or wrapper with a fixed width, such as a <div>. This <div> would set your viewport width ( more on viewports later).

If you’re not sure if you meet one of these requirements you can easily test how your page will look on a mobile device by shrinking your desktop browser window to simulate a smaller display. If everything looks good then you can stop there if you want. It doesn’t even matter if you have to scroll horizontally to see everything; the point is to check that your layout doesn’t fall apart on a resized browser window or a small mobile display.

If your design doesn’t hold upon resizing the browser window, you should probably work on it some more. You could add a viewport meta tag with a fixed width to fix the problem for mobiles, as we will see later, but it’s no fun for your users to see a mess when they resize the window on their desktop either.

How does it look?

Regardless of how your layout looks upon resizing, be aware that if it has a set width that is too wide for a particular display most mobile browsers will automatically zoom out in order to fit everything on the screen. Otherwise useres can zoom out themselves, though you can limit that option in the viewport meta tag which, again, we will explore later.1 The point is to keep this in mind since your zoomed out webpage might look very small depending on the mobile device.2

1 The concept is the same for desktop browsers: if you have to scroll horizontally the layout is too wide for your display. You’re free to zoom out instead of scrolling. 

2 You can test this pretty accurately by placing your mobile device up against your desktop monitor (or using a physical ruler to measure for other screen sizes) and resizing your browser window horizontally so that it is the same width as the mobile display. Then zoom out until the horizontal scroll bars disappear. You might get strange looks while you’re doing this, but you can just ignore that or tell them that you’re doing it for science! What you see on your desktop browser now should correspond to what gets displayed on the mobile device, but be aware that it might be slightly off since your browser probably doesn’t allow such surgical zooming. Also when text and images are so small they might not render with the same quality as they would on the mobile device.

Pros of leaving your pages unoptimized

Assuming you have a fluid design or all of your layout and content is inside a container (wrapper) with a fixed width…

  • Takes absolutely no time and zero effort.
  • Retains the same design users see on their desktop browser.

Cons of being lazy

Assuming you don’t have a fluid (liquid) design or if the layout/content is not inside a container (wrapper) with a fixed width…

  • Layouts which have a set width considered “normal” on a desktop display will be too wide for most mobile devices. This will in turn make it necessary for users to zoom in and out in order to juggle between seeing the entire page and actually being able to see any one thing in a reasonable amount of detail.

The viewport and the viewport meta tag

It can be tricky deciding how or if you should even use the viewport meta tag. And if you do decide to use it, should you combine it with the other mobile optimization tools at your disposal? In the following paragraphs I will attempt to answer these and other questions that you will inevitably ask yourself.

In order to understand what the viewport meta tag does you should first know what a viewport is. Simply put, the viewport is the area which contains your entire page. Everything you see on your browser window you are seeing through the viewport.

On a desktop browser you might have to scroll up and down or side to side to see everything. Most mobile browsers will not show you scroll bars but will instead let you zoom in and out to see the entire page.  Regardless of how much you are shown when the page first loads, the entire area in which you can move around is enclosed by the viewport.

Viewports
Viewports and zoom (click to enlarge)
Most mobile browsers automatically load pages zoomed out (right) so that the entire viewport is visible, but you can have a certain amount of control over this by setting initial-scale or minimal-scale values in your viewport meta tag.

——————————–

So now you might be wondering how to control the size of the viewport. If it has not been set by an element, as described earlier, we can go ahead and insert the infamous viewport meta tag between the <head> tags on the page.3 It looks like this:

<meta name=”viewport” />

It’s not much to look at and it is in fact useless as defined above. In order to control anything with this tag we need to add some parameters to it. To set a specific width to our viewport we could write:

<meta name=”viewport” content=”width=1500″ />

And here it is again with even more parameters:

<meta name=”viewport” content=”width=1500,initial-scale = 1.0,maximum-scale = 1.0″ />

In this case we are telling the browser to make the viewport 1500 pixels wide (width=1500). The page is loaded at 100% zoom (initial-scale=1.0) and the user is not allowed to zoom in (maximum-scale=1.0).

One last example:

<meta name=”viewport” content=”width=1500,initial-scale = 1.0,minimum-scale = 1.0″ />

This time the user is not allowed to zoom OUT (minimum-scale=1.0). Combined with the other values we provided this is probably not a good idea: since 1500 pixels is a lot for most mobile displays and the page is being loaded at 100% zoom the user will only see the top-left corner of the page on most mobile devices. Combine that with the inability to zoom out and the user will have a very frustrating experience!

3 Remember that the viewport meta tag has no effect on desktop browsers. It can be useful in controlling how your page displays on mobile devices, but if your layout falls apart when you resize the browser window on a desktop you should fix that first. 

What can you do with the viewport meta tag?

Below are several things you can do to control how the viewport is presented to users. Keep in mind that different combinations of meta tag parameters can produce different results, which are often hard to predict. On top of that different browsers may have different ways of interpreting parameters and their values so the more browsers a page is tested on, the better.

Note for parameters that take numerical values that these should not be less than “1.0” (100%) as different browsers either ignore or output unpredictable results for lower values. By the same token manually zooming out to less than 100%  does not seem possible.

  • Control the width of the viewport using the width parameter.
    • “width=x” for a viewport x pixels wide or “width=device-width” to let devices set viewport width automatically. This page lists many mobile devices and their default viewport sizes.
    • “width=device-width” is a good choice for liquid and responsive designs as it ensures that the page loads at 100% zoom, meaning a comfortable reading experience across devices.
    • The width parameter may override a viewport width previously defined by an element or vice-versa depending on the browser.
    • If no width is defined by a page element or by the viewport meta tag, different browsers will set different viewport widths.
    • The width parameter has corresponding “height” and “device-height” values but in most cases it is not useful to control viewport height.
  • Set the initial zoom level of a page when it loads using the initial-scale parameter.
    • “initial-scale=x” sets page width to (x*100)%, then disables the ability to zoom out if no element exists with a wider width. Otherwise zoom out limits vary by browser or are limited by the minimum-scale parameter.
    • 100% zoom corresponds to the device’s default viewport size.
    • initial-scale may override minimum-scale and/or maximum-scale or vice-versa depending on the browser.
  • Limits how much users are allowed to zoom IN using the maximum-scale parameter.
    • “maximum-scale=1.0” disables the ability to zoom in, higher numbers allow zooming in more.
  • Limits how much users are allowed to zoom OUT using the minimum-scale parameter.
    • “minimum-scale=x” sets page width to (x*100)% , then disables the ability to zoom out since it is already at the minimum scale of (x*100)%.
    • minimum-scale may override initial-scale or vice-versa depending on the browser.
  • Control whether users are allowed to zoom in and out in your page using the user-scalable parameter.
    • “user-scalable=yes” allows users to zoom in and out; “user-scalable=no” disallows zooming in and out.
    • The most unpredictable parameter of the viewport meta tag is the user-scalable parameter and its use is strongly disencouraged. Despite previously defined viewport widths, some browsers set unique viewport widths on page load when user-scalable is set to “no.” Additionally all other parameters of the viewport meta tag are disabled, effectively denying not only the user but also the developer the ability of scaling and controlling the page layout. Many browsers do not support the user-scalable parameter.
    • The default value of the user-scalable parameter is “yes.” To disallow users the ability of zooming in and out the best option is to set “maximum-scale=1.0, minimum-scale=1.0”

Some examples of defining viewport width

Following are three different ways to set the viewport width on a page, plus one example where no width is set anywhere. Examples are meant to be viewed on a mobile device — view the index page at goo.gl/ma4Fm or scan the following QR code:
Viewport width test

When should you use the viewport meta tag?

  • When you have a layout that already works well on a desktop — including when the resolution is low or the browser window is small — and you want to have more control over how the page is displayed on mobile devices.

When should you refrain from using the viewport meta tag?

  • When your design is falling apart when viewed on lower desktop resolutions and resized browsers. The viewport meta tag only applies to mobile devices; therefore it is important to fix these problems at their source so that your desktop users (which is probably the marjority) also have a decent experience.
  • When you cannot test your webpage on multiple mobile browsers. Since different browsers handle viewport meta tag parameters differently what works on one browser may give a completely different result on another.

Conclusion

In a lot of ways optimizing for mobile devices is the same as making sure that your pages work on different desktop resolutions and resized browsers — something webdesigners have been doing since the dawn of time. Many of the old tricks can still be used and we can now combine them with new tools whose development was encouraged by the evergrowing use of the internet on small screens. In addition new solutions like the viewport meta tag, CSS media queries and mobile-specific websites have been exclusively developed to deal with mobile devices.

Part 2: media queries, a Javascript alternative to media queries, and mobile-specific websites.

Remote Registry Editing and Registry Recovery

If you edit something in the registry and Windows doesn’t start it might seem like you have a really big problem as you no longer can access and edit the registry to fix the problem. But if you have access to another hard drive with a working copy of Windows or another computer with Windows, you can plug in your “sick” hard drive and access its registry editor. Following are my directions for Windows 7. For Windows XP see here: http://forums.pcper.com/showthread.php?409638-Remote-Registry-Editing-and-Registry-Recovery

  1. Go into Registry Editor (run… regedit)
  2. Highlight HKEY_LOCAL_MACHINE
  3. Click File -> Load Hive
  4. Browse to A:WindowsSystem32config (replace A with whatever drive letter you have assigned to your sick hard drive).
  5. Find SYSTEM and open it.
  6. Now you will be asked to create a name for the hive. I enter “a” so it shows up first on the list.
  7. Qhen you are finished editing your registry remotely move to the top level of the named key (“a” in this case), and click File->Unload Hive. DO NOT SKIP THIS STEP

Now when you go into “a” you will see all the HKEY_LOCAL_MACHINE registry entries for your sick hard drive with the exception of SYSTEM/CurrentControlSet. This key cannot be accessed remotely. If that’s where the problem resides there is still one other way to get Windows on its feet again.

The SYSTEM file

If you had a system restore point saved on your sick drive, navigate to A:WindowsSystem32configRegBack (again replace A with the drive letter assigned to the sick drive) and copy the SYSTEM file. Paste it into A:WindowsSystem32config, replacing the file that is there currently. The only likely downside will be that you will have to re-install any programs since that restore point was created.

Once again, when finished remember to move to the top level of the named key (“a”), and click File->Unload Hive!

Alternatively, if you have a clone of the sick drive from before it was sick you can copy the SYSTEM file from A:WindowsSystem32config (replacing A with the drive letter assigned to the CLONED DRIVE) instead. If you have both restore points on the sick drive AND a clone of the drive before it became sick I would recommend you to choose whichever SYSTEM file was created most recently.

Edit 19/08/2013: As I’ve written in my post about browser testing in VirtualBox there is a last resort I can recommend to those who need to bring their Windows installation back from the dead and don’t have access to either an extra hard drive with a  copy of Windows or a restore point: the SYSTEM file might also be copied from a Windows installation in VirtualBox, though copying it from a clone of your hard drive or one of its restore points is always preferrable since all programs installed after the file’s creation will need to be re-installed.

Good luck!

Salvaging a mediocre photo

Last month I went out to take some photos of an oak tree nearby, but I was not very happy with the results. Yesterday I got inspired to go through and try to do some post processing on them. I felt like the last photo of the day actually had some potential and in the end I was very happy with the result.

Oak tree

HOW IT WAS DONE
I started out in Lightroom with some regular tone adjustments, and then I worked with the White Balance. I decided to bring it up quite dramatically in order to emphasize the orange color of the sky. Next I decided to brighten up the ground so I used a Graduated Filter and brought up the Exposure. It started looking pretty nice but I didn’t like how my White Balance adjustments had also given the ground an orange tint so I decided to bring the image into Photoshop to work on it with more control.

In Photoshop I separated the image into two layers, one above the horizon line and one under (the “ground” layer). I used Color Balance and Hue/Saturation adjustments on the ground layer to get the color the way I wanted, then I brightened it up even more with Brightness/Contrast and Levels adjustments.  Then I decided that I had actually made the sky too orange and even worse, I had lost all of the blue. So I “cheated” a little: I used the Gradient Tool going from a nice blue color to transparent and I let that “sky” layer have it! Even though the tree itself was on the same layer it was not visibly affected since it was completely dark anyway.

I finished up the job by bringing the photo back into Lightroom, sharpening it, and adding a nice vignette.

The lesson to be learned here is not only that mediocre photos can be salvaged with the right tools, but also that maybe some of those photos aren’t so mediocre after all. My oak tree had a simple, but very nice composition so really, the only thing wrong was with the exposure and colors. Since I always shoot in RAW there was a lot I could do in post-processing. That mediocre photo is now the top viewed, liked, and commented on photo in my 500px account.