function calling from another function javascript - javascript

I have 2 functions. First contains Jquery-UI dialog and called from the Second function. Something like :
function First() {
$('div').dialog({
buttons: {
"Ok": function () { /* code */
}
}
});
}
function Second() {
First();
/* rest of this function code is depend upon the "Ok button"
function code */
}
Now my problem is that after calling function First the execution of script doesn't wait for dialog's Ok button press. Whats should i do, so that only after pressing the Ok button, the control return from the function First?

Move from the function Second the part after calling First into a 2nd function (here called SecondOkHandler). Call First with a new parameter (this callback function) and in the function First on 'ok' call this:
function First(okCallback) {
$('div').dialog({
buttons : {
"Ok" : okCallback
}
});
}
function Second () {
First(SecondOkHandler);
}
function SecondOkHandler() {
/* rest of this function code is depend upon the "Ok button" function code */
}
Also see this example.
=== UPDATE ===
To make it more complex, here a link to an example with more callbacks.

This is because you have given a parenthesis First() this will make a call to that function as soon as the parser encounter that line.
You can make use of the one of the 2 Javascript methods of calling the function apply or call. By using this your function will not execute as soon it is encounter.
Check out this reference http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx
Try using this and let me know if it is not working.

function First(waitTillOk) {
$('div').dialog({
buttons: {
"Ok": function () {
/* code */
if(typeof waitTillOk == "function"){
waitTillOk();
}
}
}
});
}
function Second() {
var waitTillOk = function(){
/* rest of this function code is depend upon the "Ok button"
function code */
}
First(waitTilOk);
}

Related

One button runs a function, a second button runs a different function but only if the 1st function gets run

I have 4 buttons assigned to run 4 different functions. Seen below
document.getElementById("buttonOne").addEventListener("click", functionOne);
document.getElementById("buttonTwo").addEventListener("click", functionTwo);
document.getElementById("buttonThree").addEventListener("click", functionThree);
document.getElementById("buttonFour").addEventListener("click", functionFour);
I have another function,functionFive, that is not controlled by any button.
All of these functions set parameters on a 3D object when the given button is clicked. Clicking button one runs functionOne, setting a specific set of parameters. If those parameters are set from functionOne and I click button four, I want functionFive to be run.
If those parameters from functionOne are not set when button four is clicked, I want functionFour to run.
To clarify, I only want this functionFive to run if functionOnehas already run and its parameters are set.
Can someone help me write this script?
I've rewritten my question to fit my exact need. My original description was condensed to try and simplify it so it wouldn't be this long.
Maybe make a new boolean variable that is false when it's defined, but set to true when functionOne is run and that determines which function buttonTwo runs.
<html>
<script>
var oneClicked = false;
function functionOne() {
oneClicked = true;
alert('functionOne');
}
function functionTwo() {
alert('functionTwo');
}
function functionThree() {
alert('functionThree');
}
</script>
<button onclick="functionOne()">button one</button>
<button onclick="if (oneClicked) {functionThree()} else {functionTwo()}">button two</button>
</html>
Found the working solution to be....
var clicked = false;
function functionOne() {
/functionOne parameters
clicked = true;
}
function functionTwo() {
clicked = false;
//functionTwo parameters
}
functionFour() {
if (clicked) {
cliked = false;
functionFive()
} else {
//functionFour parameters
}
}
}

Between two event listeners: How do I pass my function without using trigger()?

Please check out my diagram, and the pseudo-code below. I'm trying to figure out how to pass a function between two event listeners.
Basically, I want to execute some code if "Availability" is less than 0, OR when a user clicks "confirm" in a bootstrap dialog. If the Availability is greater than 0, you'll get the special bootstrap dialog.
I'm trying to avoid writing the same code twice. I'm also trying to avoid using trigger $("#btnConfirm").trigger("click", fn1); --- my assumption is that there is a sexier way, like a callback, or something...
So.... how do I get the code I want to execute into the other 'button click' event listener --OR-- how do I return "btnConfirm" back to the event listener that called the dialog?
$("#Select").on("change", function(e) {
fn1 = function() {
//stuff I want to do
};
//a check that must be passed
currAvail = $("#Availability").val();
if (currAvail > 0) {
//show a message, "Are you sure you want to make the thing?"
//if YES, execute fn1()
//fn1() needs to be available to btnConfirm click listener
// use trigger("click", fn1) ????
} else {
//execute the code
fn1();
};
});
$("#btnConfirm").on("click", function(e, param1) {
//Ok, well, they said YES...
//so I need to execute fn1();
});
Since the requirement is to call fn1() in both cases, you can separate the logic out into a method and call when it is needed
function fn1() {
//code to execute on no goes here
}
$("#Select").on("change", function(e) {
let currAvail = $("#Availability").val();
if (currAvail > 0) {
//show modal window
} else {
//execute the code
fn1();
};
});
$("#btnConfirm").on("click", function(e, param1) {
fn1()
});
Why not just move the function definition to outside the change callback?
$("#Select").on("change", function(e) {
//a check that must be passed
currAvail = $("#Availability").val();
if (currAvail > 0) {
//show a message, "Are you sure you want to make the thing?"
//if YES, execute fn1()
//fn1() needs to be available to btnConfirm click listener
// use trigger("click", fn1) ????
} else {
//execute the code
fn1();
};
});
$("#btnConfirm").on("click", function(e, param1) {
//Ok, well, they said YES...
//so I need to execute fn1();
});
// Function move to here.
function fn1() {
//stuff I want to do
};

Defining generic function jquery

I have a simple function that shows a div when the user clicks on a given checkbox. I'd like to have the same behaviour on another checkbox, so that's why I'd like to generalize it as a function passing the element to be shown.
But I'm not aware of the syntax on Jquery to do so. And it's triggering automatically when the page loads. Does anybody has an idea?
Code:
$(document).ready(function() {
$("#transcricao").change(
function(){
if ($('.form_transcr').css('display') === 'none') {
$('.form_transcr').fadeIn();
} else {
$('.form_transcr').fadeOut();
}
}
); //This is working fine!
$("#traducao").change( show_hide($('.form_trad')) );
//This is auto-trigerring without user action...
});
Here's my function:
function show_hide($elm){
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($($elm).css('display') === 'none') {
$($elm).fadeIn();
} else {
$($elm).fadeOut();
}
}
Its auto-triggering without user action because you are invoking it.
Use
$("#traducao").change(function () {
show_hide($('.form_trad'));
});
As you are passing jQuery object so use it directly
function show_hide($elm) {
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($elm.css('display') === 'none') {
$elm.fadeIn();
} else {
$elm.fadeOut();
}
}
The argument to .change() should be a function. You're not passing a function, you're calling the function.
$("#traducao").change(function() {
show_hide($('.form_trad'));
} );
BTW, your show_hide function seems to be equivalent to jQuery's fadeToggle method, so it can be:
$("#traducao").change(function() {
$(".form_trad").fadeToggle();
});

Javascript async callback

My problem is better explained in code:
//This code is triggered before ajax ObBegin. But I need f1 to return a boolean to either cancel or continue the event.
f1();
function f1(){
$.modalWindow.Open(); //This is an async method, this is where my problem lies.
//I need to freeze here and wait on a return value from one of the events below.
}
//In the modal window:
//An event which waits for the click event
$('.cancelBtn').click(function(){
//How do I send false back to f1?
closeModalWindow();
});
$('.yesBtn').click(function(){
//How do I send true back to f1?
closeModalWindow();
});
So basically what happens is this:
openModalWindow() opens a modal window that waits on a button click.
I want to pass the value back to f1 and return it.
Is there a way to fix this?
Use jQuery's Deferred objects. There's a good tutorial on it here, but you haven't actually shown enough of your own code for me to demonstrate how to wire it up with $.Deferred.
Here's a very basic demo of how to do this: http://jsfiddle.net/mattball/fNQ8J/. Basically, you have to pass callbacks around for asynchronous execution.
function openModalWindow(callback) {
if (typeof callback !== 'function') callback = $.noop;
$("#dialog-confirm").show().dialog({
resizable: false,
modal: true,
buttons: {
Yes: function() {
$(this).dialog("close");
callback(true);
},
No: function() {
$(this).dialog("close");
callback(false);
}
}
});
}
function f1() {
return $.Deferred(function(dfd) {
openModalWindow(dfd.resolve);
}).promise();
}
$('#clickme').click(function() {
f1().then(function(result) {
alert('f1 async returned: ' + result);
});
});
There's no good way to do this, no. You'll have to refactor f1 so it can deal with asynchronicity.
f1() should be implemented as a callback for someAsyncFunc():
function someAsyncFunc(callback) {
// open your modal window
$(".theBtm").click(function() {
// do your stuff
if (typeof(callback) === "function") {
callback(theValueYouWantToPass);
}
});
}
Called something like this:
someAsyncFunc(function(value) { f1(value); });

Using Jquery calling different functions with a singe link

I would like to use single a href link to call different functions .
On first click it should call first_function() and on second click it should call second_function. Like toggling between two functions using same link. Suggest the best way to be done.
Jquery Code :
$(function() {
var IntervalId;
function first_function() {
//code goes here
};
function second_function(){
//code goes here
}
$("#link2").click((function(){
second_function();
}));
$("#link1").click((function(){
first_function();
}));
});
Html Code :
Call function2
Call function1
"Like toggling between two functions using same link."
$("#link1").toggle(
function first_function() {
// Code goes here
},
function second_function(){
// Code goes here
}
);
From the jQuery docs on toggle(fn1, fn2, [fn3, [fn4, [...]]]):
Toggle among two or more function calls every other click.
Javascript:
$(document).ready(function() {
function first_function() {
// Code goes here
};
function second_function(){
// Code goes here
}
$("#link").toggle(first_function, second_function);
});
HTML:
<!-- I'm pretty sure that <a> isn't the right tag for this. -->
<button id="link">Toggle between the two functions.</button>
the easiest way would be
var performFirstAction = true;
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").click(function(){
if(performFirstAction) {
first_function(); performFirstAction = false; }
else {
second_function(); performFirstAction = true; }
});
});
or using toggle as Tomalak mention and well,
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").toggle(
first_function,
second_function
);
});

Categories

Resources