Tutorial: Before and After Image Scrubber – Part I

Today’s tutorial is on how to create a JavaScript/jQuery Before and After image scrubber.

View jsFiddle Demo...
As you can see, the scrubber allows the user to quickly swap images or parts of the image to better visualize the changes between the two images.

First, lets look at the scrubber in theory.

  1. It should stack two images directly on top of each other.
  2. It should have a dividing line or vertical bar to distinguish the two images.
  3. It should provide a handle the user can drag with their mouse.
  4. The scrub line should show the before image on the left and the after image on the right.

Ok, let’s get started!

Step 1 : Set up the HTML

First, we’ll need separate divs to hold both the before and after images.
A div to display the dividing bar.
A div to display the handle.
Let’s put all four of these inside a container div in the <body> tag of our HTML document.

If you run the document in your browser, you won’t see much. Let’s add our images like so. (Use your own two different images that are of the same dimensions as each other.)

Run the document again. Great, images! However they are not stacked/overlaid. More likely they are side-by-side or one above the other. Let’s add some CSS to position them.

Step 2 : Set up the CSS

For this demo we want the elements; container, before, after as well as the <body> tag to all have the same properties. So we will write our first CSS as such:

We want our images to sit exactly in the top left corner of our browser. Setting “position” to “absolute” is the first step. To make sure there are no browser defaults we will zero-out the following attributes; margin, padding, border, top and left. Lastly, lets make sure nothing spills out of our containers by setting “overflow” to “hidden”.

If you run the document now, you most likely will see nothing again. That’s ok, we’ll fix this in a moment. However if you want to verify things are going ok; in the above CSS set height and width to something like “200px”. (If height and width are set, you should now see at least part of the “after” image.)

Step 3 : jQuery Foundation

First we need to tell the HTML document to use the jQuery library, and where to read it from. Instead of using up your own server’s bandwidth you can use Google’s! Like “Fight Club”, this service is free for all. Now isn’t that something?
Inside your HTML document within the <head> tag include the following line:
<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js”></script>
This tells your document to go to Google’s CDN and read the jQuery library version 1.11.0. Your header should look something like this:

Next we need to tell our document when to execute our jQuery code. Simple enough, let run it when the window is loaded. At the bottom of your HTML document, just before the closing </body> tag, insert the following code:

We used $(window).load() instead of $(document).ready() because we want to make sure the images are loading before running our code.
Next we need to know the dimensions of our two images. (Hopefully the two images you have chosen have the exact same dimensions as each other.)
Insert the following two local variables in the $(window).load() function:

Lets look at the jQuery we just inserted.
$() tells JavaScript that we will be running a jQuery function.
“#” tells jQuery that we selecting an element by its “id” attribute. In this case the element with the id=”before”.
But wait we don’t want that element. We want the image inside that element.
Hence we put a space and then the tag name for the element we really want.
Like so, “#before img”.
In layman’s terms we are saying, ‘I want the image element that is inside of the element with the id=”before”‘.
Now that we have identified which element we are talking about, we use .width() and .height() to get the numeric value of that images height and width respectively. We then set these values to our newly created local variables; newW and newH.

Step 4 : Resize Containers

Time to resize our container(s); container, before and after.
Insert the following code below your variable declarations inside your “$(window).load()” function:

Once again we use the syntax $() to tell JavaScript that we are running a jQuery function.
We use the “#” symbol to identify that we want an element with the id that follows the “#” symbol.
However, this time we have three different elements we want the same code to run on. So we simply separate the three different element ids with a comma placed between them.
Next new to this syntax is the .css() function.
This function permanently changes the CSS of the elements we listed in the first function.
Inside the css() we use “{}” brackets to signal to the function that we will be changing more than one CSS attribute.
‘width’ tells the function what attribute to change.
Next is the “:” which tells the function, “What follows next is the value to set the attribute to.”
In our case, we are telling each container element to set its width and height to the same size of the images.
Now if you run the document in your browser, the images should be fully displayed.

“Great” you say, “The ‘after’ image is full size. What about the ‘before’ image, ‘vBar’, and ‘handle’?”
Good question.

Step 5 : The Divider

We want a divider that’s visible, but not too distracting.
Our scrubber will move left and right, so it makes sense to have a divider that seperates the left from the right.
To do so we will create a vertical bar or line that will start in the middle of the image and stretches the entire height of the image.
Since we to want move the divider to an exact position, set the “position” attribute to “absolute”.
Pick any color you like for a background-color.
Set the width to a small even number.
Set the magrin-left to negative half the width you just set.
Why? We want the middle of the bar, to be at the “left” location we will be setting. If we didn’t adjust the margin in the negative direction, the bar would sit to the “right” of what ever “left” position we set.
Include the following code in your CSS styles:

Now lets make sure the divider is the correct height and in the middle of the image.
Include the following code below the code we used to resize the containers inside the “$(window).load()” function:

This syntax should look familiar now.
We basically said, “For the element with id=’vBar’ change the height to the height of the image, and move the element left however many pixels is half the size of the image.”
Run your document in the browser now. You should see your “after” image with a colored line running down the middle of it.

Step 6 : The Handle

Just like our vertical bar “#vBar”, we want the handle to sit in middle of our image. However since it is not the full height of the image, we want it to sit in the middle vertically and horizontally. You may be using a different size image than I am. For this reason we will calculate the horizontal position dynamically. We want to move the handle to an exact location, so set the “position” attribute to “absolute”. Pick any color you like for a background-color. You can choose any width as long as it is even. However for the same reason as the vBar, make sure to negatively offset the margin-left to half the width of the handle. Include the following code in your CSS styles:

Now lets make sure the handle is vertically and horizontally in the middle of the image.
include the following inside the “$(window).load()” function:

The syntax should look the same as the #vBar jQuery.
For the height, I am using 20% of the images height using “newH*.2”.
To move the handle to the center of the image, we set “top” to equal be half the image height.
Remember to offset the “margin-top” to half the element’s height, so the middle of the handle will be in the middle of the image.
I used 10% of the image’s height, since I set the handle height to 20% the image’s height.
Now run your document in the browser. You should see your “after” image, in the middle of the image; the vBar, and the handle.

Half time! You’re doing great. Actually you are more than half the way there. Your full HTML document should look like:

View Full Code...

Step 7 : Interactivity

At this point you can look at the Before and After Scrubber, but you can’t do anything with it. Let’s change that by letting the users know they can use the handle by changing the mouse pointer.
Inside your “$(window).load()” function, include the following code:

Notice we have two functions being passed to the “hover” function.
The first function says what to do when the mouse is over the selected element.
The second function says what to do when the mouse is leaves the selected element.
Inside the “hover” functions we use the identifier “this”. “this” refers to what ever element called the function. So now we are saying, “When the mouse is over the ‘handle’ element change the cursor to a pointer, and when the mouse moves off the ‘handle’ element, change the cursor back to its default image.”

Lets make the vBar interactive as well.
Easy enough, just add the #vBar selector to the above code, seperated by a comma:

Run your document in the browser.
Mouse over the bar or handle and the cursor should change and change back when you move the mouse off either element. At this point clicking or holding the mouse button down still does not do anything.

Step 8 : Mouse Drag

To enable the “handle” and “vBar” elements to drag with the mouse button down, we need to know two things:
Is the mouse button down and did it move while the button was down?
Include the following code inside the “$(window).load()” function:

To translate, we are saying, “For the elements with ids “handle” and “vBar” listen for when the mouse button gets pressed down. If so, then listen to the browser window for any mouse movement. If there is mouse movement after the mouse button is pressed, run the next function.”
We’ve set up the listeners on the two elements, now lets tell the elements to follow the mouse.
Your mousedown code should now look like this:

This last line moves the “handle” and “vBar”‘s “left” attribute to the mouse’s “x” location.
Run the document in the browser.
Click on the “handle” or “vBar”. They should now follow the mouse left and right.
Problem though, the “handle” and “vBar” never stop following mouse now.
Lets add the following below our previous code, but still within the “$(window).load()” function:

We just told the document, “Whenever the mouse button is lifted up, stop listening to any mouse movements.”
Run the document in your browser.
Great, the “handle” and “vBar” are following the mouse only while the mouse button is pressed down.
New problem.
What happens if the mouse button is raised while the mouse is beyond the borders of the image?
The “handle” and “vBar” are now lost to the program.
Lets fix this by making sure the “handle” and “vBar” do not go beyond the boundries of the image.
We will use two “if” statements to test for the far left and right side of the image and prevent the elements from going beyond the edges.
Replace the entire mousedown function with:

The first “if” statement makes sure the “handle” and “vBar” does not go past the far right of the image.
The second “if” statement makes sure the “handle” and “vBar” does not go past the far left of the image.
The “else” statement allows “handle” and “vBar” to follow the mouse.
Run the document in your browser. The “handle” and “vBar” now stop at the edges.

Your doing Great! Now for the real magic to start taking place.

Step 9 : Revealing the After Image

Let’s see both images!
Include the following code inside the “$(window).load()” function:

Run the document in the browser…Nothing changed.
Well yes, but we can not see it cause the “before” element is behind the “after” element.
Swap the two element’s location in the HTML document:

Now save and run the document in the browser.
Hey Hey Hey! We can see half of each image!
The “handler” and “vBar” follow the mouse too. But we want to reveal the before image up to the “vBar” and no more.
Replace the entire mousedown function with:

For each “if” and “else” condition we changed the “before” element’s width to match the “vBar”‘s position.
Save and run the document in your browser.
Tada! You can now scrub back and forth to see both images.
However, depending on your browser, you may have been noticing a blue tint over your images. We’ll fix that next.

Step 10 : Eliminating the Blues

As you scrub the handle left and right, the mouse periodically selects the image underneith. This adds a blue tint to the image. Very annoying. Get rid of it.
First lets tell all browsers to that there should be no CSS to selected images.
Add the following to your CSS styles:

This solves our problem in Chrome and Firefox, but not IE.
Now for the Coup de grĂ¢ce, to finish that pesky blue tint off for good.
To each of the three container divs (container, before, after), add the following:
unselectable=’on’ onselectstart=’return false;’ onmousedown=’return false;’
Now your HTML <body> tag should contain:

Save and run the document in your browser. No more blue flickering. Brilliant!

View Full Code...
Congratulations. You now have a Before and After image Scrubber.
However, today’s hot buzz word is “Responsive“. Part II will take the Before and Image Scrubber to the next level.

Posted in HTML, JavaScript, jQuery Tagged with: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*