DEV Community

Cover image for Reusable image before and after patterns
netsi1964 🙏🏻
netsi1964 🙏🏻

Posted on • Updated on

Reusable image before and after patterns

As I have a facebook group where people share images and sometimes a before and after view of a manipulated can be inspirational, I wanted to create code for the web to easily add such functionality to a webpage.

So I just want to add some code which will give a simple before and after comparer component on a webpage. I did a simple one which does the job:

You can see the code used in the above embedded pen, I will not go into this first version.

It is good and solves the job at that moment, but I want to take it further and turn it into first a class which can be imported anywhere and make it even easier to reuse.

ES6+ Classes BeforeAndAfter

The thing with having a JS class is that you do not need other than the code, it will contain all HTML, CSS and JS and you use it simply by creating a new instance of it

So let me see... What would I like that class to be able to offer? Here is what comes into my mind - this is how it could look like:

const BA = new BeforeAndAfter(selector, imgUrlBefore, imgUrlAfter, text);

So to get from the pen above to this I create a new fork of it where I have pulled in all the HTML and CSS into a new class BeforeAndAfter - you again can look for the HTML, CSS and JS in the result - here I have used another set of images here:

You can look at the javascript class here:

The webcomponent/customElement image-before-after

Together with my colleague Nanna Bech Munkholm we create a NPM package image-before-after which can easily be used in any web project. You can see how easy it is to import to any webpage using import which will give you instant access to the new customElement image-before-after. I have created a pen on codepen: CodePen Home
CustomElement image-before-after

Discussion (0)