Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Andrew McCormick
Andrew McCormick
17,730 Points

Javascript change image src onmouseover

I'm trying to create a rollover gallery for a website to show before and after images. I want this to plug into a WordPress site. Since there amazingly doesn't seem to be any current plugins that accomplish this I wanted to write something up myself. What I'm thinking is that I would upload the images with "_a" and "_b" on the end of the filename and give them a class of "rollover".
Then I would write a script that would on mouseover use regex to change the _a to _b. This would allow me to use the gallery system already in WordPress and be able to basically have it automatically applied to all the images.
I'm thinking something like this:

function myFunction()
var str=document.getElementsByClassName("rollover").src; 
var n=str.replace("_a","_b");

<img class="rollover" src="http://treehouse.com/image_a" />

First, is this a reasonable way to go about this?

Second, does anyone just know of a good plugin for WordPress that I'm missing (don't want to reinvent the wheel if I don't have to).

2 Answers

31,206 Points

You could do this with CSS image sprites as well. Each before/after set would actually be one image (keeps http requests down). Then using the CSS pseudo class :hover, you can show a different part of the image.

But is this really what you want to be doing? What about users visiting your sites from devices not using a mouse (hover will break more likely than not). If you do decide it's crucial from a design standpoint to "hide" the after image, could you do it in a way that would work for more users?

Andrew McCormick
Andrew McCormick
17,730 Points

Thanks. That's a great point about hover on mobile devices and even all the touch PCs these days. I really enjoyed having a hover option on my previous site using flash that did a great job of displaying my post-production work, but I think it is time to move on. I found a great before and after slider on Code Canyon that allows me to create a handle that the users can drag back and forth to show before and after and it works great with touch.