Categories:

A CSS Before and After image effect gallery

Revisiting our original CSS Before and After Image example:

Imagine you're a professional painter and want to showcase different sets of wallpaper colors to compare and contrast. Our set up only does that for one set of images. With a little help from JavaScript, however, we can easily break free from that limitation. All we need to do is create a JavaScript function that when executed modifies the two images inside the "before/after" container, plus optionally change the container dimensions to fit the new set of images if they are different. The CSS we already have in place is adaptive enough to take care of the rest without any further changes to it. Lets now see how such a JavaScript function looks like:

"before" and "after" gallery script
<script>

function updatebeforeafter(containerid, imageset, newdimensions){
	var container = document.getElementById(containerid)
	var beforeafterdivs = container.querySelectorAll('div.before > img, div.after > img')
	beforeafterdivs[0].src = imageset[0] // update "before" image
	beforeafterdivs[1].src = imageset[1] // update "after" image
	if (Array.isArray(newdimensions)){
		container.style.width = newdimensions[0] + 'px'
		container.style.height = newdimensions[1] + 'px'
	}

}

</script>

<!-- Original "before/after" markup with ID attr added -->

<div id="beforeafter" class="beforeandafter">

	<div class="before">
	<img src="wallbefore.jpg" />
	</div>

	<div class="after">
	<img src="wallafter.jpg" />
	</div>

</div>

I've included the original markup for the "Before/After" container following the new JavaScript function to show how the two interact with each other. We can call this new function inside links to update the images, and optionally, the container dimensions when clicked on. For example:

<p class="togglelinks">
	<a href="#" onClick="updatebeforeafter('beforeafter', ['wallbefore2.jpg', 'wallafter2.jpg']); return false">Orange Set</a>
	<a href="#" onClick="updatebeforeafter('beforeafter', ['wallbefore4.jpg', 'wallafter4.jpg'], [550,250]); return false">Green Set</a>
</p>

The following creates 4 links to let users compare and contrast between 4 different wallpaper color schemes. Notice how the last link also changes the container dimensions:

Personally my choice would be sky blue.

End of tutorial

Partners