Reputation: 8349
I have jquery that will add an item to a select list and change the background color to indicate that it has been added (the select list is not visible). When I click the plus it adds the item to the list and changes the background to green. When I click it a second time it removes the item and color. This works once. If I repeat the cycle it stops working. Any ideas why that might be?
<ul>
<li><span id='add'> + </span>this is a test
</li>
</ul>
<select multiple="multiple" id="destination"></select>
$(document).ready(function () {
$("#add").click(function () {
var color = $("#add").css("background-color");
if (color == "transparent") {
$("#add").css("background-color", "green");
$("#destination").append('<option value="1">New option</option>');
} else {
$("#add").css("background-color", "transparent");
$("#destination option[value='1']").remove();
}
});
});
Upvotes: 2
Views: 13925
Reputation: 206699
Don't check for backgrounds, use just the .toggle()
event:
http://jsbin.com/unojap/4/edit
$("#add").toggle(function () {
$("#add").css("background-color", "green");
$("#destination").append('<option value="1">New option</option>');
},function(){
$("#add").css("background-color", "transparent");
$("#destination option[value='1']").remove();
});
Upvotes: 3
Reputation: 272446
Instead of checking for background colors, use jQuery.data to store whether an element has been added or not:
var added = $(this).data("added");
// returns undefined if requested data does not exist
if (!added) {
$(this).data("added", true);
// change background, do stuff
}
else {
$(this).removeData("added");
// change background, do stuff
}
Upvotes: 1
Reputation: 11978
This depends on the browser. In example in Chrome $("#add").css("background-color")
returns rgba(0,0,0,0)
not transparent
. Thus reading a background color like this isn't cross-browser compliant.
In general I think you may be better off with classes.
$(document).ready(function () {
$("#add").click(function () {
if ($(this).hasClass("transparent")) {
$(this).addClass("green").removeClass("transparent");
$("#destination").append('<option value="1">New option</option>');
} else {
$("#add").addClass("transparent").removeClass("green");
$("#destination option[value='1']").remove();
}
});
});
Upvotes: 3