Wait for all async functions to complete in jQuery - javascript

I'm filtering table using jQuery and all is well. This code works nicely:
$("*[id$='EquipmentTypeDropDownList']").change(filterTable);
$("*[id$='StateDropDownList']").change(filterTable);
function filterTable() {
var $equipmentDropDown = $("*[id$='EquipmentTypeDropDownList']");
var $stateDropDown = $("*[id$='StateDropDownList']");
var equipmentFilter = $equipmentDropDown.val();
var stateFilter = $stateDropDown.val();
$("tr.dataRow").each(function () {
var show = true;
var equimpent = $(this).find("td.equipment").text();
var state = $(this).find("td.readyState").text();
if (equipmentFilter != "Any" && equipmentFilter != equimpent) show = false;
if (stateFilter != "Any" && stateFilter != state) show = false;
if (show) {
$(this).fadeIn();
} else {
$(this).fadeOut();
}
});
$("table").promise().done(colorGridRows);
}
function colorGridRows() {
//for table row
$("tr:visible:even").css("background-color", "#DED7D1");
$("tr:visible:odd").css("background-color", "#EEEAE7");
}
colorGridRows function changes background color of even/odd rows for readability
Now, It would be nice if I can replace show/hide calls with fadeIn/fadeOut but I can't because coloring doesn't work (it runs before UI effect completed. If it was just one function parameter - I would just create function for completion and be done with it. But my table has many rows and loop runs through each. How do I wait for ALL to compelete?
EDITED: Code sample updated showing how I try to use promise() but it doesn't work. It fires but I don't get odd/even coloring.

Use the promise object for animations.
$("*[id$='StateDropDownList']").change(function () {
var filtervar = $(this).val();
$('tr td.readyState').each(function () {
if (filtervar == "Any" || $(this).text() == filtervar) {
$(this).parent().fadeIn();
} else {
$(this).parent().fadeOut();
}
}).parent().promise().done(colorGridRows);
//colorGridRows();
});

Related

DevExtreme DataGrid onRowDblClick

I want to implement an onRowDblClick event for the DevExtreme DataGrid.
I need this Event for multiple grids so I would like to implement this for the DataGrid for general.
I was thinking about overriding the onClick action and check for a double click or extend the DataGrid with an onRowDblClick Action but i have no idea how to implement this.
Please advise a way to do this functionality.
OK, finally I implemented an addRowDblClick function which looks like this:
var clickTimer, lastRowClickedId;
function addRowDblClick(id, dblClickFunc) {
$("#" + id).dxDataGrid({
onRowClick: function (e) {
//OBTAIN YOUR GRID DATA HERE
var grid = $("#" + id).dxDataGrid('instance');
var rows = grid.getSelectedRowsData();
if (clickTimer && lastRowCLickedId === e.rowIndex) {
clearTimeout(clickTimer);
clickTimer = null;
lastRowCLickedId = e.rowIndex;
//YOUR DOUBLE CLICK EVENT HERE
if (typeof dblClickFunc == 'function')
dblClickFunc();
} else {
clickTimer = setTimeout(function () { }, 250);
}
lastRowCLickedId = e.rowIndex;
}
});
}
And at the DataGrid I called an function OnContentReady where I call this function with the Id and the function I want to call when I double click.
addRowDblClick('dxDataGrid', showDetail);
I that work with this :
$("#grdMain").dxDataGrid({
....
onRowPrepared:function(event){
$(event.rowElement).on('dblclick', function(){
console.log('row dblclicked');
}).on('remove', function(){
//on remove event in jquery ui libraries or
// https://stackoverflow.com/questions/29255801/jquery-on-remove-not-working-parent-node-fire-empty
$(this).off('dblclick remove');
})
}
})
I did this and worked pretty well (I followed this answer)
var clickTimer, lastRowCLickedId;
$("#grdMain").dxDataGrid({
...
onRowClick: function (e) {
//OBTAIN YOUR GRID DATA HERE
var grid = $("#grdMain").dxDataGrid('instance');
var rows = grid.getSelectedRowsData();
if (clickTimer && lastRowCLickedId === e.rowIndex) {
clearTimeout(clickTimer);
clickTimer = null;
lastRowCLickedId = e.rowIndex;
//YOUR DOUBLE CLICK EVENT HERE
alert('double clicked!');
} else {
clickTimer = setTimeout(function () { }, 250);
}
lastRowCLickedId = e.rowIndex;
}
});

WinJS listview iteminvokedHanlder how to

I'm using the iteminvokedHandler and was wonder if there is a better way to interact with the listView.
Currently using this:
WinJS.UI.processAll(root).then(function () {
var listview = document.querySelector('#myNotePad').winControl;
listview.addEventListener("iteminvoked", itemInvokedHandler,false);
function itemInvokedHandler(e) {
e.detail.itemPromise.done(function (invokedItem) {
myEdit();
});
};
});
The problem is that everytime I click on the listview myEdit() is run and propagates within the listview. I was wondering how to do it once and stop invoking listview until I am done with myEdit? Is there a simpler way to handle such a situation as this?
Simple yet hard to see when you have a mind block and forget some of the basics (yes yes I'm still learning):
var testtrue = true;
WinJS.UI.processAll(root).then(function () {
var listview = document.querySelector('#myNotePad').winControl;
listview.addEventListener("iteminvoked", itemInvokedHandler,false);
function itemInvokedHandler(e) {
e.detail.itemPromise.done(function (invokedItem) {
if (testtrue === true){
myEdit();
}
});
};
});
In myEdit:
function myEdit() {
var theelem = document.querySelector(".win-selected #myNotes");
var gestureObject = new MSGesture();
gestureObject.target = theelem;
theelem.gestureObject = gestureObject;
theelem.addEventListener("pointerdown", pointerDown, false);
theelem.addEventListener("MSGestureHold", gestureHold, false);
function pointerDown(e) {
e.preventDefault();
e.target.gestureObject.addPointer(e.pointerId);
}
function gestureHold(e) {
if (e.detail === e.MSGESTURE_FLAG_BEGIN && test === true) {
e.preventDefault();
editNotes();
} else {
}
console.log(e);
}
theelem.addEventListener("contextmenu", function (e) {
e.preventDefault();}, false); //Preventing system menu
};
function editNotes() {
//The Code I wish to execute
return test = false;
};
What I needed was a conditional statement so that it would run if true and not if false. That same test needed to be done in the gestureHold otherwise it would continue to fire myEdit on the invoked item because of the way the gesture is attached to the item the first time it is run.

How to handle click event being called multiple times with jquery animation?

I have a click event that has a Jquery animation in it.
How can i guarantee that the animation has finished when multiple click events are being fired.
$(this._ScrollBarTrack).click(function(e) {
if(e.target === this && _self._horizontalClickScrollingFlag === false){
_self._horizontalClickScrollingFlag = true;
if(_self._isVertical){
} else{ //horizontal
if(e.offsetX > (this.firstChild.offsetWidth + this.firstChild.offsetLeft)){ // Moving Towards Right
var scrollableAmountToMove = _self._arrayOfCellSizes[_self._scrollBarCurrentStep + 1]; // additional amount to move
var scrollableCurrentPosition = -($(_self._bodyScrollable).position().left);
var scrollBarCurrentPosition = $(_self._ScrollBarTrackPiece).position().left;
var scrollBarAmountToMove = _self.getScrollBarTrackPiecePositionBasedOnScrollablePosition(scrollableAmountToMove);
$(".event-scroll-horizontally").animate({left:-(scrollableCurrentPosition+ scrollableAmountToMove)});
$(_self._ScrollBarTrackPiece).animate({left: (scrollBarCurrentPosition + scrollBarAmountToMove)});
_self._scrollBarCurrentStep += 1;
} else{
var scrollableAmountToMove = _self._arrayOfCellSizes[_self._scrollBarCurrentStep - 1]; // additional amount to move
var scrollableCurrentPosition = -($(_self._bodyScrollable).position().left);
var scrollBarCurrentPosition = $(_self._ScrollBarTrackPiece).position().left;
var scrollBarAmountToMove = _self.getScrollBarTrackPiecePositionBasedOnScrollablePosition(scrollableAmountToMove);
$(".event-scroll-horizontally").animate({left:-(scrollableCurrentPosition - scrollableAmountToMove)});
$(_self._ScrollBarTrackPiece).animate({left: (scrollBarCurrentPosition - scrollBarAmountToMove)});
_self._scrollBarCurrentStep -= 1;
}
}
_self._horizontalClickScrollingFlag = false;
}
});
jQuery has a hidden (I'm not sure why it's not in the docs someplace) variable $.timers that you can test against.
I made this function a long time ago to handle situations like this. Mind you, this will test to make sure there are NO animations currently being executed.
function animationsTest (callback) {
var testAnimationInterval = setInterval(function () {
if ($.timers.length === 0) { // any page animations finished
clearInterval(testAnimationInterval);
callback(); // callback function
}
}, 25);
};
Useage: jsFiddle DEMO
animationsTest(function () {
/* your code here will run when no animations are occuring */
});
If you want to test against one individually you could do a class/data route.
$('#thing').addClass('animating').animate({ left: '+=100px' }, function () {
// your callback when the animation is finished
$(this).removeClass('animating');
});
You could declare a global boolean called isAnimating and set it to true right when you begin the animation. Then add a done or complete function to the animation that sets it back to false. Then set your click event to only begin the animation if isAnimating is false.

Problems to run Jquery code on button click on my Wizard-step Jquery code

I am using Wizard-step for my form in a view, My project is on MVC3.
I have a form that is made on 3 steps which means I have three tags for each step in my form
and two buttons that are following:
<p><input type="button" id="next-step" class="next-step-client-val" name="next-step" value="Next" /></p><
<p><input type="button" value="Back id="back-step" name="back-step"></p>
In my first step I have only a bunch of TextBoxes, DropDownlists and TextAreas, second step have alot of client-side functionality, one example is that user can move rows from a table to another one etc.. And I have a Jquery validation that is following:
var customTbl = $('#CustomPickedTable');
var has1 = customTbl.find('td[data-row="1"]').is('*');
var has2 = customTbl.find('td[data-row="2"]').is('*');
var has3 = customTbl.find('td[data-row="3"]').is('*');
var has4 = customTbl.find('td[data-row="4"]').is('*');
if ((has1 === true) && (has2 === true) && (has3 === true) && (has4 === true)) {
jAlerts("Saved", "Info");
} else {
jAlert('You have to move atleast one row from each table', "Varning"); ;
return false
}
On the 3th step its just a review on what was created and my next-step button submits the form, when a user clicks on it.
What I want to be able to do is that when a user is on the 2th step and clicks on next-step button the jquery validation above should run. With my Wizard-step code I cant do that beacuse it uses next-step button selector for everything. Is there any solutions for this?
I have tried to put my Jquery validation code inside
$("#next-step").click(function () {
}
But then my jquery validation code run everytime a user clicks on next button, beacuse my tables are shown in the form but hidden, the validation triggers on first step when a user click on next. So that solution didnt work.
This is my Wizard-step Jquery Code and right now I have my Jquery validation in the bottom which means that when im on 3th step and click on next-step button it will validate and then post. But I dont want it to be like that. I want the validation to happen on the 2th step.
Here is the code:
$(function () {
$(".wizard-step:first").fadeIn(); // show first step
// attach backStep button handler
// hide on first step
$("#back-step").hide().click(function () {
var $step = $(".wizard-step:visible"); // get current step
if ($step.prev().hasClass("wizard-step")) { // is there any previous step?
$step.hide().prev().fadeIn(4500); // show it and hide current step
// disable backstep button?
if (!$step.prev().prev().hasClass("wizard-step")) {
$("#back-step").hide();
}
}
});
// attach nextStep button handler
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("select").each(function () {
if (!this.disabled && !validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
$("#next-step").click(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
if ($step.next().hasClass("confirm")) { // is it confirmation?
// show confirmation asynchronously
$.post("/wizard/confirm", $("form").serialize(), function (r) {
// inject response in confirmation step
$(".wizard-step.confirm").html(r);
});
}
if ($step.next().hasClass("wizard-step")) { // is there any next step?
$step.hide().next().fadeIn(4500); // show it and hide current step
$("#back-step").show(); // recall to show backStep button
}
else { // this is last step, submit form
var selectedQuestions = $("#SelectedQuestions");
var selectedCustomQuestions = $("#SelectedCustomQuestions");
var currentIds = new Array();
var currentText = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
});
$('#CustomPickedTable td[data-attr-id]').each(function () {
var ClickedText = $(this).html();
currentText.push(ClickedText);
});
selectedCustomQuestions.val(currentText.join("|"));
selectedQuestions.val(currentIds.join(","));
var customTbl = $('#CustomPickedTable');
var has1 = customTbl.find('td[data-row="1"]').is('*');
var has2 = customTbl.find('td[data-row="2"]').is('*');
var has3 = customTbl.find('td[data-row="3"]').is('*');
var has4 = customTbl.find('td[data-row="4"]').is('*');
if ((has1 === true) && (has2 === true) && (has3 === true) && (has4 === true)) {
jAlerts("saved", "Info");
} else {
jAlert('You have to move atleast one row from each table', "Varning"); ;
}
return false;
}
});
My html code looks something like this:
<div class="wizard-step>
//step 1 content
</div>
<div class="wizard-step>
//step 2 content
</div>
<div class="wizard-step>
//step 3 content
</div>
<p><input type="button" id="next-step" class="next-step-client-val" name="next-step" value="Next" /></p><
<p><input type="button" value="Back id="back-step" name="back-step"></p>
I think it would be better if you detect at which wizard step you are using jquery .index() function. This way you can do the validation in your next step click handler only if you are on second step moving on to the third step. The code would look something like this :
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
var stepIndex = $(".wizard-step").index($step); //index returns 0 based index so second step would be 1.
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("select").each(function () {
if (!this.disabled && !validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
if(stepIndex == 1) //if you are on second step then validate your table
{
var customTbl = $('#CustomPickedTable');
var has1 = customTbl.find('td[data-row="1"]').is('*');
var has2 = customTbl.find('td[data-row="2"]').is('*');
var has3 = customTbl.find('td[data-row="3"]').is('*');
var has4 = customTbl.find('td[data-row="4"]').is('*');
if ((has1 === true) && (has2 === true) && (has3 === true) && (has4 === true)) {
jAlerts("Saved", "Info");
} else {
jAlert('You have to move atleast one row from each table', "Varning"); ;
return false
}
}
else if ($step.next().hasClass("confirm")) { // is it confirmation?
// show confirmation asynchronously
$.post("/wizard/confirm", $("form").serialize(), function (r) {
// inject response in confirmation step
$(".wizard-step.confirm").html(r);
});
}
if ($step.next().hasClass("wizard-step")) { // is there any next step?
$step.hide().next().fadeIn(4500); // show it and hide current step
$("#back-step").show(); // recall to show backStep button
}
else { // this is last step, submit form
var selectedQuestions = $("#SelectedQuestions");
var selectedCustomQuestions = $("#SelectedCustomQuestions");
var currentIds = new Array();
var currentText = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
});
$('#CustomPickedTable td[data-attr-id]').each(function () {
var ClickedText = $(this).html();
currentText.push(ClickedText);
});
}
});
I think you could approach this problem by refactoring the code
// validate the inputs in a form
// #param {string|object} jquery selector or jquery object
function validateStep (selector){
var $step = $(selector);
var validator = $("form").validate();
var anyError = false;
$step.find("select").each(function () {
if (!this.disabled && !validator.element(this)) {
anyError = true;
}
$step.find("input").each(function () {
if (!validator.element(this)) {
anyError = true;
}
if (!validator.element(this)) {
anyError = true;
}
return anyError;
}
This way you could validate the second step by calling
// this works because jquery returns an array of objects
// as a result of the css selector we call it with
// the eq() function accepts an index value that returns
// the jquery object at that position
// see. http://api.jquery.com/eq-selector/
validateStep($('.wizard-step').eq(1));
Or the first
validateStep('.wizard-step:first');
Etc
We could incorporate this into your code like this -
$('#next-step').click(function (event){
var $step = $('.wizard-step');
if(validateStep($step.filter(':visible'))){
// go to the next step
if ($step.next().hasClass("wizard-step")) {
$step.hide().next().fadeIn(4500);
$("#back-step").show();
} else {
// submit form
}
}
});
NB: You can read more about jQuery selectors here http://api.jquery.com/category/selectors/

make 'each' cycles occur consecutively

I have two actions I need to apply to a set of DIV's, but I need one cycle to happen before the other is finished.
Here is my code:
$("div").each(function(){
//do stuff first
}).each(function(){
//do stuff next
});
but at present, do stuff next happens before do stuff first finishes. Anything I can do to stop this?
Full Script
$("div").each(function(){
if($(this).html() === "yes"){
$(this).fadeOut(time,function(){
$(this).parent().height(0);
});
}
}).each(function(){
if($(this).html() !== "yes"){
$(this).parent().height(25);
$(this).fadeIn(time);
}
});
Knowing that you want to fadeIn and then set height, will this do what you require?
var divs = $('div');
divs.fadeIn(function () {
divs.height('200');
});
Using each to allow different settings for different divs:
$('div').each(function () {
var div = $(this), toggle = true;
div.fadeIn(function () {
if (toggle = !toggle) {
div.height('200');
} else {
div.width('200');
}
});
});
Seeing your code snippet I believe I got it now:
var yesDivs = $('div').filter(function () {
return $(this).html() === 'yes';
});
yesDivs.fadeOut(time, function () {
yesDivs.parent().height(0);
$('div').filter(function () {
return $(this).html() !== 'yes';
}).fadeIn(time).parent().height(25);
});

Categories

Resources