Page 1 of 1

Moving div Background Position on Click

Posted: Tue May 05, 2009 2:14 pm
by millsy007
I have a product image that is 4 images 'sewn together'
http://www.flickr.com/photos/28033561@N03/3504394261/

I am going to set a div called ProductImage and then have the background of the div set to this image, but with only the top image showing.

I then want to have a button for 'more views' and when this is clicked the background position shift to show the next part of the image showing a different view.

What is a suitable way to do this, I am hoping it could be done with a combination of css and javascript.

Re: Moving div Background Position on Click

Posted: Tue May 05, 2009 3:28 pm
by kaszu
With javascript on button click animate background-position css attribute (element.style.backgroundPosition in javascript) from "0px 0px" to "0px -256px" (for second image), "0px -512px" (for third), etc.
If you are using jQuery (or any other good library), then it should be easy.

If you want without animation, then just change element.style.backgroundPosition to needed value or
In css create classes and assign them to the DIV

Code: Select all

.image1 { background-position: 0px 0px; }
.image2 { background-position: 0px -256px; }
.image3 { background-position: 0px -512px; }
.image4 { background-position: 0px -768px; }

Re: Moving div Background Position on Click

Posted: Mon May 11, 2009 6:00 pm
by millsy007
Thanks

I now have the following:

Code: Select all

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function changePos(val1,val2,what)
{
document.getElementById(what).style.backgroundPosition = val1+' '+val2;
}
</script>
</head>
 
<body>
<div id="ProductImage" style="background-image: url(http://farm4.static.flickr.com/3563/350 ... 5b.jpg?v=0); height:126px; width:242px"></div>
<a href="#" onclick="changePos(0,-126,'ProductImage');return false">Change Position</a>
</body>
</html>
 
 
I have a couple issues I would love some help with.

When I click to change the position it will shift the background position once, but only once, is there a way I can get it to do this each time it is clicked?

And in firefox nothing happens