Reputation: 2533
So I'm making a image-toggling function that can toggle between two images. More specifically, it toggles the background images of a div.
I'm using the jquery .data() function as a counter where one = first image and two = toggled image.
Here's the algorithm I'm using:
It seems to replace the image on the first try, as in the first "if", but it doesn't replace the image again on the second try (the else part). It seems to never reach the else part, even though the first if should return false and then go to the else.
Any help will be appreciated. Also, I know there is a .toggle() function and other image-toggling methods, but I must use this one because this is only a small, edited chunk of a larger program.
Here's the code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="mouseovertestlayout.css" />
<script>
function startEdit()
{
$("div").click(function ()
{
if (($(this).data('kangaroo')) == "one")
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
(this).css('background-image', "url(image1.png)");
$(this).data('kangaroo',"one");
}
});
}
</script>
</head>
<body>
<div class="container" data-kangaroo="one" ></div>
<button onclick="startEdit()"> </button>
</body>
</html>
Here's my .css
.container
{
width: 20px;
height: 20px;
line-height: 0;
border-style:solid;
border-width:1px;
border-color:red;
padding: 20px;
background-repeat:no-repeat;
background-image:url('image1.png');
}
Upvotes: 0
Views: 227
Reputation: 856
You are missing a $ in else clause.
Fixed:
function startEdit() {
$("div").click(function ()
{
if (($(this).data('kangaroo')) == "one")
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
$(this).css('background-image', "url(image1.png)");
$(this).data('kangaroo',"one");
}
});
}
Upvotes: 1
Reputation: 94101
What you want to do can be done much shorter if you use a class and toggleClass
.
Demo: http://jsbin.com/anazoq/1/edit
HTML:
<div class="container"></div>
<button>Toggle</button>
CSS:
div {
...
background: url(image1.png) no-repeat;
}
.switch {
background-image: url(image2.png);
}
JavaScript:
$('button').click(function() {
$('div').toggleClass('switch');
});
Upvotes: 0
Reputation: 28763
Try like this
if (($(this).attr("data-kangaroo")) == "one") //Here is the edit
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
$(this).css('background-image', "url(image1.png)"); //Here put "$" before (this)
$(this).data('kangaroo',"one");
}
Upvotes: 0
Reputation: 1370
You have a typo in your "else" first line is the $ missing at (this)
Upvotes: 4