DEV Community

Nic
Nic

Posted on • Originally published at blog.nicm42.me.uk

Moving elements with JavaScript

Recently I had a situation where there were two elements, A and B, each of which contained a whole load of things. On mobile A was at the top and B was below it. But on desktop B was on the left and A was on the right.

Theoretically that's easy to fix - flexbox will sort that right out. However, that then meant that the focus order was wrong.

But that's still an easy fix - you just duplicate one of the elements in the HTML and hide one on mobile and the other on desktop. Except that this is in a CMS and the HTML was being built by it and didn't exist as HTML to change. And there were a load of scripts doing things inside these elements, some of which could well depend on a unique ID or a class only being used once. It was an important page on the site, so if I broke it, things would go very wrong, so I didn't want to touch it.

There will one day be some CSS to tackle this: reading-flow. But at the moment it's only available in Chromium browsers and is also marked as experimental, therefore subject to change and shouldn't be used in production code.

Fortunately, there's a really simple JavaScript solution. What I did at desktop size was to move element B to be before element A. When you look at the resulting HTML it looks like it's always been that way round. And the focus goes through the element on the left, followed by the element on the right.

The solution is before. Or after. Since I only have two elements they effectively do the same thing.

To move element B before element A you use:

a.before(b)

or you can use

b.after(a)

Which is a bit confusing because if you read that from left to right it sounds like you're saying a is before b, or b is after a. But when you try it it's easy to tell you've done it wrong.

Top comments (0)