CategoryCode

It’s all about the “Programming Motherf_cker!”

Demythstifying Web Components

The following is an attempt to stomp out the seemingly endless FUD that circulates about Web Components, most of which is purely manufactured by attacking tangential, opinionated choices of frameworks that happen to use Web Components in a way that differs from the opinions of other frameworks.

Level Setting

Don’t let me catch you claiming a Web Component is anything but the following, or I’ll send Kam Chancellor to lay you out:

Web Components are an amalgam of APIs from two W3C specs (Custom Elements and Shadow DOM) that enable the creation of encapsulated, declarative, custom elements, which serve as standard, reusable, interoperable vehicles of discrete, stateless functionality.

Myth 1: “Web Components are at odds with Framework X”

This is probably the most fallacious statement about Web Components.

Continue reading

S(GH)PA: The Single-Page App Hack for GitHub Pages

SPA woes

For some time now I have wanted the ability to route paths for a gh-pages site to its index.html for handling as a single-page app. This ability is table stakes for single-page apps because you need all requests to be routed to one HTML file, unless you want to copy the same file across all your routes every time you make a change to your project. Currently GitHub Pages doesn’t offer a route handling solution; the Pages system is intended to be a flat, simple mechanism for serving basic project content.

If you weren’t aware, GitHub does provide one morsel of customization for your project site: the ability to add a 404.html file and have it served as your custom error page. I took a first stab at doing an SPA hack by simply copying my index.html file and renaming the copy to 404.html. Turns out many folks have experienced the same issue with GitHub Pages and liked the general idea: https://twitter.com/csuwildcat/status/730558238458937344. The issue that some folks on Twitter correctly raised was that the 404.html page is still served with a status code of 404, which is no bueno for crawlers. The gauntlet had been thrown down, but I decided to answer, and answer with vigor!

One more time, with feeling

After sleeping on it, I thought to myself: “Self, we’re deep in fuck-it territory, so why don’t I make this hack even dirtier?!” To that end, I developed an even better hack that provides the same functionality and simplicity, while also preserving your site’s crawler juice – and you don’t even need to waste time copying your index.html file to a 404.html file anymore! The following solution should work in all modern desktop and mobile browsers (Edge, Chrome, Firefox, Safari), and Internet Explorer 10+.

Template & Demo: If you want to skip the explanation and get the goods, here’s a template repo (https://github.com/csuwildcat/sghpa), and a test URL to see it in action: https://csuwildcat.github.io/sghpa/foo/bar

Continue reading

A Renewed Call for App-to-App Interaction APIs

Cow, come in cow

The battle ground of app-to-app interaction history is littered with abandoned ideas, half-solutions, and unimplemented APIs. The current, consumer/provider interaction paradigm for apps and services is a mess of one-off, provider-defined systems that each use their own transaction mechanisms and custom data structures. This makes it hard to do simple things across N providers, like save something to a user’s preferred storage service without jumping through provider-specific code and UX hoops.

I’d like to restart the conversation about bringing legit, app-to-app interaction APIs to the Web. There have been past spec attempts, namely Web Activities and Web Intents, but I’ll argue that while they get a lot right, they all fail to deliver an A+ solution.

Continue reading

Element Queries, From the Feet Up

Everybody’s looking for Element Queries

What are Element Queries? At a high level, I’d describe them as pure, unfiltered, rocket fuel for hyper-responsive layouts and components. More technically, they are Media Queries scoped to individual elements. Element Queries would allow you to attach Media Query break-points based on the dimensions and characteristics of an element itself, instead of the page’s viewport.

Developers have wanted Element Queries for a long time. Here’s a list of articles that convey the need, along with a few attempts to make them real:

Continue reading

CSS Selector Listeners

The following article explores a new event mechanism that I like to call CSS Selector Listeners. Selector listeners are completely bad ass, and sufficiently indistinguishable from magic, as you will soon find out.

Rise of the Mutants

Developers recently were empowered with a new way to listen for changes in the DOM: DOM Level 4 Mutation Observers. Mutation Observers emit fairly general events that tell you basic things, like when a new element has entered the DOM, or an attribute has changed on an element or subtree you are observing.

As a result of their relatively low detail resolution, developers have created libraries to help make Mutation Observers more useful for developers. Rafael Weinstein of Google recently introduced a library called Mutation Summary, which lets you watch the DOM through the lens of a limited subset of CSS selectors using a combination of Mutation Observers and its own custom logic layer to filter and interpret mutation events. The concept of listening to selector matches is intriguing because selectors inherently require the parser to quickly assess complex DOM conditions and perform selector-related logic to check for matches. Having the ability to listen for when selector states become active would be a powerful tool indeed!

A Hidden World of Events

Mutation Summary is pretty cool, but what if I told you there was a hidden world of arcane CSS selector event magic living in your browser that offered unlimited, detailed insight into the state of the DOM? Well there is, and technically there always was, in every style sheet you’ve ever written. All we needed was the right key to access this world…well, a Keyframe, to be exact.

Piggybacking the Parser, with Keyframes

I recently posted a method for using CSS Animation Keyframes to detect node insertions via the animationstart event of a dummy keyframe animation. Now let’s take a second to realize what this hack really is at its core: the ability to listen for any selector-based matches the CSS parser makes anywhere in the DOM. The Selector Listener code I’ve developed provides two methods, addSelectorListener and removeSelectorListener. These methods are available at both document and element level, and allow you to listen for any selector match, regardless of complexity. Once the parser detects a matched selector, the event bubbles up the DOM from the matched target element to the element or document the selector listener is attached to. Here’s what it looks like in action:

// Some action to perform when a match occurs
var sequenceMatch = function(){
  alert("Selector listeners, they're easy as A, B, C!");
};

// Attaching your selector listener to the document or an element
document.addSelectorListener('.one + .two + .three', sequenceMatch);

// Remove the selector listener when it is no longer needed
document.removeSelectorListener('.one + .two + .three', sequenceMatch);

The Goods: Code & Demo

The code that provides all this new hotness, as well as more examples of what’s possible, is available on Github here: SelectorListener Code Repo

You can also play around a bit with this demo page: SelectorListener Demo

I Want a DAMNodeInserted Event!

Have DOM Level 3 Mutation Events got you down?

There’s a long, sordid history behind DOM Level 3 Mutation Events. They’re basically the DOM Event equivalent of crack for developers: a ridiculous high of programmatic, dynamic handling of DOM manipulation, with a crash of endless, unavoidable, performance-destroying event evaluation.

John Resig detailed the plight of DOM Mutation Events in a mailing list thread, circa 2009:

Yes, DOM mutation events already exist (in Firefox and Opera – fairly reliably – and dicey in Safari). They have a huge problem, though:

They absolutely cripple DOM performance on any page which they’re enabled.

Firefox, for example, when it realizes that a mutation event has been turned on, instantly goes into an incredibly-slow code path where it has to fire events at every single DOM modification. This means that doing something like .innerHTML = “foo” where it wipes out 1000 elements would fire, at least 1000 + 1 events (1000 removal events, 1 addition event).

Mutation Events have since been deprecated, and browsers have not implemented any sort of replacement…but unknowingly, they actually have đŸ˜‰

But wait! An epic hack emerges!

What I’m going to present below is a hack in the truest sense of the word, but damn, is it cool. The method I’ve devised provides the same functionality DOMNodeInserted offered, without requiring you to annihilate browser performance in the process – and it is very likely to work for a long, long time.

The Description

Basically what we’re going to do is setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for. I used a relatively benign and little used css property, clip I use outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.

Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.

The Demo

That’s about it, pretty simple huh? Let’s see it in action – notice that the text in the divs isn’t added until their insertion into the DOM is detected:

Party time, excellent!

There you have it folks, a scope-able, performant, relatively simple method for DOM node insertion listeners in all browsers that support CSS3 Animations.

In related news: I will be accepting donations in the form of Jamba Juice gift cards, or pure gold bullion if you’re feeling especially generous.

The Best Damn Modal Method Periodâ„¢

The Gist

In the long annals of web history there have been many attempts at creating modal dialog boxes. As far as I’m aware, all methods to date use hard-coded element heights and heavy-handed JavaScript logic to center the modal in the viewport (not to mention the complex measurement of elements and resetting of styles they do on window resize). There are a number of ways to vertically center things with HTML and CSS, Douglas Heriot details most of them in the following post: Vertical Centering with CSS via ThemeForest’s Lost In the Woods blog.

Thinking Outside the Box…Literally

The other day, I threw an off-the-shelf lightbox script into a new project that I had used previously. Quickly, old frustrations returned as I looked over the mess of code and calculations required to do something as simple as positioning an element in the center of a page. I thought “Holy expletive outburst Batman, there has to be a better way than this!”. Turns out there was.

I’ve devised a method for centering modal content that is radically easier than any that have come before it. There are two types of modals you can create with this method that I’ll be discussing in this post. The first is a basic single element modal. The second is a modal with a header, footer, and even more dynamic height functionality. Both varieties automatically resize and recenter the modal in response to changes in size or content. The two methods work in IE7+, Firefox 2+, Chrome, and Safari 3+ (IE6 support requires fixed position fakery, but that is par for the course).

Here is a diagram so you can visualize the basic HTML and CSS that forms the foundational for both variations of the method:

A Simple Modal

Start with the following simple HTML structure:

<table id="modal">
  <tbody id="modal-tbody">
    <tr id="modal-tr">
      <td id="modal-td">
        <div id="modal-box">
          <div id="modal-body"> 
              <!-- Your content will go in the
              modal-body element. Always use
              this element for adding padding,
              margin and styles, as it will preserve
              your height and width settings. -->
          </div>
        </div>
      </td>
    </tr>
  </tbody>
</table>

“Nooo, a table!”, I can hear it now, sigh. You want a simple, non-JS, vertically centered modal or not buddy? Yeah, that’s what I thought. Here’s a preview of what you’re about to think in 10 seconds: “Just when I was about to light this guy up for simply nesting crap in a table (big wup), he throws down this sweet CSS and totally redeems himself!”. Here’s why you’re about to think that:

(I have commented next to the property values that can be optionally user-specified using any CSS unit you’d like)

html, body
{
    height: 100%; /* root and body MUST be height 100% */
}

#modal
{
    position: fixed;
    top: 0;
    left: -100%;
    height: 100%;
    width: 100%;
}

#modal-tbody, #modal-tr, #modal-td
{
    height: 100%; /* All table elements should be height 100% */
}

#modal-td
{
    vertical-align: middle;
}

#modal-content
{
    position: relative;
    left: 100%;
    height: auto; /* HEIGHT optional, any unit */
    width: 50%; /* WIDTH optional, any unit */    
    max-height: 80%; /* MAX-HEIGHT optional, if height auto, must be % */
    min-height: 80px; /* MIN-HEIGHT optional, any unit */
    max-width: 225px; /* MAX-WIDTH optional, any unit */
    min-width: 80px; /* MIN-WIDTH optional, any unit */
    margin: 0 auto;
    border: 1px solid;
    background: #eaeaea;
    overflow: auto;
}

Here’s a basic example via jsFiddle:

NOTE: When using the simple modal method with height set to auto, you must constrain the modal to a percentage-based max-width in order to ensure that scroll bars appear when the modal content is taller than the window. An example of this use-case would be cases where you need to add elements to the modal, but outside the modal-body element, such as a header and footer. Luckily the advanced method described below allows for this.

The Advanced, Have-your-cake-and-eat-it-too Modal

There are cases were you want the best of everything. For such cases, you’ll need a slightly modified HTML structure:

<table id="modal">
  <tbody id="modal-tbody">
    <tr id="modal-tr">
      <td id="modal-td">
        <div id="modal-box">
          <div id="modal-header"></div>
            <div id="modal-content">
              <div id="modal-body">
                  *** YOUR CONTENT HERE ***
              </div>
            </div>
          <div id="modal-footer"></div>
        </div>
      </td>
    </tr>
  </tbody>
</table>

There is also a single addition to the CSS:

#modal-content
{
	overflow: auto;
}

Notice I have wrapped the body in another element, modal-content. This is the only required change, the header and footer are just so our advanced modal demo looks more like the intricate modals you see on the web today.

Next, you need to set a single style with JavaScript on window resize. Now don’t get all sad face on me, this one-line of JavaScript is nothing like the complex, performance assaulting JS found in the modal scripts floating around the net. This is about as close to set-it-and-forget-it you’ll ever get, let’s take a look:

window.addEventListener('resize', function(){
    document.getElementById('modal-content').style.maxHeight = document.documentElement.offsetHeight - headerFooterMargin;
}, false);

Above you’ll notice the header/footer/margin variable. In cases where you have a header, footer, or want to allow extra space between the modal and the edge of the window on resize, you’ll need to subtract that value from the document’s height offset.

The awesome thing about this JavaScript is that it retains 100% of the adaptive ability of the modal. All other modal scripts on the web fall down when you add dynamic content or manipulate the size of their modal elements. Usually if you add content afterward, modal scripts require you to fire some laborious recalculation method that resets a massive set of height, width, and positioning values in order to maintain a centered and scrollable modal. The Best Damn Modal Method Period eliminates all that unneeded calculation and frees you up to create the most dynamic and complex modal interactions you can think of.

Here’s a full-page demo of the advanced method in action. For my own purposes, I create a MooTools class using the Best Damn Modal Method Period for my own convenience, but the output remains the same:

Sexy Full-size Advanced Modal Demo

Happy modal’n folks!

Link element load event support for CSS Style Sheet includes, finally!

In the long history of developer attempts at creating a method of loading CSS Style Sheets via LINK tags with load event support, there has been a lot of FAIL and almost no WINNING! Oddly enough, Internet Explorer has supported a load event on LINK tags for as long as I can remember, but Firefox and the Webkit bunch…not so much.

What are people doing currently to service this need? Well here’s an example of half-baked solutions that have surfaced over the last couple of years on Stack Overflow (I have added my solution to the list, so up-vote it!). Most developer have been reduced to loops that look for the new sheet in the StyleSheet object at short intervals or even loading the link tag in an iframe and using the frame’s onload event, two methods that cause me to puke on my shoes on principle.

The Solution

Well web devs, today is the day. Yup, CSS Style Sheet loading via LINK tags with pretty damn legit load event support is a reality:

var loadCSS = function(url, callback){
    var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = url;

    document.getElementsByTagName('head')[0].appendChild(link);

    var img = document.createElement('img');
        img.onerror = function(){
            if(callback) callback(link);
        }
        img.src = url;
}

The code above creates a LINK tag for your CSS file and inject it into the head of the document, there’s certainly nothing odd about that. Next comes the interesting part, it creates an IMG tag and adds your CSS file location as src parameter of the element then injects it into the page. The browser parser downloads the file and attempts to parse it, which predictably fails as it is the wrong MIME type. That failure triggers the error event on the image element. We know the file is present at that point, so the load event you pass to the function is fired from inside the image element error event, the image element is then deleted from the document. Whether cached or not, this method will fire your load event for any CSS file you include, when the file is in the cache it is called immediately – which is a huge benefit.

Try it out!

Here it is a live demo, I have added an alert as the load event default for example sake:

Opera Added to the Browser Add-on API Coverage Table

I have received quite a few feedback responses on the Add-on API Table. A curiously large percentage of the responses were from folks asking me to add support for Opera’s new extension APIs. Well I committed to updating this thing, so here you go, Opera extensions APIs are now included đŸ˜‰

The Opera extension API docs were pretty tough to traverse. They are quite verbose and some sections seem like a mixture of a tutorial or article with some method references sprinkled in. I want to make sure I don’t short-change any of the browsers on the list, so please let me know if I’ve missed any APIs.

Happy extension development!

Programatically Convert CSS named colors to RGB & HEX

Converting color values between different formats is commonplace on the web. Whether it is a JavaScript-assisted animation, color picker, or modifying a color’s attributes, there are many circumstances where color manipulation is essential to front-end development. One color format particularly hard to work with is CSS named colors. Named colors are widely supported in A-grade browsers, here’s a list of common named colors courtesy of w3schools.

So what’s the problem?

The problem with named colors is the difficult lengths to which a developer must go to manipulate and use them practically. It is relatively easy to use them statically in style-sheets (though I prefer RGB or HEX, in that order), but more interesting uses are usually dynamic ones that result from user input.

As developers, we think in RGB and HEX values because that is the world we are immersed in, users however are more likely to think in black and white as opposed to #000000 and #FFFFFF. What does that mean to you as a developer? Let’s say you have a color picker that transitions a target element to and from colors based on user input, how do you allow a user to type in “purple” and effectively animate your element from #000000 to “purple” without a gigantic, pre-populated, name colors object? Furthermore, what developer would ever want to spend their time assembling and maintaining such a list?

“Computed Styles, I’ve heard so much about you.”

Most developers are aware of computed styles, but just in case you are not, here’s a definition to prime the pump:

Computed Styles methods provide used values for all CSS properties of an element in their most reduced format. Computed Styles is a somewhat costly operation as all the values must be calculated each time the method is called.

One note on the above definition – the used values returned by computed styles methods are always reduced to a common format, this is most evident with the transform property, it is reduced to the common matrix(a, b, c, x, y) representation of the value regardless of which format (rotate, scale, skew, translate, etc.) the style was applied with.

Now that we have a better understanding of computed styles, let’s find out how we can use them to overcome the use of dumb, static named color tables.

As it turns out, all browsers have internal methods for reducing named color values to HEX or RGB formats, some are just harder to access than others. Mozilla, Chrome, and Safari all have a common global method for retrieving computed styles – window.getComputedStyles() – that takes as an argument the element you are requesting the computed styles for.

Opera uses the same mechanism as other non-IE browsers to report computed styles, however named colors are not converted to HEX or RGB values when retrieved with the computed styles method. Instead, Opera strangely chooses to reset the property in question on the style object of the element to the calculated HEX or RGB value of the named color.

IE provides an object, currentStyles, that is accessible directly from the element. Unfortunately IE does not convert named colors to RGB or HEX through any sane means – even in IE9. It is possible to get to the calculated HEX and RGB values of named colors in IE, but as you’ll see below, it isn’t pretty.

Bringing it all together

So let’s get smart about this! With the goods on computed styles I crossmedibrowsertated and came up with the String native methods “colorToHex()” and “colorToRgb()” with a little help from the sextacular MooTools javascript framework:

© 2017 Back Alley Coder

Theme by Anders NorenUp ↑