how to pass a callback function to a button? - javascript

i have a php project which includes a few js files.
One of the js files, is a popup manager. This is the code:
function openYesNoPopup(message, callback) {
$('.popupBtn').unbind();
var popup_top = "<div class = 'popup_top'></div>";
var popup_bottom = "<div class = 'popup_bottom'></div>";
var yesNoButtonsDiv = '<div class="popupBtnContainer"><button class="popupBtn" data-type="yes">Yes</button><button class="popupBtn">No</button></div>';
$.fancybox.open({
padding: 0,
content: message
});
$('.fancybox-skin').prepend(popup_top);
$('.fancybox-skin').append(popup_bottom);
$('.fancybox-outer').append(yesNoButtonsDiv);
$(document).on('click', '.popupBtn', function() {
if ($(this).data('type') === 'yes') {
callback;
}
$.fancybox.close();
});
}
The problem is, the callback function that i want exacuted, is undefined.
Can anyone help me make this right?
Thank you!
the call to openYesNoPopup:
openYesNoPopup("Hello World",foo());
function foo(){
alert("bear");
}
for some reason, the alert is shown right on start...

You'd have to actually call it
if ($(this).data('type') === 'yes') {
callback();
}
but when calling the openYesNoPopup function, you'd reference it, not call it
openYesNoPopup("Hello World",foo);

Related

Using callbacks JS / JQuery

I am trying to use callbacks in order to effectively "overwrite" the standard alert and confirm actions in JavaScript.
The code I am using is a bit long winded so I jotted it into a working jsfiddle
I am trying to get it so that a callback is used to determine true or false, but it is coming back as undefined as the callback function is fired before a click is
My questions, is how can I change this to effectively overcome the functions value being returned before the click is called via jQuery?
Example usage:
<button onclick="confirm('This is a test')">Show dialog (confirm)</button>
Example jQuery events:
if (confirm("This is a test")) {
alert("Confirmed")
}
else {
alert("Did not confirm")
}
Edit
Using a loop within the callback messed it us a lot...
You are mixing things up when waiting for the return value.
You are passing dialog.checkForInput as the callback. But in the dialog.show() function you do:
var ret = callback();
...
return ret;
But the dialog.checkForInput function doesn't return anything, it merely sets event listeners.
As events all run "asynchronously" it would be more sensible to give your dialog a callback function which will be run when there actually would be an event. Meaning: in your checkForInput function (I would name it differently, but whatever) run the callback and pass the action as a parameter. Something like:
checkForInput: function () {
$(document).ready(function () {
$(".dialog_confirm_okay").on("click", function () {
dialog.hide();
callback('confirm');
})
$(".dialog_confirm_cancel").on("click", function () {
dialog.hide();
callback('cancel');
})
$(".dialog_alert_okay").on("click", function () {
dialog.hide();
callback('alert');
})
})
}
And your callback could look like this (assuming your callback was called dialogCallback):
function dialogCallback ( action ) {
alert('Dialog closed with action: ' + action);
};
Some points I conclude from your code:
The reason why statement callback() return undefined value is because dialog.checkForInput return nothing.
The $(document).ready inside checkForInput is async, so returned value from that block is meaningless (it won't become the return value of the checkForInput as well).
And also you put the return statement inside event declaration, it'll become return value of the event (when the event triggered), not the checkForInput.
I did some modification on your code, this one working. Basically I create new method called onclick, which will be called every time button yes or no is clicked.
show: function (e_type, e_content) {
var d = dialog;
var d_head = e_type == "confirm" ? "Confirm Action" : "Error";
var d_buttons = e_type = "confirm" ? d.parts.buttons.okay + d.parts.buttons.cancel : d.dparts.buttons.alert_okay;
var _dialog = d.parts.main + d.parts.head.replace("{DIV_HEADER}", d_head) + d.parts.body + e_content + "<div class='dialog_button_container'>" + d_buttons + "</div>" + d.parts.footer;
$("body").append(_dialog);
},
onclick: function (ret) {
$(".errors").text("Return value was: " + ret);
},
showError: function (e_content) {
dialog.show("alert", e_content);
dialog.checkForInput();
},
showConfirm: function (e_content) {
dialog.show("confirm", e_content);
dialog.checkForInput();
},
checkForInput: function () {
var self = this;
$(".dialog_confirm_okay").on("click", function () {
dialog.hide();
self.onclick(true);
})
$(".dialog_confirm_no").on("click", function () {
dialog.hide();
self.onclick(false);
})
$(".dialog_alert_okay").on("click", function () {
dialog.hide();
self.onclick(false);
})
},
Working example: https://jsfiddle.net/p83uLeop/1/
Hope this will help you.
EDITED
From the comment section I assume that you want this alert to become a blocking function like window.confirm, so you can do something like if (confirm('Are you sure')).
But sadly it's impossible to achieve this case.
I have some suggestion, you can encapsulate your code better, and implement clean callbacks or promises. Maybe something like this:
showConfirm(function (ok) {
if (ok) {
// "yes" clicked
} else {
// "no" clicked
}
})
// or
showConfirm(function () {
// "yes" clicked
}, function () {
// "no clicked"
})
// or
var customConfirm = showConfirm()
customConfirm.on('yes', function () {
// "yes" clicked
})
customConfirm.on('no', function () {
// "no" clicked
})

Passing parameters to a event listener function in javascript

Hello I have some code in which I take user input through in html and assign it to,two global variables
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
Which next show up in this addeventlistener function as parameters of the whowon function
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
The click event is meant to trigger the whowon function and pass in the parameters
function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {
if (FirstScore > SecondScore) {
FirstTeam.win();
SecondTeam.lose();
} else if (FirstScore < SecondScore) {
SecondTeam.win();
} else {
FirstTeam.draw();
SecondTeam.draw();
}
}
However the values are null,as I get a cannot read properties of null error on this line
var spursscoref = document.getElementById("spursscore").value;
I am pretty sure the problem is coming from the addlistener function,any help would be appreciated
Well you could do something like this -
$( document ).ready(function() {
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
});
Wrap your code in $(document).ready(function(){}). This will ensure that all of your DOM elements are loaded prior to executing your Javascript code.
Try putting all of your code inside this
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
My guess is that your code is executed before the html actually finished loading, causing it to return null.

jquery.each not working after jquery.load

I use jQuery.load to load the HTML template. After this I'm trying to get HTML content from each loaded HTML element. The HTML is loading but I can't get the HTML content.
Here is the code:
var _InterfaceBuilder = function() {
var k45 = new _K45Kit;
var _this = this;
this.build = function(element) {
var error = false;
switch(element) {
case 'loginPanel':
$('#content').load('template/loginPanel.html', _this.localize(element));
break;
//sth else
}
// sth else
};
this.localize = function(section) {
$(".loginPanel.localString").each(function(index) {
console.log($(this).html());
});
//sth else
});
When I put
$(".loginPanel.localString").each(function(index) {
console.log($(this).html());
});
into the firebug console it works correctly. Can someone help me?
The 2nd parameter for $.load() must be a function that will be called once completion. You are not providing a function, but the result of calling _this.localize(element). So basically, the localize function is called before adding the listener, and since it returns undefined you have no handler.
Try with:
$('#content').load('template/loginPanel.html',
function(){
_this.localize(element);
});

Shaking effect in my javascript code

I was just trying to use a function of jQuery in my JavaScript code for styling. I want that whenever the required text field is empty, the textfield should shake, but I can't do it. Please help me out I just wasted my whole night on it. Finally asking for your help. I hope that you people get my question.
The code is given below
function validate() {
var em = document.getElementById("email_value").value;
var pass = document.getElementById("password_value").value;
if(em == "") {
shakeIt();
}
}
$(document).ready(function() {
function shakeIt() {
$("input").effect("shake", { times:5}, 50);
}
});
function validate()
{
var em = document.getElementById("email_value").value;
var pass = document.getElementById("password_value").value;
if(em == "")
{
shakeIt();
}
}
function shakeIt()
{
$("input").effect("shake",
{
times: 5
}, 50);
}
Don't wrap it in $(document).ready() function, because your shakeIt function is not longer in global scope, if you do so.

Jquery Impromptu function running order problem

I I hafe a function which uses the $.prompt Jquery (impromptu) pluggin. This works fine except that whenever I call the function it is run right at the end of the function that it was called from.
Here is the function...
function addfile(){
var txt = '<?php echo $JSString; ?>';
function mycallbackform(v,m,f){
if(v != undefined)
var newText = f.alertName + " , " + f.alertName.replace("-", " ").replace(".php", "");
alert(newText);
}
$.prompt(txt,{
callback: mycallbackform,
buttons: { Add: 'add', Cancel: 'cancel' }
});
}
The PHP bit just adds the html string in and is working fine, the problem still occours when using text (i.e. 'this is a prompt').
Whenever I call addfile() from JS it will run last. e.g. ...
function newfunction()
{
prompt("Before");
addfile();
prompt("after");
}
... will display do the following ...
Prompt - 'Before'
Prompt - 'After'
addfile();
No matter what I do the addfile() will always run last which confuses me. I'm pretty new to these things so If i'm doing anything really stupid please don't be afraid to point it out.Subnote: The function is sitting in the header of my php file so that the <?php echo $JSString; ?> works. I have removed the php and inserted the function into an external JS file but the same problem prevails so it is the $.prompt which seems to be causing the problem not the JS
Any ideas as to how to get this JS to behave greatly appreciated.Many thanks
your prompt function is asynchronous, that's why it accepts a callback function as parameter.
Try this:
prompt(
txt,
{callback: function() {
addfile();
prompt("after");
}}
);
Above approach is not working . Below is the code portion that. Alert is being displayed before blocking the page. I am using blockUI along with it.
function blockPage(){
$.blockUI({
message: "<img src='loading.gif'/>",
color: 'transparent',
backgroundcolor: '#777777',
top: $(window).height()/2
});
return true;
}
function dosomethingelse(){
var aa;
var bb;
alert("c");
}
function createOverlay(){
var overlaySubmit = function(e,v,m,f){
if(v === -1){
alert("Closing the prompt");
$.prompt.close();
return false;
} else if(v === 1){
dosomethingelse();
//blockPage();
return false;
}
};
var prompt = $.prompt(
"This is a test prompt",
{
opacity: 0.3,
buttons: {Add: 1, Cancel: -1},
position: {x: 300},
prefix: 'jqi',
submit: function(e,v,m,f){
blockPage();
try{
alert(g);
} catch (err){
alert("here");
}
overlaySubmit(e,v,m,f);
}
});
prompt.bind('promptsubmit',blockPage);
}
<!-- Ajax-->
$('#ajax').click(function(){
$.ajaxSetup({async:false});
$.ajax({
url: "test-server.txt",
success: function(response){
createOverlay();
return false;
},
error: function(){
return false;
}
});
});

Categories

Resources