Randomizing and Listing Data

Bottles in a row

I collect scents. Many online fragrance stores have sampling services that let you try even very expensive scents (over $300) for only a few dollars. Over the years I’ve managed to collect about 750 scents. My problem is that I keep wearing the same ones over and over, while neglecting many hidden gems. I wanted to pick random selections from my database (which is in Apple’s Bento), and schedule them on a weekly basis, without repeating any. That involved several challenges: exporting the data into a generic data format, randomizing it, checking for duplicates in the output, and organizing it in lists by day.

The first challenge was exporting. It sounds easy because Bento will export as Excel or csv. The problem was that I wanted to use JSON and jQuery to process the data and I needed numbers for each database entry, both for the JSON structure and to use for fetching the random item. Even though databases and spreadsheets number all the rows, they don’t export those numbers with the data. I needed it to look like the code below:

{ "1": { "Scent": "Scent Name 1", "By": "Company Name 1" }, "2": { "Scent": "Scent Name 2", "By": "Company Name 2" }, [etc.]

Maybe there’s an easy way to do this I don’t know about, but here’s how I did it: I imported my Bento data into Excel, created a new first column, then used the fill option to create a new numbered column. (Instructions can be found in this short video.) After I got the numbers I exported the data as a csv file and then converted it to a JSON file. It gave me exactly what I wanted.

Once I had referenced my JSON file in my jQuery I needed to choose my random selections. The randomizing was easy. I used a target number equal to the number of items in my database:

var myNumber; function doRandom() { myNumber = Math.floor(Math.random() * 748) + 1; }

To choose a week’s worth of scents, I fetched the data that corresponded to my number 7 times:

var myNumber, myHtml=''; for(var n = 0; n < 7; n++) { myHtml+=(data[myNumber].By + data[myNumber].Scent); }

But I quickly saw a problem, which was that even in such a small output the same scent got repeated. With such a large data set, that had seemed unlikely, but there it was. I needed to make sure that didn’t happen, and the answer was to compare the generated random number to a saved array, and if it was unique, add it to the array for the next comparison, then output it to the list.

var myNumber, usedArray = []; doRandom();//generate a number if ($.inArray(myNumber,usedArray) !== -1) { doRandom();//if it's already in my array, try again } else { usedArray.push(myNumber);//if unique, save to array and use }

That gave me all unique choices. Next, I wanted to build a list from the results and assign to days of the week. I defined my days with an array, and used the modulo operator to give me the index for the array. I also added some markup around it:

var myDays=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]; myHtml+=("<dt>"+myDays[n % 7] + '</dt><dd><strong>'+data[myNumber].By + ':</strong> <em>'+data[myNumber].Scent + '</em></dd>');  

It went so well I decided to go with a full month, by wrapping my output in columns with weeks numbered 1-4. (I put the modulo in a variable because I was reusing it.):

var j = 1; for(var n = 0; n < 28; n++) {//4 weeks * 7 days = 28 myMod = n % 7; if (n==0) {//initial HTML wrapper and first week myHtml+="<div><h2>Week " + j +"</h2><dl>" } else if (myMod == 0) {//end the week and begin the next myHtml+="</dl></div><div><h2>Week " + (++j) +"</h2><dl>" } [Generate data result html] if (n==27) { myHtml +="</div>";//final close HTML structure }

Here is the completed code and the results list:

See the Pen GqzoQK by Connie Finkelman (@pixelslave) on CodePen.21122

I went on to expand the script to schedule the entire collection, which spanned 94 weeks. I output it on an HTML page and printed the results. I’ll probably never run the script again, but if I were reusing this often I would do things differently. I would get the collection count from the JSON file, then make and array by shuffling numbers between 1 and the collection count, then use that to draw my data results, rather than choosing a succession of random numbers and comparing them one at a time to the JSON values.

Scaling Text

One of the challenges posed in modern web development is dynamic text sizing. Images can be set to “auto” or “100%”, but text doesn’t work that way. It is scaled relative to its base size rather than its container.

When we’re just thinking about sizing responsively we can use the “vw” unit of measure to size text in relation to the viewport when the width gets into the hand-held device realm. That would usually be around 4-5vw. But what happens when we need it to fit into a container other than a viewport?

I’m currently working on a project that has a member points block, where the points are placed in a circle. The points aren’t very valuable. meaning that a user may have thousands. The artist specified a design showing only a 4-digit number where one of the digits was “1”, which is very narrow in a non-monospaced font.

Circle with number in it

artist’s vision

What would happen when the user had 333,333 points? Would the circle become an oval? Not very attractive!

I could have used CSS text ellipsizing to slice it off. That is done like this:

span { width: 100px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

But that would not have produced a meaningful result. Since the artist’s specs also included a diagonal “badge” to incentivize a user with zero points, I was going to have to write JavaScript anyway. I decided to try to find a way to programmatically shrink the text.

I didn’t want to rely on character count with the numbers, because they are not all of the same width in the specified font.* Instead I needed to rely on the length of the HTML element when the number was present in it. In order to do this, I had to trust that the code would work and let the span holding the number to grow as much as it wanted. If I clipped it with “overflow:hidden” it would never show the pressure its contents were exerting.

It turned out to be much easier than I thought. I reasoned that I would have to reduce the font size by a percentage that reflected the relative proportions of the expanded span and the fixed-width holder. For example, if the span holding the number grew to 200px, it would need to be reduced to 54% of its size to fit the 108px container again (108/200=.54). I knew my font size was 40px, and I hoped that multiplying 40 by the reduction percentage would work. Surprisingly, it did! I used 100 instead of 108 to give myself a little margin for error, then I reduced the result again by subtracting 10 from my calculation to provide a little padding. I was really happy with the result!

 

See the Pen Shrink Text by Connie Finkelman (@pixelslave) on CodePen.21122

*Numbers in Verdana are monospaced, giving you a character count option instead.

Making a Custom Icon Font for Your Website

One of the things I noticed over the years is that web developers hate making sprites. A few years ago there was a heated debate among performance engineers about whether or not it was better to use data URIs in your CSS or to make sprited pngs for all those icons websites typically use (arrows, bullets, etc.). The right answer at the time was probably make a data URI out of your sprite but now we can put that argument to rest forever with fonts. Using a custom font solves so many problems it seems like the obvious solution, and I use them now whenever I can. Now that graphics are heavily influenced by Google’s Material Design, flat one-color icons are very popular, and that’s what fonts are. They are particularly good for mobile, because they look super smooth and sharp on high-density displays. The pictogram characters in custom icon fonts are called “glyphs”, and all the frameworks seem to have them. Bootstrap has its  “gylphicons“, Foundation has its icon fonts and Google Web Toolkit has its material design icons. Many WordPress themes come with several sets of icons included. You could use one of these off-the-shelf icon sets, but they are much bigger than you need. They all contain icons you’ll never use and (what I think is worse) the ones you will use will not be a perfect fit for your interface or be the perfect symbol for your message. That’s why I like to create a custom icon set whenever I’m doing a new website. These custom sets are very small and efficient. For example, the site I’m currently working on has a set with 117 icons and weighs in at 30k for the minified CSS and the WOFF version of the font (the one most widely supported by browsers). Contrast that with Bootstrap’s glyphicon font that has 250 glyphs in it at about 94k without the CSS.
Do you really need a cadastral map icon?

Do you really need a cadastral map icon?

 

Creating your custom font

It’s very easy to make a custom font. There are probably several ways to do it, but I like to use Fontello. Fontello already has hundreds of fonts in various collections that you are free to incorporate into your custom font. To do this, simply click on them in the browser window. A circle will appear around the icon and that means it’s been added to your collection. You can also add your own custom glyphs. For this post I created a custom font with three icons called “pastry”. custom icons I made these in Illustrator by taking black and white clip art and using the command “Object > Image Trace > Make and Expand”. Next I simplified it by selecting the parts I wanted and deleting everything else. (Vector images often include backgrounds and masks.) I sized the artboard to fit my graphic, then saved it as an SVG. It is not necessary to select anything special when doing this. Just use the “Export” or “Save As” command, choose “SVG” as the file type and accept the defaults. Next I dragged the svg from my workspace folder on my computer onto the Fontello browser window. It automatically added it to my custom font. Once I had all the glyphs I wanted I downloaded my font. Fontello will remember your font on subsequent visits. If you want to reload your custom font in a different browser, or share it with someone, just open Fontello.com and import the config.json file that comes with the font downoad. (Import is under the wrench icon at the top of the page.) If you want to forget your old font and start again you can clear Fontello (under the wrench icon) and delete your custom fonts (link next to the heading above the custom font area) and import a new config. Dragging the svg version of a custom font onto Fontello will also open it as a custom font.

Using your custom font

To apply your font you can use use the classes provided in the CSS on any HTML element (except form fields) or use the character number provided in CSS :before content. If you want to use your font in a design program just import the font into your system and choose your custom font from the font menu. Typing the characters you want is difficult, since they don’t map well to the alphabet. Instead, copy paste them from Mac’s font book or from your Fontello website page.

Troubleshooting

As always, things are never as simple as they seem. Sometimes when you drag your SVG onto Fontello you get nothing, or a partial image. That’s usually a problem with the vectors in your glyph that can be easily solved.
  1. Image lost detail or turned solid black If you have an area filled with white sitting over an area filled with black it will come out all black, since fonts only handle one color. To fix this, punch out the white so it makes a hole in the black that lets the white background show through (Pathfinder > Minus Front).
  2. Image lost parts Some areas of the image may be separate and this sometimes causes them not to be seen as a group by Fontello. Make your image into compound paths before exporting (Object > Compound Path > Make).
  3. Lines disappeared Fonts only work with fills, not strokes. If you have strokes (a circle, for example) you must convert these to paths. Use the “Expand” or “Expand Appearance” commands in Illustrator. Then, be sure to merge any that overlay each other (Pathfinder > Unite).
Mac and PC handle fonts differently. I’ve had quite a few cases where the glyph looked fine on my Mac, but on PC it had lost all or some of its shapes. PC is more sensitive to the issues listed above, so be sure to test your font across different platforms and browsers. When making rectangular glyphs—especially those intended for use at large sizes (logos, e.g.)—center them in a square bounding box using Illustrator’s artboard. Otherwise you may see weird vertical misalignments, which I think may be due to the browse’s inability to calculate the descender height.

10 CSS Pro Tips

GitHub Octocat Ninja

There are lots of resources for cool CSS implementations, like animating elements and applying complex effects, but often it’s the little things that are the most useful. Those aren’t flashy enough to get mentioned in books and articles. They are the finesse techniques that experienced developers use to make their work more elegant and their workdays shorter. Here are my ten favorites:

1. Smart text case

Coding for maximum control of casing is particularly useful on buttons. In my experience the Business is always changing their minds on button casing and using the most adaptable capitalization when coding will make it simple to change all the cases sitewide with a single line of CSS. My tip is to use title case. That is hand tuning to a mix of upper and lower case, where insignificant words like “to” and “and” are not capitalized, but everything else is. It’s the only type of casing CSS can’t achieve. In the example below I have five identical buttons with the words “Add to Cart” on them. I’ve used only CSS to change the capitalization.

See the Pen Casing by Connie Finkelman (@pixelslave) on CodePen.21122

2. Smart line breaks

Line breaks are the result of text automatically wrapping in its container or the application of the HTML tag “<br />”. We all know that using break tags to introduce vertical space into a layout is the mark of an amateur coder, but now that we are using responsive layouts and building code for use on devices of greatly varying widths, we begin to see more subtle gotchas. For example in the menu snippet below, breaks have been used to balance the wrap and control where the ampersand is placed.

That’s fine until you need to transform this menu for a tablet or a phone and you want the menu text all on one line. You can use CSS to set the break tags to “display: none”, but there are more elegant ways to provide for customizing line breaks. The first is with CSS white-space formatting.

See the Pen Line breaks by Connie Finkelman (@pixelslave) on CodePen.21122

The second way to accomplish this is with spans or other inline HTML elements. (By “inline” I mean the opposite of “block”. See this explanation is you are unclear about the difference.) Using these wrappers is a semantic approach that is well suited to content that needs separation due to its meaning and context. For example, if you have a price label and a dollar amount and you want the ability to stack them.

Our Price: $19.99

To accomplish this you simply wrap each part in a label, span, strong, or em element and either float and clear, use flex, or give each a 100% width and center text align. The added advantage here is that you now have hooks for additional styling.

See the Pen Wrapping with flex by Connie Finkelman (@pixelslave) on CodePen.21122

3. Definition lists

In my experience, the definition list is one of the least used HTML structures but it is one of my favorites. I love it because it is semantic and establishes a relationship between two pieces of related content. That is a scenario we see often on transactional sites, for example, in a cart totals and account information. It can give you an effect similar to the tab spacing you get in word processing without locking you into a horizontal layout.

See the Pen Definition lists by Connie Finkelman (@pixelslave) on CodePen.21122

4. Namespacing

There are lots of great resources for naming and applying CSS classes, one of the best being Jonathan Snook’s SMACSS. But to me, one of the most important practices is separating styling classes from programming hooks. Enterprise code often has many developers modifying it on a continuous basis and it is refactored often for styling changes. If you use a generic styling class such as “full-width” as a hook for JavaScript your code will get broken when someone removes or changes that class and it will be your fault for not communicating the role of that element. Since HTML elements can have many classes, I always create a namespaced class for JavaScript hooks that will signal to any developer who comes after me the significance of that element. For example, I might create a class called “js-tooltip-trigger”. That makes it clear what’s going on with that element and protects the functionality.

4. Doubling weight

To me, the most important aspect of CSS authoring is controlling the specificity or weight of CSS rules. We want to keep rules as weak as possible so they can easily be extended for more specific cases later in the style sheet. Sometimes we have a generic class that needs to be given a little more strength. (This happens when you apply multiple generic classes that may have duplicate rules that contradict each other. Which ever one comes last in the style sheet wins. You may want to allow the earlier rule to always win.) We don’t want to make a rule too strong, so adding “!important” to it is out of the question. We can’t add an HTML element to it because we want it to be universal.

The best option is to add an additional class to it. We could pick a class we expect it to have as an ancestor, but that’s not guaranteed. The answer? Double it! by chaining a class to itself (“.stong.strong”) we double its weight without creating a dependency. Is it a hack? Maybe. But it’s valid CSS and incredibly useful, so that’s good enough for me.

5. The magic number

1.2em seems to be sort of a magic number in CSS. It is the normal line height and it is also the amount of left-side space a list needs if it has bullets on it. Resets sometimes strip off all the margin and padding from elements. This makes sense because they are used for structural elements such as navigational hierarchies more often than they are used as simple text lists. This leads to a situation where the bullets fail to show up on a list or the bullets are too far to the left, appearing outdented in relation to the surrounding paragraphs. Applying 1.2 ems of margin to your list cures this.

See the Pen 1.2em by Connie Finkelman (@pixelslave) on CodePen.21122

6. //#end

When you’re writing SCSS (SASS or LESS) you often have extensive nesting. Even if you don’t nest deeply you may have many siblings under a parent class or ID. No matter how much of a CSS ninja you are you will eventually hang a closing tag. I spent countless hours trying to debug huge blocks of SCSS looking for a missing or duplicated closing bracket until I started putting comments after the main closing tags in a block. I do this as soon as I open the class or ID declaration, rather than waiting until it fills up. There’s no downside to overdoing it, since comments are stripped out in compile for production-bound code. Both CSS and JS style comments work in SCSS. For example:

/*.article */
//[id=mainContent]

I also hand-code HTML, and I’ve also wasted many hours of time trying to troubleshoot broken CSS only to find that the real problem was a broken DOM. It’s a good idea to mark these as well, for example:

</div><!--/.article -->
</div><!--/#mainContent -->

7. Line flag classes

This one may be a bit controversial, but I find it to be a huge timesaver. I currently work in .Net with a very large codebase. I often find it difficult to figure out where dynamic content is coming from. For example it may be the result of a multipart conditional that has half-a-dozen possible outputs that have different values but identical markup and CSS classes, or it may have a pattern of markup, ids and classes that is not unique in the project and could have originated in one of several .asp files. When I’m trying to narrow down the source of this output I do a “find” to get a list of all of the possible sources, then I add a class that references the line number of each, e.g. “l4573”. That tells me conclusively which instance I’m working with.

I did this once for a table that had separators I was trying to eliminate. Flagging the line numbers showed me that these separators were coming from 6 different code blocks and it made the job so much less frustrating to know which one I was working with in each case.

When you’re done with the current task you can take these markers out or leave them in. Leaving them in makes it simple to locate the code later, as this class will be unique. (The chances of multiple elements falling on the same line number in a single document is nil and the possibility of this happening across several documents is also nil unless the documents are identical.) The downside is that you’re adding additional markup in the form of a CSS class that has no CSS functionality. That may bother CSS purists. The upside is that you’ll be able to take a longer lunch hour. For me it’s a no-brainer.

8. CSS Wayfinders

There is no “==” in CSS syntax. That makes this an extremely useful identifier in CSS blocks. If you comment each CSS section or SCSS include with this character pattern you can easily find your way in large CSS documents by simply searching for it. It looks like this:

/* ==Navigation */

You can take it a step further by coming up with your own scheme, such as using the word “page” + the id of a page’s body to introduce a block specific to a certain page:

/* ==page #checkoutPage */

9.Codepen autoprefixing

It’s easy to see from these blog posts that I love Codepen. I work in big enterprise projects with compiled code (including CSS and JavaScript that has to be built on each change). Being able to extract just the piece I’m working on and have it all in one place with instant updates saves me hours. Among the many great features of Codepen is the ability to automatically generate autoprefixing for CSS properties like “flex” that aren’t fully supported in all browsers. This is under “Settings” –> “Vendor Prefixing”. To use it, click the “View Compiled” button that will appear on your CSS panel when prefixing has been enabled. You can easily copy this to your project’s CSS file. I routinely paste my CSS into Codepen just for this function.

10. Codepen CSS validation

If you need to validate your CSS, LESS, SASS or SCSS the quickest and most reliable way I’ve found to do this is to paste it into Codepen’s CSS panel. It not only  flags errors it also tells you how to fix them. I do this on at least a weekly basis because if you’re hand-coding CSS you will make a typo sooner or later.

jQuery Toolkit: 5 Scripts Every UI Developer Needs

I build a lot of websites and I find myself using the same helper scripts over and over. Let’s face it—websites have a lot in common! Over the years I’ve refined these scripts and I’m collecting them here for others to use and share. You may not have found a need for these because you’re relying on jQueryUI for your widgets, but I’m finding that library to be out-of-date and too bloated for my use. Maybe it’s time we all rolled our own! I chose the following list based on how often I used them.

1. Clickable Box

The popularity of individual, styled content blocks on sites has created a need for an entire div to be clickable, not just the link or button within. Now that we have lost some of the browsers that didn’t support divs inside of anchors, and we use HTML5, which allows anchors to wrap block elements, we could simply wrap an anchor around the entire div. Unfortunately, things aren’t always that simple.

For example, your active element might be an input (form submit button) instead of an anchor. Or you might be dealing with a dynamic, repeating block of content that does not give you access to the link at the start of the output (in a WordPress loop, e.g.) You may want to keep the call-to-action button clickable for usability or accessibility purposes and you can’t wrap an anchor within another anchor.

We see this most often with promotional banners in responsive layouts, where composites of text, images and active links have replaced a single graphic to allow smart resizing.

The script for dealing with this is quite simple:

See the Pen Making a box clickable by Connie Finkelman (@pixelslave) on CodePen.21122

2. Tab Box

I’m constantly making tab boxes. I don’t like the fact that jQueryUI needs to add 5 classes to my tab wrapper, four classes to each tab and three classes to each content box. But what bothers me more is that the tabs’ style is accomplished using png background images. I’ve got nothing against pngs, but that’s old school. Browser support for gradients is good, but even so, that look is old-fashioned.

It’s so easy to make your own!

See the Pen Tab Box by Connie Finkelman (@pixelslave) on CodePen.21122

3. Accordion

This widget is such a core element that we require developers applying for a UI developer position in our organization to code one in under 15 minutes. It should take less than 10 minutes, but we add extra time for nerves. I like to use lists for this because of the strong sibling relationships they create, but you can easily adapt it to any structure.

See the Pen Accordion by Connie Finkelman (@pixelslave) on CodePen.21122

4. Modal Dialog

This is a basic dialog window that can be used for most messaging. If you have a very large amount of content in it you may have to add scrolling to the inner content. This dialog relies heavily on CSS, using JavaScript to open and close it and correct its positioning. It opens with its top left corner in the center of the page, so it must be moved half its height and width up and to the left to actually center it. This is done with negative margin, since position is already being used for the basic centering. Since it uses CSS to center, it automatically corrects itself when the window resizes, so no resize listener is required.

See the Pen Modal by Connie Finkelman (@pixelslave) on CodePen.21122

5. Tooltip

This is a script for replacing the browser’s tooltip with one that you can style in a more attractive fashion.

See the Pen Tooltip with caret by Connie Finkelman (@pixelslave) on CodePen.21122

Mobile Toolkit: Off-canvas Sliders

Mobile toolbox

On a mobile website I recently built I had two sliders. The first was the main navigation menu, and the second was a product filter. They used similar CSS techniques and had to be coordinated with each other, as they both occupied the same off-canvas area to the left of the visible content.

The Off-canvas Navigation

I built the off-canvas navigation first, since it is fundamental to the site’s framework. I used the standard checkbox method to achieve this with CSS rather than JavaScript, because JavaScript tends to have a bigger impact on performance than CSS and can easily grow to a huge size if not carefully controlled. For those not familiar with this technique it uses a checkbox, a label and an adjacent sibling. The checkbox is hidden and its label is the menu icon/link. When the label is clicked it toggles the :checked state of the checkbox. The main content area is a direct sibling of the checkbox, allowing it to respond to this state via CSS, using the adjacent sibling selector (“+”). Briefly, it looks like this:

checkbox:checked + #contentWrapper { left: 75%; transition: left 0.4s; }

The important thing to remember is that for the label to activate the checkbox the two must be linked, as they are not siblings: The checkbox is above the main content area and the label is inside the content area. They are linked by matching the “for” attribute on the label to the checkbox’s ID:

<input id="menuTrigger" type="checkbox"/>
<label for="menuTrigger">Menu</label>

I dressed it up with a glyph from FontAwesome and added some CSS styling. Here’s what that looks like when completed:

See the Pen Mobile Off-canvas Navigation by Connie Finkelman (@pixelslave) on CodePen.21122

The Filter Menu

Next comes the filter. The filter is a side column on the desktop site that lets the user narrow their search results by making selections from a list of attributes. There is no room for a side column on a mobile device, and it would be useless if it flowed after the content. It is too complex to be replaced with a select element. It has to be either a pop up (modal window) or a slide out.

I can make a simple HTML list and activate it with a button:

<span class="button">Show Filter</span> <div class="filter-options"> <ul> <li>[options]</li> ...

It also needs to have a mask behind it to dim and deactivate the page allowing the user to focus on this element. Typically this would be done with a plugin, such as jQuery UI, which automatically adds the mask. But I really don’t want the bulk of that plugin! Instead, I make the mask with CSS by using the :before pseudo-element and giving it a fixed position. I created the class “mask” because I may use this same tactic on a different element later. I can use the same checkbox scheme for the filter slider as I did on the nav.

It is not possible to activate the main navigation menu when the filter is open because the mask blocks the click. However when the menu is open part of the filter button shows and that is clickable. If the user clicked it the filter’s mask would block the user from closing the nav and they might have to refresh the page to continue. For that reason, I want to be sure that the filter can not be activated when the menu is open. That’s easily accomplished with the “pointer-event” CSS attribute. I can inherit from the #contentWrapper div in its open state (using the :checked sibling relationship) and the trigger for the filter is its child, so will also inherit from that state:

#menuTrigger:checked + #contentWrapper .filter-wrapper{ pointer-events: none; }

One final thing I have to do is hide the filter slider content when the menu is showing. It is ofter longer than the navigation and it will cause that area to be taller than the space needed by the menu. You would probably be able to see it when scrolling. I can’t hide it by default and show it when the slide is triggered. That would kill the animation because it would not show until after the transition completed. Instead I hide it when the menu is showing—using selectors similar to the CSS above, but with a different child. Below is the completed code.

See the Pen Mobile sliders by Connie Finkelman (@pixelslave) on CodePen.21122

Lightweight Mobile-friendly Slider

Big vs little

There are many sliders and carousels you can download free and plug into your site. Most of them are full-featured. They are meant to be a one-size-fits-all solution. That versatility comes at a price. The minified js and css weight of one of my favorites is around 25k. That’s not very big, but on a mobile device, every byte counts. That’s why I decided to roll my own. My version is well under 2k. I can get this savings because I’m only building one slider with one action for one website. I’m not trying to write a plugin that does everything for everyone.

The first thing I decided when making my slider was what kind of transition I wanted. Since changing between slides is what it’s all about, this decision drives your coding strategy. I wanted the slides to move off to the right and the next slide to move with it to take its place: A traditional slide.

To determine how far to move my slides I had to get their widths and store this value in a variable:

var slider = $('.slider-holder'), slideWidth = slider.width()

Notice that I’m taking the width of my slider itself, rather than the width of the slides. That’s because my slider will be responsive, and since it’s on a mobile device it will fill the entire width of the device. I am planning on using a lazy load strategy, so I can’t be sure I actually have images to measure when the slider runs.

It’s very easy to make the slides move:

$(nextSlide).animate({ left: '+=' + slideWidth }, 1000

To make the current and next slide move together, I use “add”:

$(nextSlide).add(currentSlide).animate({ left: '+=' + slideWidth }, 1000

This works until you run out of slides. Some sliders clone the first and last slides to make an endless loop. I’m taking advantage of the fact that the slides are absolutely positioned and that only two are seen at a time (during transition). My scheme is to move the first slide onto the stage, transition it out to the right when the replacement slides in, then reset it back to the default position at the left when transition is complete.

I initialize the slides by sending all but the first one off the stage to the left.

$('li:not(:first-child)', slider).css('left', '-' + slideWidth + 'px');

If my current slide number is less than the total number I go onto the next slide; if not, I return to the first slide and reset my counter. (I stored my first slide as a variable because I need a constant reference point.):

slideN = ($(currentSlide).index()) + 1; if (slideN < slideCount) { nextSlide = $(currentSlide).next(); } else { nextSlide = firstSlide; } slideN = 0;

This is a brief overview of the technique. The complete code is in the pen below, including the code to put indicators below the slider.

For me the most interesting part of this project was the responsive aspect. Because a mobile user can change orientation on their phone, the slider has to be able to adapt on the fly to a new width and height. The slider responds to the viewport width and the slides rely on that parent for width. The difficulty is setting the proper height. The images do not recalibrate their height when their width changes because the parent’s height does not change.

If the slide width changes, the distance each slide must move has to be updated as well, since this is stored in a variable.

To solve this problem, I wrote a function that can be used to set the initial height, recalibrate the height of the images on orientation change and update the animation distance as necessary:

var doResHeight = function () { slideHeight = $('li:eq(0) img', slider).height(); $(slider).css('height', slideHeight + 'px'); slideWidth = currentSlide.width(); $('li', slider).not(currentSlide).css('left', '-' + slideWidth + 'px'); }; window.addEventListener("orientationchange", function () { doResHeight(); }, false);

One of the main features I wanted in my slider was a lazy loaded image, i.e. I didn’t want them slow down the initial page load. Images load on page render if they are referred to in the CSS or in the src attribute of an image element. Slider images on the site I built this for can run between 100-300k. Multiply that by 4 or 5 and you’ve easily got a megabyte. Even on a wifi connection you can see a lag—especially if your slider is the kind that waits for all the images to come in before organizing them and presenting itself.

Lazy loading techniques can be fairly sophisticated, but I chose a simple route. I use a small blank gif as my src placeholder and replace it with an real image src from the data attribute. I also have the choice of using my real image on the first slide instead of the blank gif if I want to make sure it always shows first. Otherwise, it’s likely the slider will start with the second image.

I put a simple spinner on the slide holder background. If the transparent gif (or nothing) is showing, the spinner is seen. If the slide images are in they cover it. No need to do any JavaScript listening, adding and removing.

See the Pen Slider with indicators by Connie Finkelman (@pixelslave) on CodePen.21122

I also did a version with fading instead of sliding. I used opacity as the animation. (jQuery has two useful helpers, “opacity: “toggle” and “fadeToggle()”, but they change both the opacity and the visibility and there is no toggle for visibility, so the slide would have stayed hidden if these were used.)

See the Pen Fader with indicators by Connie Finkelman (@pixelslave) on CodePen.21122

Ups, Downs, and Highlights

Recently I developed an incrementor/decrementor for a quantity input field. Normally I’d rely only on the built-in HTML5 functionality, but key stakeholders on the project were uncomfortable with the small size at which Mac OS rendered these, and asked for a custom solution.

HTML5 Number field

Mac vs. PC

The first step was to suppress the up/down arrows, which are called “spinners”.

input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; } input[type=number] { -moz-appearance: textfield; }

The next step was to create the buttons for the plus and minus indicators. A simple way to do this is to create two spans and style them accordingly. (Use “&ndash;” to get a nicer munus sign.) I was already using a web font with icon graphics, so all I had to do was add the appropriate class to get the indicators I wanted courtesy of Fontello and Font Awesome.

fontawesome

I placed a span before my number field with a class of “icon-minus-squared” and one after classed “icon-plus-squared”. That provided my indicators, to which I applied sizing, alignment and color to match my UI.

plus-minus

Finally I added a script to increase or decrease the quantity when the indicators were clicked. I used the sibling relationships to find and change my field value on click.

.next('input[type=number]') .prev('input[type=number]')

Everything worked as it should except for one really unsightly problem: In use, the tendency is to rapidly and repeatedly click the indicators. The browser reads this as a double click. The standard browser behavior on a double click is to select. Here’s what that looked like:

highlight

To fix that, I added this CSS to my indicator spans:

-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;

That solved the selection problem and completed the solution.

See the Pen WbaJjy by Connie Finkelman (@pixelslave) on CodePen.21122

Responsive Interactive Map

Interactive map of the world

Recently I was tasked with implementing an interactive world map as part of a global resorts website. The artist’s Photoshop comps made the task somewhat easier because they used a vector image for the map. This was a necessity for my implementation, since I intended to use SVG. In a responsive layout there was no other choice.

In a fixed-size layout it would have been possible to simply use absolute positioning to overlay PNG images on a background and use an image map to create the links and the rollover effect. This won’t work in a responsive layout, because image maps don’t scale. They don’t scale because their hotspot coordinates are expressed in pixels. Theoretically you could use percentages for the hotspots, except no major browsers understand percentage coordinates correctly, and all interpret percentage coordinates as pixel coordinates.

Drawing coordinates with SVG is the same amount of code, but unlike an image map SVG coordinates automatically scale to the parent dimensions.

Building the SVG

If I were doing a small map with simplified regional shapes I would have done the map entirely in SVG. However the map I was given was of the entire world and had an extreme amount of detail. Those details translated into additional coordinates, which would have greatly bulked up my file size, weighing in at 532k. I could not simplify them with Illustrator without losing the look of the map. Instead I made it an 8-bit PNG, at the largest dimensions I would need. It was 1476 × 723 and weighted 26k. I erased some of the smaller islands because they added unnecessary clutter and looked like dirt, rather than detail.

Next, I selected only the countries that would be active from my vector map and hid the rest. I didn’t delete them because I may need to add them back later as the client adds new resorts, and hidden layers don’t get included in the SVG export, so they won’t bulk up my file size. I ended up with a vector drawing that looked like this:

active areas of my map

I placed the geo indicators (vector graphics) where I needed them. I grouped each indicator with its country. The grouping is important, as SVG exports by layers, and I needed the indicators to be on the same layer as their countries for the rollover action:

map with indicators

I placed a rectangle on my map to act as an extension of the rollover state. Since on most of the countries the rollover text won’t fit on the country itself it must be placed outside the bounds of the country. That means you will loose the rollover when you try to get to it. The rectangle keeps the text contiguous with the country. I also used it to enlarge the active area on the smaller countries.

Draw a rectangle on map

I could also have added the text for each country name to the SVG in Illustrator and group it with the country, but I chose not to do this. Illustrator gives two export options for text: Outlined text (vectors) or SVG. Vectors would not have allowed me to easily edit the text later, for example if I needed a version of the map in Spanish. The SVG export option wasn’t much better. Due to the way Illustrator handles text, the SVG output looked like this:

<text xmlns="http://www.w3.org/2000/svg" class="cls-6" transform="translate(1778.94 265.36)"> <tspan class="cls-7">F</tspan> <tspan x="27.66" y="0">r</tspan> <tspan x="46.98" y="0">an</tspan> <tspan x="109.2" y="0">c</tspan> <tspan x="135.72" y="0">e</tspan> </text>

Technically, it was editable, but not easily. Instead, I decided to add my text after export to the SVG. Here is what the export pane looks like for Illustrator. (The “Font” setting is selected, but since there is no font on in my graphic it will not matter.)

S

I chose “Internal CSS” because my other choices were to have it inline with each element, which would have made it impossible to style all identical elements at the same time. I also chose to link my PNG file (the map background image) because otherwise it would have been embedded as a data URI. I think given the size of the PNG and the below-the-fold placement of my map this is a better choice in this case. Notice the globe icon with the orange square around it in the above image. Clicking this opens your SVG in the browser. From there, you can copy the entire implementation and paste it into your HTML page. You can also use the “Show Code” option, which will output it as a text document. You’re going to need one or the other, because editing will be required for the rollover states. You can use any text editor for this.

Editing the SVG

The artist’s vision required that when the user rolls over a country the name will show as a hyperlink that the user can click to go to a detail page for that country. This is done by adding text elements to the SVG and wrapping everything in a link. I position the text using x and y coordinates that I derive from the rectangle I put in earlier. My text position doesn’t exactly match my rectangle, but the adjustment was simple:

<a xlink:href="/france.html"> <path class="resort" >[SVG for country] /> <path class="geo-ind">[SVG for indicator] /> <rect x="746" y="104" width="170" height="45"></rect> <text class="title" x="765" y="137">France</text> </a>

I took the <style> block out of the SVG and added it to my external CSS, then I placed the SVG inside a parent set to scalable width, for example 100%. The SVG will scale with that parent, making it responsive. I completed the implementation by adding a hover state to my CSS and adjusting the colors (fills) of the SVG paths. Below is the final result:

See the Pen Responsive Interactive Map by Connie Finkelman (@pixelslave) on CodePen.21122

Accessible Custom Checkbox

animated checkbox

In an earlier post I explored custom styling of form selects. In this article I’m going to discuss how to make custom checkboxes to match those selects. Note that the same technique can be used for radios.

The first thing I think about is structure. I want everything wrapped in a label because if a label is associated with a check or a radio it can activate the element if it receives a click anywhere on it or in it. Next comes my check or radio and then a span to hold the label message. I need that span for two reasons: The first is that I need to put CSS :before content on it, which will be my replacement graphic or “glyph”. The second is because I need an element directly after the check or radio to respond to it’s state. When the element is checked I can refer to that state in my CSS and target its adjacent sibling to change the glyph in its :before content. I’m using Font Awesome for my glyphs in this demo, but typically I make my own by importing SVGs into Fontello.com.

With this scheme you have the option of removing all the custom styling and just going with the natural elements for mobile. This saves the weight of the font download and gives preference to the device’s native implementation, which I think is a better experience for the user.

See the Pen Accessible Custom Checkbox by Connie Finkelman (@pixelslave) on CodePen.21122

Accessible Responsive Pseudo-selects

Cris Coyier hearted this pen

If there’s one thing designers always want to style it’s form elements. They want them bigger and rounded and more colorful. That’s easy to achieve with CSS on most form elements, but some are more stubborn than others. The difficult ones are radio buttons, checkboxes and selects (dropdowns). I think this is because of the nature of the form element itself: They are the only HTML elements that actually do something and they come from the computer’s operating system. That’s one of the reasons they have so much cross-platform variation. Browsers customize them with their own internal styling, putting on an additional layer of interface. Making a custom style look good on all browsers and platforms is very tricky because instead of starting with an unstyled element your attacking something that’s already been styled twice.

We also have to consider accessibility. Many styling schemes take away the natural accessibility of the form elements, for example making them unresponsive to tabbing or other keyboard navigation. Many designers feel form labels create too much clutter and get rid of them as well. So when I got a style to implement recently that called for custom styling on the select element I wanted to replace the default select in such a way as to preserve the accessibility of the original HTML element.

A common replacement scheme for the select element is to use a div that reveals a list when hovered. This has the advantage of being extremely customizable, but it’s not accessible at all, first because it’s not tab-able, since it’s not an active element, and second because it is useless without JavaScript.

For custom styling, any block element will do, so instead of using a div I started with a label. The label held my default value for the select. Inside the label I placed a select element. Here’s a cool thing about selects: Even if you hide them, their children will still show on hover. I took advantage of that by placing my select over top of my label and setting them both to the same size. When the user hovers over the label they are actually hitting the select, which opens. I needed JavaScript to assign the value of the select option to the label on change, but this is purely a visual aid and doesn’t affect the state of the select, so an unsighted user will still be interacting with it in the usual way.

See the Pen Pseudo-selects by Connie Finkelman (@pixelslave) on CodePen.21122

Selects are a bit quirky in that they won’t take any custom sizing until you change their background color. That’s why my selects are set to a white background, even though they’re invisible. I needed that to make their height match the height of my labels.

Lessons from Failed Projects

Spend enough time in IT and you’ll see plenty of failed dev projects. Although there is a huge amount of wisdom to be gained from a failed project, I have never seen that benefit reaped by an organization. That’s really unfortunate, but it could easily be avoided. I want to begin by talking about how an organization identifies a failed project. Failure may seem like something that would be self-evident, but unfortunately it is not. That’s the first major reason organizations don’t learn from it: They don’t realize it happened. The fact is they often never correctly identify a failed project as a failure. How is that possible? Reason #1: Redefining Success As the project begins to fail, the organization lowers the bar and redefines success to be whatever the project deliverables are regardless of how far below the original requirements they fall. It’s like kids’ soccer when everyone goes home with a trophy. Reason #2: Denial In the Agile process there is a retrospective after each sprint. Part of that retrospective is discussing what went well and what didn’t. I’ve worked in companies where discussion of the negatives never took place, and other companies where criticisms were grudgingly allowed to be recorded during the retrospective, but discussion of them wasn’t. Criticism or even recognition of failure was taboo, which brings me to… Reason #3: Refusal to Blame Failure and blame go together, whether we like it or not. Many organizations are uncomfortable assigning the blame for failure on either their processes or their people. Process change is difficult, and there is often great resistance to it. In the typical organization, blame is not something most people are comfortable with on either the giving or receiving end, and in some workplaces it even violates the corporate culture. Reason #4: Escapism and Scapegoating When a project looks like it’s going to fail, those responsible often head for the door while their reputation is still intact. Managers cover themselves by firing those below them, or do a reorg to thwart accountability.   Project failures cost a lot of money. They cost the wasted salaries of those involved. They cause negative ROI and lost revenue when they underperform or fail at release. The most insidious cost—one that I believe is rarely counted—is the opportunity cost. It’s the benefit of positive revenue a success would have generated and the developer hours that could have been productive. Software has no intrinsic value, so it is often discarded when it doesn’t fulfill its requirements. I have never seen a failed software project refactored successfully. Refactoring can make it usable until it can be replaced, but I don’t believe you can repair your way to success. Successful software requires a clear design vision and sound architecture. Failed projects rarely have these and they can’t be retrofitted. As a developer it hurts to spend months of time on a project only to see it be rejected by the business owner or fail QA repeatedly. And it especially hurts when you knew it was going to fail before you wrote the first line of code! You might ask yourself why a developer wouldn’t push back at the start of a project that had failure written all over it, and the answer is simple: Corporate culture doesn’t like negativity. Positivity is a great thing and it makes everyone feel better, but that doesn’t mean negativity is a bad thing. Hearing the potential down-side of a proposed project while it’s still in the design phase can have huge benefits, the biggest of which is the ability to limit the damage of bad decisions to the design phase. The longer the project lives, the more time and energy have been invested in it, the harder it is to change course. Here’s a real-world example One of my coworkers was given a project to create a variation of an existing page for an A/B test. I went over the design with him and identified multiple problems in the UI design, in usability, in functionality and in implementation and integration with our existing code. The number of flaws was hardly surprising, since the design was provided by a data scientist rather than a UX expert, and had he had not received any input from anyone familiar with the code or the feature being modified. He had dashed out the design in a few hours, basing it on a feature he’d copied from someone else’s website. The feature he copied was not the same feature we were implementing. They just looked similar. I knew the project would fail if developed as designed. We both should have pushed back on the design immediately, but we didn’t. All the problems I identified before any code was written became obvious as soon as development began. The result was that the project had to go through many cycles of redesign, redevelopment and retesting until it actually worked. Instead of the project taking the original estimate of one week to develop, it took four months! And it looks and behaves like the hodge-podge it is. As an A/B test it underperformed the original experience. In other words, it was a total fail. This failure occurred for one reason: No one called out the flawed design. The developer tasked with the design was new to the organization and he wanted to make a good impression. He didn’t feel confident enough to express his opinion. I had the experience and confidence to push back, but it’s because I had experience that I didn’t. I had previously pushed back on a design proposed by this same business owner, who happens to be a V.P. in the organization. The result was that I was immediately pulled off the project and it was reassigned to someone else. The project had to be completely redesigned for all the reasons I identified, but that did not vindicate me or buy forgiveness. I was never given another project and was relegated to working bugs and doing routine updates from that point on—the developer equivalent of being sent to the gulag. My “negativity” virtually ruined my career at the organization. No way I was going to speak out again, and based on my experience it wouldn’t have made a difference. And that’s a real shame. Every organization I’ve ever worked for has spent tons of money teaching me and other developers how to avoid failure with many painful real-life lessons. Yet organizations refuse to recoup that investment by actually listening to those of us who learned the hard way when we warn them in advance of how a project can or will fail. How can this be changed? “More hurry, less speed” Business owners and dev managers are under pressure to produce results, so they rush projects through the design phase. I have never worked on a project where one hour of design didn’t pay me back ten-fold in the dev phase. My advice is to take the time to rigorously criticize a design while it is still only a design. Do your best to tear it down. Search tirelessly for ways to improve it. A great design can stand up to these assaults and can get stronger by receiving input. A fatally flawed design will end up where it belongs—in the garbage can instead of in dev. Thinking hard and striving for excellence are difficult, but great results don’t happen by magic during the dev phase. The design phase is not the place to be lazy! I say take as much time as you need to get it right. Seniority doesn’t equal expertise I’ve been consistently overruled by senior management whose only expertise is their personal use of the web. Unfortunately in corporate America, there tends to be the attitude that everyone’s opinion counts, but that an opinion matters more if it comes from someone higher up the chain. What they fail to grasp is that while the customer service director may have an opinion, the developer may actually be speaking from knowledge, expertise and experience. So while some people are debating opinions, others are trying to convey facts. The lesson here is to listen to the people who know what they’re talking about no matter where they are on the corporate ladder, and most importantly: Don’t try to make non-technical stakeholders into dev managers. Really. I could write volumes on that one mistake.

Creating Beautiful HTML Style Guides

When working on websites that will undergo continuous editing and updating by a team, it is important that the creators of the website pass on their front-end HTML and CSS architecture to those who will be working on the site post-launch. The best way to do this is with a style guide.

A style guide insures that the interface will remain consistent by specifying colors, layout measurements and structures. But it performs a more important function: It acts as a catalog of existing styles and modules that can be recreated in the site simply by applying the HTML markup and CSS classes specified in the guide. Rather than combing through thousands of lines of CSS and HTML to find a matching style a developer can simply cut and paste the desired markup directly from the style guide.

Corporate style guides are typically PDF or PowerPoint documents. An HTML style guide is created using the same HTML and CSS as the website, so it exists in the same medium as the site. That gives a much more accurate presentation than a version created for print or compiled from static screen shots. It is sometimes called a “living” style guide, since it uses the same CSS file as the website and evolves with the site’s CSS, automatically updating itself when the CSS changes.

Living style guides are generated from a combination of CSS and markup/markdown. There are two main style guide generators that I’ve worked with: Styledocco and KSS, which stands for “Knyle Style Sheets”. They are similar in several ways:

  • They generate their style guides from CSS.
  • They can be used with files having the .css, .less, .scss, .sass and .styl extensions. 
  • They are run from the command line using Ruby and Node.js, making them best suited to the Mac.
  • They are very poorly documented!

Styledocco and KSS differ in one key respect: KSS uses a template system that allows for more customization in the look and feel of the generated style guide. For that reason I prefer it, and will focus on it exclusively for the remainder of this article.

It can be extremely frustrating getting started with KSS due to the sparse documentation and the fact that it is run via Terminal, which can be a very foreign and daunting interface for those spoiled by Mac’s excellent GUI. This article will attempt to demystify the process and save you the hours of head banging I went through to get it all figured out. Instructions apply to Mac computers. (I’m not even sure it’s possible to do this on a PC.)

Installation

Verify Ruby

The first step is to make sure you have Ruby installed. Ruby is part of Mac’s basic equipment, so start by opening the Terminal app. (Type “Terminal” into your Mac’s Spotlight search field to find it.) At the command prompt ($) type in:

ruby -v

That will confirm that you have Ruby and tell you which version you have. Unless you haven’t been updating your Mac OS, you should be fine. If not, you should update.

Install Node.js

Download Node.js. This is a simple .pkg file that you can click and install like any other Mac app. It includes NPM, which is the Node Package Manager. You need it to install the CSS preprocessors for Sass, Less and Stylus.

Optional: Install CSS Preprocessor

I’m using Less (dynamic CSS) for my style guide, so I’m going to use NPM to install the Less preprocessor. (If you’re only using CSS files you can skip this part.) You must be a “super user” to install from Terminal, which is Mac’s way of making sure you enter your password as you would with any other software installation. The easy way to do that is to start your installation commands with the word “sudo”. Paste the following line into your terminal after the prompt and hit the return key:

sudo npm install -g less

You will be prompted for your password. After you authenticate the installation will begin.

If you are using Sass, I recommend starting by installing Compass, which is great for creating responsive grids and brings in the Sass preprocessor as a dependency.

Install KSS

In your Terminal command line paste the following and hit the “return” key:

sudo npm install -g kss

You’ll want a sample template to get you started. Create a folder in your home directory (the one with your Mac user name and the house icon next to it) and name it “kss-test”. Go back to the Terminal, paste the following and hit the “return” key:

kss-node --init

This command installs a KSS template. (It’s supposed to accept the name of a folder to install into, but that doesn’t work. Instead it always installs directly into your home directory.) The template it creates is a folder called “styleguide-template”. Find it and move it into the “kss-test” folder you created.

You’ll notice in your Terminal window that KSS has output instructions for using this template. For me it was

>kss-node [sourcedir] –template "/Users/connief/styleguide-template"

That’s really cryptic and we’re just going to ignore it, since we moved the file anyway and we need a lot more assets to actually make a style guide.

Go into your “kss-test” folder. You will already have moved the styleguide-template directory here, which contains a subdirectory and a number of files, but you’ll also want to create the additional folders (css, styleguide, and styleguide/public) and files (style.less) shown below to result in the following directory structure:

KSS Directory Structure

Make sure you name your Less file “style.less”. If you’re not using Less, just call it “style.css”. But make sure to name it “style”. This name is special to KSS and, although the documentation fails to mention it, nothing will work if you don’t have a file of this name in your css directory. If you want to keep your existing CSS or Less files, just import them all into the “style” file using the @import declaration. For Less, you would use “@import “myless.less”;” and for CSS you would use “@import url(“mycss.css”);”.  (In a CSS file all @import declarations have to be at the very top of the file before anything else!)

Generating the Style Guide

Preparing your CSS

Open “style.less” and type in some simple Less (or CSS), for example:

@button-color: #f00;
input {
background-color: @button-color;
}

Now it’s time to make the actual style guide. This is done by putting instruction inside the Less or CSS file in a comment block. It can be above or below the CSS. I’m going to put in a button style:

/* Button Buttons are action items. Markup: <input type="button" value="Red" /> Styleguide 1 */

Whitespace is important here! If you don’t put a blank line between each section it won’t output correctly. The first line is my header, the second is my description. “Markup:” causes the block below to be treated like code in the style guide, and the final line (Styleguide 1) creates the menu.

My “style.less” file now looks like this:

/* Button Buttons are action items. Markup: <input type="button" value="Red" /> Styleguide 1 */ @button-color: #f00; input { background-color: @button-color; }

Generating the Style Guide from Terminal

Now we generate the style guide. Go back to Terminal and past in the line below, type a space after it, but don’t hit the return key yet:

kss-node kss-test kss-test/styleguide --template

You also need to add the location of the template your using (the directory KSS created for you when you ran the –init command). It can be a pain finding the actual path to a folder or file on Mac when you’re using the Terminal, then typing it in correctly. Instead, use Mac’s great drag and drop functionality: Make sure you typed that space after  ”–template”, then drag the “styleguide-template” folder from your “kss-test” directory onto the Terminal window! That will write the correct path to your directory into the Terminal command, like so:

kss-node kss-test kss-test/styleguide --template /Users/connief/kss-test/styleguide-template

and will automatically insert a space after the path. Type in your CSS format, e.g. “less” or “css” with two dashes in front:

kss-node kss-test kss-test/styleguide --template /Users/connief/kss-test/styleguide-template --less

Add a space, then drag your “style.less” file into Terminal to add its path:

kss-node kss-test kss-test/styleguide --template /Users/connief/kss-test/styleguide-template --less /Users/connief/kss-test/css/style.less

Now hit the return key to execute this command. You will get Terminal output telling you the operation was a success and your style guide was created. But at the bottom of the output you will see this error:

generating styleguide overview
...no styleguide overview generated: ENOENT, no such file or directory 'kss-test/styleguide.md'

KSS uses a configuration file to make an overview of the document—a landing or introductory page. Without this configuration file you won’t have a main page. Open a text editor (such as TextEdit) and paste the following into a new plain text document and save it as “styleguide.md” inside your “kss-test” folder:

#Hello styleguide
My Online Style Guide

We’ll need to regenerate the style guide to include this file. Here’s a shortcut: Go back to Terminal and type two exclamation marks (!!) at the command prompt and hit the “return” key. That will rerun your previous command, which will regenerate your style guide. (Be sure to save your build command in a text document within your “kss-test” folder so you can re-enter it easily in Terminal when you start a new session.)

Navigate to your “kss-test” folder, open the directory “styleguide” and locate the “index.html” file and open it in a browser. Et voilà! Behold your beautiful style guide.

Customizing the Style Guide

If you want to customize the style guide you can do so with the template and its CSS. (This may be necessary if you have styles coming in from your CSS that override elements of the same name in the template.) Never work in the “styleguide” directory. Its contents get overwritten each time the style guide is generated and your work will be lost. Make your changes in the “styleguide-template” directory. Place any CSS changes you want to make to the template’s CSS in the “kss.less” file. If you don’t know Less, don’t worry. Standard CSS works fine in Less files—just be careful not to make a syntax error, as even an error as trivial as a missed semicolon can cause a Less file to not compile, resulting in a blank file.

To customize the template itself, open the “index.html” file in an HTML editor and edit it as you would any HTML file. You can import a logo, change the imported Google font, add a reference to an additional CSS file or change the markup. Be careful of the double brackets. That’s where the dynamic content comes in and you probably don’t want to mess with that.

Final Thoughts

It is not always possible to integrate style guide generation into your actual web project. If your web project is on a Mac then it’s easy to incorporate the style guide generation into your build process, making it a truly living style guide. If you’re working in the .Net environment on a PC you’ll have to periodically export your CSS and build the style guide outside the project. If that’s the case you may be better off using “style.less” for the style guide comments and for importing your Less files, rather than cluttering the CSS you’re using for development with them. If you do keep the comments in your working CSS files, be sure to set your Less preprocessor to strip them out before you go to production to keep your CSS file size as low as possible.

Lose My Number

iOS has a handy built in feature: automatically sensing phone numbers and making them active links. When you touch them you get a dialog to make a call to that number. Unfortunately this can cause problem with your layout and your pages.

Layout

When iOS makes a number dial-able it enlarges it, as in this example:
Desktop iPhone
nodial dial
iOS has changed the source code of the document by injecting data attributes around the phone number as shown in the before and after code samples below:
Before: Call 800-585-5055
After: Call <a href = “tel:800-555-5555” x-apple-data-detectors=”true” x-apple-data-detectors-type=”telephone” x-apple-data-detectors-result=”1”>800-555-5555</a>

Normally, this would only require that you be aware of the transformation and style it appropriately, as below:

redial

Wrong Number

The problem arises when iOS makes a mistake, which is quite common. It often interprets other numbers, like serial numbers, skus and order numbers as phone numbers. The problem then becomes how to remove the dial link. This can be achieved by adding this meta tag to the head of your document:
<meta name="format-detection" content="telephone=no">

The problem with that is that it will un-link any phone numbers on your page as well. Since enterprise websites use templates for headers and footers (where the customer service number is usually located) adding this will turn off dialing throughout your website.

A quick easy solution for this problem is to add a “#” in front of non-phone numbers. Unfortunately, it must be immediately adjacent to the digits. If you try to wrap it in a span or other markup in the hope of hiding it with CSS it will not work. Another alternative is to wrap the number in an anchor and mark it up like this, where [digits] is replaced with your non-dialable number:
<a href="#" x-apple-data-detectors="false">[digits]</a>

Unfortunately this requires that you have a non-working anchor on your number.