PDA

View Full Version : Resolved move background position on each click


many_tentacles
03-31-2010, 09:59 AM
I want to be able to move the background position of a div by 300px every time I click on a button.

So it starts at 0px then 300px on click, then 600px on click, then 900px etc etc...

I've got the following code at the moment

<!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" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<style>
#thediv
{
background-image:url(http://farm2.static.flickr.com/1320/876653257_d1e394d38e.jpg);
background-position:0 0;
height:200px;
width:300px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
$('#thediv').css({backgroundPosition: + 300 +'px 0'});
});
});
</script>
</head>
<body>
<div id="thediv" >
<a href="javascript:;">link</a>
</div>
</body>
</html>


Thank you!

many_tentacles
03-31-2010, 10:21 AM
<!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" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<style>
#thediv
{
background-image:url(http://farm2.static.flickr.com/1320/876653257_d1e394d38e.jpg);
background-position:0 0;
height:200px;
width:300px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var current = 0;
$('a').click(function(){
current = current+300;
$('#thediv').css("backgroundPosition", + current+"px 0");
});
});
</script>
</head>
<body>
<div id="thediv" >
<a href="javascript:;">link</a>
</div>
</body>
</html>

VIPStephan
04-01-2010, 02:43 AM
I’m sorry if this isn’t relevant to the issue but I can’t leave this uncommented:

[CODE]<a href="javascript:;">link</a>

Remove this and never ever do it again.
And to add to this: A link has to be functional (i. e. link somewhere). If it doesn’t serve any purpose other than executing a script then there’s no need for an anchor in the first place, you could use any element. And if it’s just supposed to execute a script you can as well not hard code it into the HTML at all but rather add it dynamically through JS since the element would be useless if JS wasn’t available.