How to trigger a delayed jQuery event? - javascript

I'm writing a workaround for web form. The given problem is that hitting Submit pops out a loading animation. The content is saved, but the form is still shown, as is the loading animation.
The idea is to trigger an event, 2-3 seconds after the Submit click, that will reset the form content and hide the loading animation.
How would you suggest to approach this?
Thank you.

Use the callback functions in the events to chain them together - that way it will make sure that the action has completed, instead of trying to run all of them at the same time. If you post some code we can probably help some more. There's also the .delay() function, but I think callbacks are more appropriate, because your process is event driven and not time driven. You have more flexibility in the case that something in the process goes wrong, instead of statically resetting after a click.

Can you just use a setTimeout(...) that calls a method that resets form content and hides the animation? See: http://www.w3schools.com/js/js_timing.asp

jQuery Form came to the rescue.
$('form#id').ajaxForm(function() {
// do stuff
});
This will run the callback after the form is submitted.

Related

Why is telling jQuery to click my link button slowing my page down?

I don't know if this is the effects of an update panel or what, but I basically have a drop down list that allows a user to select an item as a filter. When the item is selected it should bring back only one item into a grid view. That is this specific filter will at most bring back the record you are looking for. This works fine if the user clicks an "apply" link to apply the filter. Behind the apply link is some server-side code (C# within an ASP.NET Web Forms application).
We had a request by a user with something to the effect of:
"Why do I have to click the apply button if I make a selection in this
one drop down filter...it should simply get that one record I am
searching for. This helps me because I don't have to click the
"Apply" button."
I agreed with him and thought what is the easiest way to do this...I thought: Simple, I will have an on change event handler of the drop down such that when a selection is made I'll trigger a click event. Something to this effect:
$("#MainContent_ddlCompany").on("change", function() {
var companyId = $("#MainContent_ddlCompany").val();
$("#MainContent_hdnCompanyValue").val(companyId);
$("#<%=ddlCompany.ClientID %>").trigger("chosen:updated");
if (companyId.length > 0) {
$(".apply").click();
$(".apply").removeClass("applyButton");
$(".apply").addClass("resetButton");
} else {
//cleared selection of a company
$(".apply").removeClass("resetButton");
$(".apply").addClass("applyButton");
}
});
At first this didn't work, and I couldn't tell why, but then after some serious googling I changed this line:
$(".apply").click();
To this:
$('.apply')[0].click();
That worked great...so I decided to test it some more. As I kept selecting one filter value after another I noticed the page started to slow down. In fact by the 6th or 7th time it was pretty unusable. I don't know why it's happening, but I suspect again it has to do with the fact that this linkbutton with the class name .apply is inside an update panel.
But still I thought to myself, it was inside of an update panel before I changed my jQuery code to simulate the click event. So why does the page slow down and drag with this little piece of code? Is calling the event from jQuery code rendering something else in the HTML that could be causing this?
If I change my code back and force the user to click the apply button then we are back to a good normal speed. Why is it if I tell jQuery to simulate clicking the button my page slow down? It's doing the same thing, the simulation of the click of this link button is calling its server-side code method whether the user clicks it or I have jQuery click it.
For now I'm at a loss as to why this is happening because this button is in an update panel in either case, yet when I have jQuery click it via $('.apply')[0].click(); the page slows down after several attempts. Yet when I have the user simply click this button (without the jQuery click event) then it works fine?
What am I missing here?
Ugh, well, I found my issue. Because I was using updatepanels I had to wrap my jQuery code to include an add_endRequest. That is, you have something to the effect of:
$(document).ready(function() {
//Some initial event/triggers
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
//Copy of some initial event/triggers
});
});
Why do I use the endRequest you ask? Well, because updatepanels basically throw away all your events after an asynchronous postback because the HTML at that point (after an update) is rendered again and at that point all events associated with any control inside an update panel are wiped away. At this point of course document.ready() does not run, so I have to resubscribe to these events inside of endRequest. Enter my issue...
I had a huge brain fart where I basically took everything, literally everything inside document ready and copied it into endRequest. In fact, if I remember correctly, I read articles which stated
Whatever you have in document ready simply copy paste into endRequest
That's fine, but you have to be careful here. I was throwing in events that were not wrapped around inside of an updatepanel into endRequest. The result is disastrous...at least for me.
These events would be attached then multiple times..or based on the number of asynchronous postbacks made. In my case, as I was testing I mentioned after the 6th or 7th time performance starts degrading. Well, by that time my controls were being attached that many times to events. For instance, my .apply button along with my dropdownlist were both outside of my updatepanel. But my jQuery code was attaching the change event of my dropdownlist in both document ready and endRequest.
The result is initially it's pretty fast, because it's only in document ready. But as I make asynchronous postbacks these events are being attached every time. For n tests I would have n attached events...in my case the test of 7 yields 7 on change event handlers!
Case in point, do not place any event handlers such as jQuery's on() event for any controls that are NOT inside an update panel. Otherwise you will run into what I ran into which was poor performance as events are happening.

Is there a way to extend a jQuery event handler that is already bound?

I've written a code that clears the form on every reset event like that:
$("form").on("reset", function(event) {
event.preventDefault();
$("form").clearForm();
$("#reportGenerated").empty();
});
This code is inside an external js loaded in every page so this handles the entire system.
In one specific form in my system I have three inputs that loads Ajax requests into another parts of the page, then when I try to reset and clear the form the information provided by the Ajax request isn't cleared.
So my question is, is there a way I can extend my functionality above without being forced to copy/paste what it already does?
I've read the jQuery Event Extension but does not seem to do what I need, plus, is quite "dangerous" to do it if you don't know exactly how every browser and its version handle JavaScript events.
You can easily add another click handler with will run along with this one(no need to do anything in the already existing handler).
$("form").on("reset", function(event) {
//do your custom stuff here
});

jQuery trigger and bind to event on page load?

How can I both trigger and bind to an event after the page load?
The problem I am having is that in one place, on page-load I fire an event:
//producer.js
pageLoaded(){
var e = jQuery.Event("eventA");
$("body").trigger(e);
...}
and in another I bind to it:
//consumer.js
pageLoaded(){
$("body").bind("eventA", function(args){console.log("Got it!");} );
... }
The problem is that the first time event is fired (when page is loaded) - the consumer does not see it. The second time event is fired, however, everything is fine!
I am guessing this is because event is actually fired BEFORE consumer starts listening to it.
Is there a good practice to follow when creating "triggers" and "listeners" to events - that have to work both on page load, and later?
If there are no listeners when you triggered an event nothing will happen which is why you are not seeing anything on the first trigger.
Sounds like you need to control the order of document.ready() calls .. perhaps the responses to this question or this article might assist you
Using something like RequireJS will allow me to first load one javascript file, and then another.
So I can make producer.js dependent on consumer.js

Page elements don't visibly update during load

I'm probably missing something really obvious here...
I'm showing a dialog box with progress bar during page load. The dialog and progress bar are both jQueryUI widgets. There are a couple of phases of loading - the page makes a load of jQuery $.get() requests to load resources, then on the $(document).ajaxStop() event, does things with those resources. I'm updating the progress bar and some status text throughout this process.
The issue is that as soon as the ajaxStop event fires, updates stop. The code works nicely during resource loading, but then freezes and I don't see any of the updates during processing. If I put a breakpoint on a post-ajaxStop update in Chrome and step through the code, the screen updates correctly so I know that the code works.
Can anyone explain why everything updates nicely during my AJAX loading phase, but then stops on the ajaxStop event? Is there an easy way to make updates continue afterwards?
Thanks!
Several hours of searching later, the following blog pointed me in the right direction:
There's a jQuery extension described in the entry which allows you to define two functions, one to compute and one to update the UI. It schedules them alternately using the setTimeout function.
I've had to rewrite my code in something akin to continuation passing style so that each function schedules its continuation to run using setTimeout. This returns control to the browser for long enough for the screen to be updated.
This feels like a bit of a hack though to get round browser/Javascript limitations. Anyone know of a better way?

Validation plugin hijacks click function?

Absolute newbie question, any help is highly appreciated :)
I am using curvycorners (http://www.curvycorners.net/) in combination with the jQuery validation plugin (http://bassistance.de/jquery-plugins/jquery-plugin-validation/), and I'm having problems getting the div to redraw the rounded corners when I do like this:
$("input[type='submit']").click(function(e) {
curvyCorners.redraw();
});
When I click the submit-button the first time the form validates, the validation error-message pops up and expands the div, causing the layout to go ugly. However when I click on it the second time the rounded corners redraw nicely.
Could it be that my validation plugin hijacks my initial click? How do I go about this? Any hint is very much appreciated.
Make sure that the handler you have above is set before the validation code is called. Event handlers are executed in the order they were bound, so if the validation plugin is cancelling the event, then you want to be attached before it does so.
In short, attach your handler first to make sure it gets executed and something else doesn't interfere.
Disclaimer: This isn't always true, something trying to interfere can (.unbind() for example) but it should solve your issue. If you see the same behavior after doing this, please provide more detail, something else is interfering.

Categories

Resources