Reputation: 17829
I simply want to have a variable toggle between true and false and have the text on the button
clicked to change as well. Here is my Jquery:
$("button").toggle(
function () {
$(this).text("Click to change to paint brush");
var erasing = true;
},
function () {
$(this).text("Click to change to eraser");
var erasing = false;
}
);
This looks 100% sound to me, but in my jsfiddle you will see that it is toggling the existence of the button before I can even click it! Why is this happening and how can I fix it?
Upvotes: 2
Views: 136
Reputation: 123739
This version of toggle has been deprecated (1.8) and removed (1.9). Now you need to handle it in button click itself. Somthing like this:
var erasing = false;
$("button").click(function () {
erasing = !erasing;
$(this).text(function (_, curText) {
return curText == "Click to change to paint brush" ? "Click to change to eraser" : "Click to change to paint brush" ;
});
console.log(erasing);
});
Plus if you want to preserve the value of the variable just define them out of the click event scope, so that it is more global to be accessed outside.
See
Upvotes: 3
Reputation: 17829
Thank you all for explaining how toggle is out of date...so that is all I needed and then I solved my problem with a simple if
statement:
var erasing = false;
var i = 0
$("button").click(function () {
if(i%2==0){
$(this).text("Click to change to paint brush");
erasing = true;
}
else{
$(this).text("Click to change to eraser");
erasing = false;
};
i += 1
});
Upvotes: 1
Reputation: 11371
As PSL said, the toggle
you're looking for is gone and lost. if you want a click and hold solution (as your title suggests), you could look at using mouseup
and mousedown
.
var erasing;
$("button").on({
"mousedown": function () {
$(this).text("Click to change to paint brush");
erasing = true;
},
"mouseup mouseleave": function () {
$(this).text("Click to change to eraser");
erasing = false;
}
});
Demo : http://jsfiddle.net/hungerpain/ymeYv/6/
Upvotes: 0