Before even starting, I know there already has been a thread about this, but unfortunately it did not help me at all.
So here is my problem, I have a loop written in JavaScript and at the end of it is a button click event. The event is related to a button situated inside a popup window.
for(var i=0; i<value; i++){
[...]
//some code here
[...]
//opens the window
windowButton.addEventListener('click', function(){
//code
});
//here I would like for it to continue once the click has been triggered
}
Unfortunately, it doesn't wait for the click.
Like said in the similar post, incrementing the variable i inside the function doesn't work, or even using a global variable. And the suggested answers are not what I am looking for.
[EDIT]
Okay, so I'm going to add some information to be more precise. I need to create a form. But it also needs to be able to parse a file containing all the information, and to be able to fill it. For each line of information of the file, so each time the form is completely filled, a window needs to open and wait for the validate button situated inside it.
Si I am hoping I made myself clear enough.
[/EDIT]
Thank you in advance for any reponse
There is no way to pause a function in JavaScript. You need to completely change your approach.
Move the code that you currently run each time you go around the loop into a separate function.
Create a variable outside that function.
Each time the function is called, increment that variable.
If the variable is "too big" return from the function before doing anything.
Assign that function as your click event handler.
Related
I'm not a javascript/jquery coder, and not sure if what I'm trying to do is possible.
I have a html/php/ajax form that is updated an sql database as the user fills it out. As they fill the form, there is a progress bar ran by javascript/jquery that updates as the user types in the input. The start of the function looks like this:
$("#update input").keyup(function() {
This works great. My problem is when the page is reloaded. My code is pulling sql data from the database to fill the value of every input on the page that has a value so that a user can come back and completely the form later. When the user reloads the page, the only way for the script to activate is if the user types in an input field.
I thought I would fix the issue by changing the my initial javascript/jquery function with $(document).ready(function() . This caused the script to only run when the page was loaded and not when the form was being filled out. I need both the script to run on page ready, and when a user is typing in the input filled. Is there a way I can run both $(document).ready(function() AND $("#update input").keyup(function() { simultaneously? Or is there a better why to accomplish this? Thanks!
Let me know if I need to post more code.
Here's a generic approach attaching declared functions to events.
function handler (e) {}
element.addEventListener('click', handler);
You're free to call handler everywhere, also inside $(document).ready, or if there's no other code in your DOMReady handler, you can just pass a reference as an argument:
$(document).ready(handler);
In your specific case you most likely want something like this:
$(document).ready(function () {
function handler (e) {...}
handler();
$("#update input").keyup(handler);
});
If the handler function uses the event object (e in the example), in modern browsers it's also available as a global event object, or in jQuery, e.originalEvent. The object doesn't exist if there's no event fired, though, in that case you've to pass a fake event object, containing the provided properties, to the handler, if it is needed.
I've created some code for a custom entity involving dynamically displayed questions and the ability to answer them. I'm working on being able to display previously answered questions, along with the ability to update answers. To do so, I have certain functions fire onLoad of my custom entity form, and another fire onSave.
My trouble is that my onLoad code runs every time a save happens, effectively erasing the output of the onSave code. I only want my onLoad code to run the first time the form is loaded. Otherwise, the code I want to fire onSave should handle everything else.
One way I tried to solve this was using Xrm.Page.ui.getFormType(); This returns a value of 1 or 2, with 1 corresponding to the record being created, and 2 corresponding to the record being updated. This worked for one scenario -- I didn't want my onLoad code to run when a fresh record for the custom entity was being created, and getFormType() solved this. BUT when I saved the record, the return value changed, and caused my onLoad code to run OnSave, which messed things up.
Any ideas on how I would go about solving this? I can forsee something like getFormType() being useful, but I'm at a bit of a loss on how to go about things. Thanks!
Add an onChange event handler to the modifiedon attribute, this value would only ever change after a record is saved, you can have a global parameter and set its value and use its value to stop the onLoad from re-firing again.
var canRunOnLoadCode = true;
//form onLoad function
function onLoad() {
if(!canRunOnLoadCode) return;
//on load code below
}
//register the below function on change of modified on
function afterOnSave(){
canRunOnLoadCode = false;
}
I just got through figuring out that I need to watch out for duplicate event handlers in jquery if I'm dynamically assigning them multiple times as described here: http://www.parallaxinfotech.com/blog/preventing-duplicate-jquery-click-events
Do I need to watch out for this or handle it somehow if I'm declaring a function dynamically within another function multiple times? How does JavaScript really handle this? Does it only use the last function that was called or does it only instantiate a function once at load time? From what I can tell it's not running the function multiple times.
$(document).on("click",".button",function() {
function alertThem()
{
alert('Clicked!');
}
alertThem();
});
JavaScript will remember every function you're assigning it.
$('button').click(function(){
alert('hi')
})
$('button').click(function(){
alert('hi')
})
The code above will alert "hi" twice. If you're assign new function and you want to clear the old one, you can do unbind().click(). what it will do is it will unbind all events, or you can do unbind('click') which will unbind just the click. see https://jsfiddle.net/rznbtc1p/
$('button').click(function(){
alert('hi')
})
$('button').unbind().click(function(){
alert('hi')
})
The link you provided does not work (gives me timeout) so I hope I understood what you asked.
About what happens there:
In your script you created a closure and bound it to a click event. Each time you click on the element with class button, the anonymous function is triggered. Each time is triggered it defines function alertThem(), and calls it. Only once defines it, only once calls it. The scope of that function is its parent, the closure. That function is not defined outside that scope, so no need to worry about double definition.
Side note here: Personally as a rule of thumb don't think is a good idea to define functions like this, but if it suits your project... go for it.
Now about duplication. Since I cannot see the link, I think you are referring to double event binding.
In js can bind any number of events to the same element. You can for example bind on click something that says "Hi, you clicked me", then bind also on click something that says "Hi, you received a message before saying you clicked me". When you click that element, you will see both messages.
This can actually become a problem. You have 3 options:
Be really careful how you bind events
Keep tracking of what you bound
Check if events are already bound (although that is a bit unreliable). You can check how here: jQuery find events handlers registered with an object
In your code snippet, you aren't creating duplicate event handlers.
What is happening in your snippet is that you are creating a new function alertThem within the scope of your click handler function and then executing it in the line below.
I have a weird problem that I am not able to debug.
I have a script with the following relevant functions:
a function events() that has a jQuery.on('click', callback(event)) event binder inside it. That function gets called every time I add or remove anchors with AJAX, but that's irrelevant for this problem.
a function get_passwords() which gets jQuery.attr("href") from anchor $("a.active") and makes a $.post to the server with a callback that inserts values into a table upon receiving the data
The function get_passwords() is called synchronously in the callback(event) function like this:
event.preventDefault(); //prevents a browser navigation
$("a.active").removeClass("active"); //removes active class from all other anchors
$(this).addClass("active"); //adds a class "active" to the anchor that was clicked
get_passwords(); <---- the function in question <--BREAKPOINT #1
The function get_passwords() contains the following relevant lines:
$.post("url", postData, function(data) { //put received data into table }); <--BREAKPOINT #2
Now, the weird bug is that the get_passwords() function is called multiple times by the same event listener, and only stops calling that function after an arbitrary, but constant amount of times, every time the click is made on an anchor with the event listener.
I've set the breakpoint in FireBug on the above indicated line, and as I execute the script step by step, all it does is jump between the two breakpoints set above (the part where it calls get_passwords() and where it executes $.post, 4 times (always the same amount), up until the 4th time when it actually proceeds with the callback in the $.post function.
Realizing that there is no way I can ask anyone to read through all the code that I've written, does anyone have any suggestions as to where this bug could be coming from?
Thank you in advance.
EDIT: http://jsfiddle.net/nt3A4/
Are you looking for event.stopImmediatePropagation()?
#epascarello, #nbrooks,
You were both right. I was attaching multiple event listeners, somehow, to the same anchor. Probably got lost due to my poor coding planning (I was making up website features as I went along).
Anyway, I fixed it by pre-pending $("a").off() in the events() function, as to remove any other event listeners that may have been set before. Should of done that from the beginning :/
Thank you all for your answers and your time.
When a link is clicked on my site the Javascript code below is executed, if the condition is true it will display an alert dialog. When the user selects the OK button in the alert dialog the block of code is executed again.
So the alert closes, the code below is executed for a second time and the alert dialog is displayed again. When the used selects the OK button on the alert dialog the second time the alert dialog is closed for good.
How can I prevent the code below being executed twice?
$("#my-button").click(function() {
var login = someVar;
if(!someVar || someVar == ''){
$('.close-reveal-modal').click();
alert(myMessage);
}
});
Check if you are adding the click handler twice, maybe that is what is causing that behavior.
In that case remove one of them.
From the very limited information that's provided, this is all that I can think of as going wrong:
$('.close-reveal-modal').click();
This piece of code should have some kind of function which is executed to display a similar Alert Box.
A complete code would be more useful for a complete answer!
Might not have anything to do with that code at all. Check to make sure that your javascript file isn't being called twice in the same app.
From what we have here, I'm guessing that your .close-reveal-modal element is in #my-button (or is the same html node).
When you trigger the click on it (by $('.close-reveal-modal').click();), it also trigger the click on its parent node, so on #my-button too.
I can be wrong, we need the HTML part (a fiddle would be great) to validate my theory.