You are viewing the Articles published in

Styling HTML5 placeholder attribute text

HTML5 placeholder attributes can be leveraged to provide a convenient means of indicating required input formats.

By default, browsers typically implement placeholder attributes as light-grey text. As with all default user agent styles, one will feel compelled to define custom selectors to provide application specific styles to elements, placeholder attributes included.

Styling Placeholder Text

Styling placeholder attributes on input and textarea elements is rather simple; however, one should take care to keep style declarations limited to those of a textual nature; e.g. color, font-size, font-family, etc.

As it stands, HTML5 placeholder attributes can be styled with pseudo-elements in WebKit, and pseudo-classes in both Firefox and IE10; all of which (currently) require vendor prefixes.

Placeholder attribute text can be styled for all supported input element types (text, search, url, tel, email, and password) as follows:

As can be seen, defining styles for placeholder attribute text is quite simple, and such styles can be employed to add subtle enhancements to form elements in modern web apps quite nicely.

Pseudo-abstraction in Backbone

As has been mostly disseminated, JavaScript, being a dynamic, prototypal language, affords developers the ability to design outside the rigid confines inherent to statically typed languages. Interestingly, perhaps even somewhat paradoxically, this same flexibility also allows for programmatically simulating specific features commonly found in statically typed languages, if desired.

While JavaScript does not have a traditional type system, nor does it provide traditional constructs by which user defined types are specified, it is still, necessarily so, a common and desirable design goal to implement a system with the notion of classes in order to provide data types which encapsulate domain logic and facilitate reuse; both of which being key design attributes which help mitigate the complexity of large applications.

Nearly all JavaScript MV* frameworks provide such facilities, and do so in a consistent and convenient manner; most of which allowing for practical circumvention of the prototype system almost entirely. It is also worth noting that while most libraries themselves are generally implemented in the succinct and terse, large applications typically call for a more traditional object oriented design, while also being prudent to do so in alignment with the conventions and idioms particular to JavaScript itself.

Abstraction

At times it will be necessary to design a system with reusable abstractions. In fact, it is quite hard to imagine a modern SPA of even marginal complexity as being maintainable without some level of base class functionality.

For instance, it can be particularly useful to implement base Models and Collections which provide general functionality common amongst all Models and Collections; such as the parsing and appropriate routing of service API exceptions to error callbacks, and successful service results to success callbacks, and so forth.

Since such base classes generally do not provide any concrete behaviors themselves (hence the abstraction), they are of considerable value, specifically when reused amongst various large scale, distributed projects; and, from a design perspective, it is often important for one to ensure such classes are only used as intended.

While one can convey the intended usage of a base class easily enough simply by means of comments alone, indicating their usage as such (and that is quite fine if you prefer), it is also just as easy to ensure base classes are only used as intended programmatically by implementing a simple conditional which checks an instance’s constructor against the base class’ constructor function. For example (in the context of backbone, though any framework applies):

Then, one can simply extend the base class, invoking defaults as needed:

Concluding Thoughts

Like many in the JavaScript community, I, too, am of the opinion that JavaScript should not be made to reflect that which is common to other languages simply for the sake of familiarity; but rather, one should be prudent to leverage the flexibility inherent to the language itself, and this example serves as a demonstration of how such flexibility can be utilized to provide what a specific design calls for at the discretion of the developer.

Natural Box Model Sizing

As Web Developers, the benefits to be afforded by simply taking the time to aquire a fundamental understanding of CSS layouts can not be overstated; for it is these very skills that provide the basis from which designs can be achieved with ease; making the task of designing the Web an enjoyable, and rewarding experience. Conversely, without an understanding of core concepts, one is certain to spend a significant amount of time – often in frustration – attempting to achieve a desired layout.

CSS Layout Fundamentals

In the context of CSS layouts, such fundamental concepts to be considered (in no particular order) include: document flow, positioning, display types, off-sets, floats, overflows, clears, and the like; and, as the title of this article suggests, the Box Model.

The Box Model

I emphasize the importance of the Box Model here in particular, as the default sizing of elements with respect to the Box Model is quite the opposite of what one might expect.

For example, consider the following:

As many would assume, any element with the .box class would render with a 1px border and 20px of padding, at exactly 200x200px. However, by default, this is not how elements are sized, but rather, the actual size of a rendered element is calculated to include both borders and padding in addition to width and height, the calculation for which essentially being:

This results in nearly all elements (form elements notwithstanding) being measured quite differently then one might have expected. Thus, in the example of the .box class mentioned above, rather than elements being rendered at the expected 200x200px, as defined by their respective width and height properties, they would instead be rendered at 242x242px.

.box content-box

One could argue that in the majority of cases, this is neither what is expected nor what is desired. Fortunately, CSS3 offers the very useful property box-sizing, which can be used to override the default sizing of elements (content-box), and allow for sizing them more naturally simply by setting box-sizing to border-box:

By setting box-sizing: border-box, elements with the .box class will render at the expected size, 200x200px, as defined by the width and height properties; with the content area being 158px, padding 40px, and border at 2px.

.box border-box

Box-sizing Global Resets

Paul Irish has a great solution for this very problem whereby a global reset is used to ensure all elements are sized with border-box. I highly recommend this approach as it provides a starting point from which all elements will be sized “naturally”. The reset is simple, safe, and works perfectly well in supported browser:

CSS3 background-clip and background-origin

The background-clip and background-origin properties, respectively, can both be used in tandem with box-sizing; each accepting the same values as that of box-sizing, allowing for related control of how backgrounds are displayed for elements with respect to the Box Model.

Concluding Thoughts

It was quite some time ago while trying to understand how the sizing of elements is determined in more detail that I first learned of the box-sizing property. In the time since, I have been using box-sizing:border-box with great results and have really come to appreciate this property.

And so, if you haven’t leveraged box-sizing: border-box in your designs yet, I strongly recommend giving it a try, as you will likely find it to result in more “naturally” sized elements.

Windows 8 Web App Start Screen Tiles

Having had to certify a Web Application for use on the HTC Windows Phone 8X, as well as the Microsoft Surface Tablet, I was interested in providing a Start Screen Tile similar to that of the application’s current iOS Web Clip Icon. Not the least, the new Tile Based UI in Windows 8 presents significant UX improvements over that which has been seen in previous versions of Windows; thus, I felt compelled to take advantage of the new UI from a Web Application context.

Conveniently, adding a Windows 8 Start Screen Tile (Pinned Site) can be accomplished quite easily, and in much the same way as that which is used when specifying a Web Application to run in standalone-mode on iOS. To do so, one need only add additional meta elements with a name attribute of msapplication- followed by a specific Tile property. A standard content attribute can then be used to provide the corresponding attribute value.

For example, a Tile can be defined with a specific color using msapplication-TileColor:

Likewise, a specific Tile image can be provided using msapplication-TileImage:

Note: Tile images should be 144x144px, in .png format (transparent).

This site, for instance, utilizes both of the above:

While creating and defining a Start Screen Tile is simple enough, Microsoft also provides a handy Web based utility which allows for automating the Pinned Site creation process by generating a selected Tile Image in the correct dimensions, and providing the corresponding source at www.buildmypinnedsite.com

Test First Workflow – A Short Story

As a depiction of the typical approach taken when solving a problem with Test First practices in mind, below is a brief excerpt from a recent conversation with a colleague who inquired as to how one generally goes about solving a problem using Test First methodologies. My explanation was rather simple, and read somewhat like a short story, though I describe it as being more of a step by step process from a Pair Programming perspective.

The general workflow conveyed in my description, while brief, covers the essentials:

  1. We have a problem to solve.
  2. We discuss the problem, asking questions as needed; then dig a bit deeper to ensure we understand what it is we are really trying to solve; and, most importantly, why.
  3. We consider potential solutions, identifying those most relevant, evaluating each against the problem; then agree upon one which best meets our needs.
  4. We define a placeholder test/spec where our solution will be exercised. It does nothing yet.
  5. We implement the solution in the simplest manner possible, directly within the test itself; the code is quite ugly, and that is perfectly fine, for now. We run our test, it fails
  6. We adjust our implementation, continuing to focus solely on solving the problem; all the while making sure not to become too distracted with implementation details at this point.
  7. We run our test again, it passes. We’re happy, we’ve solved the problem.
  8. We move our solution out of the test/spec to the actual method which is to be implemented, which, until now, had yet to exist.
  9. We update our test assertions/expectations against the actual (SUT). We run our test, it passes.
  10. We’re happy, we have a working, tested solution; however, the implementation is substandard; this has been nagging at us all along, so we shift focus to our design; refactoring our code to a more elegant, performant solution; one which we can be proud of.
  11. We run our test again, it fails. That’s fine, perhaps even preferable, as it verifies our test is doing exactly what is expected of it; thus, we can continue to refactor in confidence.
  12. We adjust our code, continuing to make design decisions and implementation changes as needed. We run our test again, it passes.
  13. We refactor some more, continuing to focus freely, and without worry on the soundness of our design and our implementation. We run our test again, it passes.

Rinse and Repeat…

While the above steps are representative of a typical development work-flow based on Test First processes, it is worth noting that as one becomes more acclimated with such processes, certain steps often become unnecessary. For example, I generally omit Step #5 insofar as implementing the solution within the test/spec itself is concerned; but rather, once I understand the problem to be solved, I then determine an appropriate name for the method which is to be tested, and implement the solution within the SUT itself, as opposed to the test/spec; effectively eliminating the need for Step #8. As such, the steps can be reduced down to only those which experience proves most appropriate.

Concluding Thoughts

Having become such an integral part of my everyday workflow for many years now, I find it rather challenging to approach solving a problem without using Test First methodologies. In fact, attempting to solve a problem of even moderate complexity without approaching it from a testing perspective feels quite awkward.

The simple fact is, without following general Test First practices, we are just writing implementation code, and if we are just writing implementation code, then, in turn, we are likely not thinking through a problem in it’s entirety. Consequently, it follows then that we are also not thinking through our solutions in their entirety, and hence our designs. Because of this, solutions feel uncertain, and ultimately leave us feeling much less confident in the code we deliver.

Conversely, when following sound testing practices we afford our team and ourselves an unrivaled sense of confidence in terms of the specific problems we are solving, why we are solving them, and how we go about solving them; from that, we achieve a concerted understanding of the problem domain, as well as a much clearer, holistic understanding of our designs.

Simplifying Designs with Parameter Objects

Recently, while reading the HTML5 Doctor interview with Ian Hickson, when asked what some of his regrets have been over the years, the one he mentions, rather comically so as being his “favorite mistake”, also happened to be the one which stood out to me most; that is, his disappointment with pushState; specifically, the fact that of the three arguments accepted, the second argument is now ignored.

I can empathize with his (Hixie’s) frustration here; not simply because he is one of the most influential figures on the web – particularly for his successful work surrounding CSS, HTML5, and his responsibilities at the WHATWG in general – but rather, it is quite understandable how such a seemingly insignificant design shortcoming would bother such an obviously talented individual, especially considering the fact that pushState's parameters simply could not be changed due to the feature being used prior to completion. Indeed, the Web Platform poses some very unique and challenging constraints under which one must design.

While the ignored pushState argument is a rather trivial issue, I found it to be of particular interest as I often employ Parameter Objects to avoid similar design issues.

Parameter Objects

The term “Parameter Object” is one I use rather loosely to describe any object that simply serves as a wrapper from which all arguments are provided to a function. In the context of JavaScript, object literals serve quite well in this capacity, even for simpler cases where a function would otherwise require only a few arguments of the same type.

Parameter Objects are quite similar to that of an “Options Argument” – a pattern commonly implemented by many JavaScript libraries to simplify providing optional arguments to a function; however, I tend to use the term Parameter Objects more broadly to describe a single object parameter from which all arguments are provided to a function, optional arguments included. The two terms are often used interchangeably to describe the same pattern. However, I specifically use the term Options Argument to describe a single object which is reserved exclusively for providing optional arguments only, and is always defined as the last parameter of a function, proceeding all required arguments.

Benefits

Parameter Objects can prove beneficial in that they afford developers the ability to defer having to make any final design decisions with regard to what particular inputs are accepted by a function; thus, allowing an API to evolve gracefully over time.

For instance, using a Parameter Object, one can circumvent the general approach of implementing functions which define a fixed, specific order of parameters. As a result, should it be determined that any one particular parameter is no longer needed, API designers need not be concerned with requiring calling code to be refactored in order to allow for the removal of the parameter. Likewise, should any additional parameters need to be added, they can simply be defined as additional properties of the Parameter Object, irrespective of any particular ordering of previous parameters defined by the function.

As an example, consider a theoretical rotation function which defines five parameters:

Using a Parameter Object, we can refactor the above function to the following:

Should we wish to remove a parameter from the function, doing so simply requires making the appropriate changes at the API level without changing the actual signature of the function (assuming of course, there are no specific expectations already being made by calling code regarding the argument to be removed). Likewise, should additional parameters need to be added, such as a completion callback, etc., doing so, again, only requires making the appropriate API changes, and would not impact current calling code.

Additionally, taking these potential changes as an example, we can also see that with Parameter Objects, implementation specifics can be delegated to the API itself, rather than client code insofar that the provided arguments can be used to determine the actual behavior of the function. In this respect, Parameter Objects can also double as an Options Argument. For example, should the arguments required to perform a 3D rotation be omitted from the Parameter Object, the function can default to a 2D rotation based on the provided arguments, etc.

Convenience

Parameter Objects are rather convenient in terms of there being less mental overhead required than that of a function which requires ordered arguments; this is especially true for cases where a function defines numerous parameters, or successive parameters of the same type.

Since code is generally read much more frequently than it is written, it can be easier to understand what is being passed to a function when reading explicit property names of an object, in which each property name maps to a parameter name, and each property value maps to parameter argument. This can aid in readability where it would otherwise require reading the rather ambiguous arguments passed to a function. For example:

With Parameter Objects it becomes more apparent as to which arguments correspond to each specific parameter:

As mentioned, if a function accepts multiple arguments of the same type, the likelihood that users of the API may accidentally pass them in an incorrect order increases. This can result in errors that are likely to fail silently, possibly leading to the application (or a portion thereof) becoming in an unpredictable state. With Parameter Objects, such unintentional errors are less likely to occur.

Considerations

While Parameter Objects allow for implementing flexible parameter definitions, the arguments for which being provided by a single object, they are obviously not intended as a replacement for normal function parameters in that should a function need only require a few arguments, and the function’s parameters are unlikely to change, then using a Parameter Object in place of normal function parameters is not recommended. Also, perhaps one could make the argument that creating an additional object to store parameter/argument mappings where normal arguments would suffice adds additional or unnecessary overhead; however, considering how marginal the additional footprint would be, this point is rather moot as the benefits outweigh the cost.

A Look at pushState’s Parameters

Consider the parameters defined by pushState:

  1. data: Object
  2. title: String
  3. url: String

The second parameter, title, is the parameter of interest here as it is no longer used. Thus, calling push state requires passing either null or an empty String (recommended) as the second argument (i.e. title) before one can pass the third argument, url. For example:

Using a Parameter Object, pushState could have been, theoretically, implemented such that only a single argument was required:

  1. params: Object
    • data: Object
    • title: String
    • url: String

Thus, the ignored title argument could be safely removed from current calling code:

And simply ignored in previously implemented calls:

As can be seen, the difference between the two is quite simple: the specification for pushState accepts three arguments, whereas the theoretical Parameter Object implementation accepts a single object as an argument, which in turn provides the original arguments.

Concluding Thoughts

I certainly do not assume to understand the details surrounding pushState in enough detail to assert that the use of a Parameters Object would have addressed the issue. Thus, while this article may reference pushState as a basic example to illustrate how the use of a Parameter Object may have proved beneficial, it is really intended to highlight the value of using Parameter Objects from a general design perspective, by describing common use-cases in which they can prove useful. As such, Parameter Objects provide a valuable pattern worth considering when a function requires flexibility.