Beating old browsers: Responsive Web with JavaScript

Forget Grid Layout, forget the Flexbox, remember old browsers. I’ll show an example for frontend-based relayouting. No more stupid IFs in backend templates!

The concept

Basically, the idea is to have a piece of HTML that would be moved as a DOM hierarchy to new parent element. As I want this solution to be generic, I won’t write JavaScript code for moving elements manually. Instead, let’s declaratively define in HTML when element should move and where – yes, in HTML. Would be nicer to do this in CSS but, oh, well.

Why even responsive?

  1. I don’t want to do this on backend because it’s much more messy – a choice between duplicated code or too many micro-templates
  2. mobile devices could be rotated between horizontal and vertical
  3. It’s easy to test on PC while development – less refreshing, just resizing the browser as with media queries :)

Example

For instance, let’s have a product picture and product description near each other – column by column.

Desktop version of the website

Now, on mobile phones (let’s say width=375px like iPhones) it would be the picture on the top and description on the bottom.

This is really simple to deal with media queries. However, believe there are much more specific relayouts where you cannot even count on Flexbox. And grids… are too far away.

My solution


Now, the contents of this <div> would be moved to a place defined by move-to-element  attribute.

Like this one:


Important notes here:

  • the value of move-to-element  looks for element with move-target  attribute of same value
  • move-filled  and move-empty  classes are defined manually here, but it’s also automatic. Manual choice was because of one less relayout after JavaScript is loaded and executed.
  • move-filled  means nothing, you could define it however you like in CSS
  • move-empty  is just a class definining display: none !important; so the empty element doesn’t take any space

Now, the code!

Implementation

The code above is pretty straightforward, probably needs no commentary.

Summary

Drawbacks? All those binding libs (React, AngularJS or even rivets.js) will broke.

However, even if this technique isn’t genius, it’s pretty useful through development and user experience – in case user rotates his device by changing screen orientation.

References