jQuery mobile button click handler firing twice?
jquery, jquery-mobile
Solution
Simple. There's two ways I've been able to solve this problem.
1) Use `e.stopImmediatePropagation()` after the opening function (second line). Be sure to pass the event parameter.
$(document).on("vclick", "#timer", function(e) {
// ^ note this param
e.stopImmediatePropagation();
console.log(past_ts);
if(past_ts === 0) {
past_ts = new Date().getTime();
$(this).text("Stop Set Timer");
}
else {
curr_ts = new Date().getTime();
diff_ts = ((curr_ts - past_ts) / 1000);
past_ts = 0; // Reset timer
$(this).text("Start Set Timer");
}
});
Documentation can be found here: http://api.jquery.com/event.stopimmediatepropagation/
OR
2) Try using `off().on()` technique. This ensures that if you've already binded the behavior, it will unbind, then rebind.
$(document).off("vclick", "#timer").on("vclick", "#timer", function() {
console.log(past_ts);
if(past_ts === 0) {
past_ts = new Date().getTime();
$(this).text("Stop Set Timer");
}
else {
curr_ts = new Date().getTime();
diff_ts = ((curr_ts - past_ts) / 1000);
past_ts = 0; // Reset timer
$(this).text("Start Set Timer");
}
});
Problem
Here is the code...simple (variables defined globally for now). First time I click it works as expected...second time howvere causes the event to fire twice consecutively which is now what I wanted...any ideas??? ``` $(document).on("vclick", "#timer", function() { console.log(past_ts); if(past_ts === 0) { past_ts = new Date().getTime(); $(this).text("Stop Set Timer"); } else { curr_ts = new Date().getTime(); diff_ts = ((curr_ts - past_ts) / 1000); past_ts = 0; // Reset timer $(this).text("Start Set Timer"); } }); ```