Im trying to create a form that will submit with a long press (currently 2 seconds) but being able to cancel (or prevent submitting the form) when the user stops holding the submit button to give the user time to change their mind about submitting the form.
function conf_submit(btn) {
$(btn).mousedown(function() {
btn_timeout = setTimeout(function() {
alert("form submitted");
}, 2000);
$(this).val("Release to cancel!");
$(this).attr('class', 'btn_down');
});
$(btn).mouseup(function() {
clearTimeout(btn_timeout);
$(this).val("Submit");
$(this).attr('class', 'btn_up');
});
}
The button is suppose to change text, i wanted to have a count down after 'Release to cancel!' so the user knows how long until the form submits but couldn't get this to work.
My problem is; The first time you click the link it doesnt fire, it also continues to fire even on mouseup.
Thanks in advance for any support.
Just call conf_submit once with the button element when page loads, not each time the button is clicked.
function conf_submit(btn) {
$(btn).mousedown(function() {
btn_timeout = setTimeout(function() {
alert("form submitted");
}, 2000);
$(this).val("Release to cancel!");
$(this).attr('class', 'btn_down');
});
$(btn).mouseup(function() {
clearTimeout(btn_timeout);
$(this).val("Submit");
$(this).attr('class', 'btn_up');
});
}
[...document.querySelectorAll(".btn_longpress")].forEach(conf_submit);
.btn_down {
background-color: red;
}
.btn_up {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input class="btn_up btn_longpress" type="button" value="Submit" />
<input class="btn_up btn_longpress" type="button" value="Submit2" />
</div>