120382833 120382833 - 2 months ago 17
PHP Question

Jquery timeout for doubleclick

I have a clickable div which should first present a text instruction to tap again in order to fire ajax action, which is under a new class name added after a 1st click. This text has a timeout and will change back to the original.

The problem is that once the text is back to original the actual ajax fire action should stop working as well, but the actual class is not removed. Any suggestions?

What I really need is a kind of doubleclick with a 2second timeout..



function onlyfire() {
$(".onlyfire").click(function() {
var div = $(this);
var original = $(this).html();
div.html("Tap again");
$(".onlyfire").addClass("fire");
setTimeout(function() {
$(div).html(original);
$(".onlyfire").removeClass("fire");
}, 2000);
$(".fire").click(function(fire) {
$.ajax({
type: "POST",
data: dataString,
url: "something.php",
cache: false,
success: function(html) {
div.html(html);
}
});
});

return false;
});
};

<div class="onlyfire">
Do Something
</div>





here is the jsfiddle:
https://jsfiddle.net/jngqzw7q/1/

Answer

You can use .one() with event namespace as parameter, .off() referencing event namespace

function handleClick(e) {
  var div = $(this).data("original", this.innerHTML);
  // var original = div.html();
  div.html("Tap again");
  $(".onlyfire").off("click").addClass("fire");
  // http://stackoverflow.com/questions/39057179/why-is-click-event-attached-to-classname-fired-after-classname-is-removed#comment65464000_39057261
  var fire = $(".fire");
  fire.one("click.fire", function() {
    alert("this should not be showing once the text is changed back to original");
  });
  setTimeout(function() {
    fire.off("click.fire");
    div.removeClass("fire")
    .html(div.data("original")).click(handleClick);
  }, 2000);
}

function onlyfire() {
  $(".onlyfire").click(handleClick);
};
onlyfire();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="onlyfire">
  Do Something
</div>

Comments