How to temporary disable the click function when it is executing? - javascript

$("#prevPage").live("click",function(e) {
.................
});
For example, when the user have already clicked on the prevPage, the statement inside it is running, if the user click on it instantly , it will trigger again. However, I would like the click event trigger only after all the statement inside it have finish execution, How to achieve that?

How about this or something similar:
<script type="text/javascript">
// disable command while function is being executed.
var sample = {
isExecuting : 0,
doWork : function (e) {
if (sample.isExecuting === 1) return;
sample.isExecuting = 1;
// do work -- whatever you please
sample.isExecuting = 0; // say: I'm done!
}
};
// live or bind
$("#prevPage").bind("click",function(e) {
sample.doWork(e);
});
</script>
simple 'shield' to block a multiple-call scenario.

Then set a flag on the element to check if it's clickable or not.
$("#prevPage").on("click",function(e) {
e.preventDefault();
//get the clickable attribute
//if it's not existent, its undefined hence "false"
var unclickable = this.unclickable;
//if it's not unclickable (it's clickable)
if(!unclickable){
//make the flag unclickable
this.unclickable = true;
//do stuff
//reset it back the way it was after operations
this.unclickable = false;
}
});

Set a variable that your event triggered
var prevPageEventTriggered = false ;
and set it to ture when event triggered
prevPageEventTriggered = true;
and then add condition for this in click event handler function
$("#prevPage").live("click",function(e) {
if ( prevPageEventTriggered ) {
return false;
}
// your code goes here
// ....
});
if it have finish execution, you can set it to false . hope this will helps

use the unbind function of jquery
$("#prevPage").unbind("click");
after your task finished
$("#prevPage").bind("click",function(){....your code here....});

unbind() will do the work for you.
An alternate could be like using detach(). When your process is executing detach the button and when your process finsihes executing, use reattach() to get the button back.
What I will suggest is use unbind().

Related

How to execute function while handle 2 events at same time?

I have some code that wants to be executed while the user resizing an element and scrolling the window at the same time tow events must occur at the same time to execute the function something like the following but I want to merge them to be like one custom event?
this.on("resize", function() {
$(window).scroll(function() {
figure.setHeight(_this.getHeight());
_this.setHeight(figure.getHeight());
});
});
Explanation : I have used a flag here, initially set to false. As it is given that both events will be happening, we can make a check in one function is the other is happening or not and execute the desired function.
First of all click the button. A console will be generated, that clicked. Now flag is set to true. But myFunction() is not eecuted, coz it will fire only when keydown will take place. In case key is pressed, flag won't be true, and hence myFunction() will not be executed. Now that you know that, button was clicked, so it has the focus. On pressing enter key, it will do perform click and keydown at same time. And myFunction() will get executed. When it gets executed, set flag to false. :)
var flag = false;
$(document).on("keydown", function() {
flag = true;
console.log("key pressed");
});
$('button').click(function() {
console.log("clicked");
if (flag) {
myFunction();
}
});
function myFunction() {
alert("Both at same time");
flag = false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click me</button>
From my understanding the resize event is triggered first, and then if the user also scrolls your custom function should be called
let resizeTriggered = false
const myResizeFunc = (event) => {
resizeTriggered = true
}
const myScrollFunc = (event) => {
if (resizeTriggered) {
myCustomFunction()
}
}
const myCustomFunction = () => {
console.log('both are happening')
}
$('#textArea').mousedown(myResizeFunc)
$(window).scroll(myScrollFunc)
div.large {
height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textArea"></textarea>
<div class="large">
</div>

stopping a recursive function call onclick button1 from a different function onclick button2

I'm trying to determine how to stop a recursive function call that came from a click to 'start_button' by calling a different function when 'stop_button' is clicked.
User clicks 'start_button' and the slide down/up animation continues to loop "infinitely" until...
User clicks 'stop_button' and the looped animations will stop.
I'd like to keep two different buttons instead of having one dual-purpose start/stop button. With my code below, the animation starts and loops, but does not stop when clicking the stop button. I'd like for the stop button to stop the animation when clicked.
http://jsfiddle.net/ZdtmZ/
var stopSliding = false;
$('#stop_button').click(function(){
stopSliding = true;
});
$('#start_button').click(function infiniteLoop(){
if (stopSliding == true)
{
$('#top_message').stop();
return;
}
else
{
$('#top_message').hide().slideDown(2000);
$('#top_message').slideUp(2000);
infiniteLoop();
return;
}
});
You are calling infiniteLoop synchronously, this means that it is impossible for any other Javascript to execute, like the click handler for your stop button. You need to make the call asynchronous so that your click handler can execute. You could use setTimeout(infiniteLoop, 0); to do this, but you still won't get the behaviour you want, because you still aren't waiting for the slider to slide up before calling infiniteLoop. So instead you should pass infiniteLoop as a callback to slideUp. That will make it asynchronous and make it wait for the animation to complete:
$('#top_message').slideUp(2000, infiniteLoop);
Your updated JSFiddle.
The problem is probably, that by the time you want to stop your animation, there are still numerous animations waiting in the queue to be executed (since your code runs way faster than the actual animations). By providing the optional argument clearQueue of the stop function, you can delete all waiting animations:
$('#top_message').stop(true)
I would write this like :
$('#start_button').click( function() {
if ( stopSliding ) return false;
$('#top_message').hide().slideDown(2000, function() {
$('#top_message').slideUp(2000, $('#start_button').click);
});
return false;
});
$('#stop_button').click( function() {
stopSliding = true;
$('#top_message').stop();
});
I just did reset the stopSliding variable to flase this way it does not stop animation if you click again on start animation .
jsfiddle
var stopSliding = false;
$('#stop_button').click(function(){
stopSliding = true;
});
$('#slide_button').click(function infiniteLoop(){
if (stopSliding == true)
{
$('#top_message').stop();
stopSliding = false;
return;
}
else
{
$('#top_message').hide().slideDown(2000);
$('#top_message').slideUp(2000, infiniteLoop);
return;
}
});

Two dom events that call the same function should call the function only once if happening in the same time

I have one input and one button. When I blur from the input and the input has changed, the price() function should be called. Also, when I click the button, the price() function should be called.
The problem is that when a user modifies the value of the input and clicks the button, the price() function is called twice. I don't want this to happen.
I tried the old-fashioned way, setting a variable "inPriceFunction" to true while entering and checking if it is not set before entering. This didn't worked because the two events (blur and click) are executed in the exact same time, the if and the variable set didn't had the time to occur.
How can I avoid that?
What I have tried:
<div>
<input type=text onchange="price();" />
</div>
<button onclick="price();" />test</button>
<script>
called = 0;
function price() {
if(called == true){
return;
} else {
called = true;
}
console.log("called");
called=false;
}
</script>
Underscore has you covered: http://underscorejs.org/#throttle
throttle will prevent your function being called twice within a
specified length of time.
once will prevent your function being called twice at all.
The click and change event do not happen at the same time. They happen one after another.
First, the "change" event is fired, setting called = true, then execute console.log("called"); and set called=false again.
Then, the "click" event is fired, but called == false, so it sets called = true; and then execute console.log("called"); and set called=false again.
Here's a jsfiddle that will do the job. You shouldn't use global variables, of course:
http://jsfiddle.net/SZe26/
var clicktimer = null;
function clickfunc() {
var BLOCK_TIME = 500;
function handleclick() {
console.log("Pressed!");
}
if (clicktimer) {
console.log("Skipping handling of click!");
} else {
handleclick();
clicktimer = setTimeout(function() {
clicktimer = null;
}, BLOCK_TIME);
}
}
The sim^pliest way to handle that might be to store a datetime whenver Price is called and use it to check if it has been called too recently.
if (refDate > new Date(10000 + (new Date())) { // 1 second delay?
return;
}
refDate = new Date();
It's likely that two calls to Date return the exact same date though (so no date manipulation would be required).
add a timeout, something like this
function schedludePrice() {
if(myTimeOut){
clearTimeout(myTimeOut);
}
myTimeOut = setTimeout('price()', 10);
}
this way if the function gets called twice in a short time by your blur and click event, the Price function will only be called once.

cursor not stopping until button click completes in window.onbeforeunload?

I have below javascript code for window.onbeforeunload. I am calling code behind button click method when pressed browser back button.
Now the problem is cursor is not stopping until $("#buttonclientid").click() completes. Just calling the method and moving to next statement. How to hold or stop cursor until $("#buttonclientid").click() complete and then move to next step?
var form_has_been_modified = 0;
$(function () {
$("input").keyup(function () {
form_has_been_modified = 1;
})
window.onbeforeunload = function (e) {
if (!form_has_been_modified) {
return;
}
doYouWantTo();
}
});
function doYouWantTo(){
doIt=confirm('Do you want to save the data before leave the page?');
if (doIt) {
var returnbutton;
//cursor should stop here until click function completes.
returnbutton = $("#buttonclientid").click();
}
else{
}
}
I believe your problem lies in the fact that your doYouWantTo function does not return a value to be passed back into onbeforeunload so it is leaving the page while also running the function, rather than waiting until it completes.
Your best action here would be something like:
return doYouWantTo()
....
if(doIt) {
$('#buttonclientid').click(function() { // unsure if you can attach callback to click but idea is same
return true;
});
} else {
return true;
}
When binding an event handler to the onbeforeunload event, it should return one of two things:
if you want a confirm to show, your handler should return a string
if you don't want a confirm to show (skip the handler), return undefined (or don't return at all, same effect)
That being said, your code should look something like this:
var form_has_been_modified = false;
$("input").keyup(function () {
form_has_been_modified = true; // use a boolean :P
});
window.onbeforeunload = function (e) {
if (form_has_been_modified) {
return 'Do you want to save the data before leave the page?';
} else {
return undefined; // this can be omitted if you prefer
}
};
The only way to tell what a user clicked on the system dialog is to use setTimeout. See this question for details on that subject.

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Categories