Jquery run onClick function as separate function - javascript

I have a jquery onClick function:
$('body').on('click', '#id_name', function() {
...
and i would like to execute this function as another function on ajax call (currently this is only onclick).
if my ajax call is success then:
success: function() {
// then execute top function
}
is it possible to do that?

Then you can use $('#id_name').trigger('click') in the ajax success callback.

Make the function a named (non-anonymous) function:
var someFunction = function () {
//...
};
Then you can use it for your click event:
$('body').on('click', '#id_name', someFunction);
Or your callback:
success: someFunction
Or invoke it from therein:
success: function () {
someFunction();
}
etc. Basically once you give the function a name and it's no longer anonymous you can refer to it anywhere that it's in scope.

Create a delegate function and call it separately
for example
function mainFunction(){
// Rest of code
}
on click call this
$('body').on('click', '#id_name', mainFunction)
Inside ajax success call like this
success: function() {
mainFunction()
}

Well, you could explicitly trigger the click event. Or even better, outsource your click code in an own function and then you can call it inside your success function. So, instead of
success: function() {
$('#id_name').trigger('click')
}
Do better this:
function clickEvent() {
// do something in here...
}
$('body').on(
'click',
'#id_name',
function (eventArgs) {
eventArgs.preventDefault();
clickEvent();
}
);
And then you can simply call it into your success callback with:
success: function() {
clickEvent();
}

Related

Attach a callback on click of a button which does an ajax operation

I'm aware that this can be achieved via a Promise but I am struggling to figure out how.
jQuery('.parentDiv').on('click', '.link', function(e) {
jQuery.when(jQuery('.saveBtn').trigger('click', { 'evtData': 'link' })).then(function {
// rest of the logic that should be performed on click of .link
});
});
The click of .saveBtn calls a function named doAjax:
jQuery('.saveBtn').on('click', function() {
doAjax()
});
function doAjax() {
var ajaxCall = jQuery.ajax(ajaxObject);
ajaxCall.done(function(data, status, xhr) {
//some logic go here
});
return ajaxCall;
}
Despite this the logic inside the .then handler is getting executed first i.e before doAjax completes.
I believe I need to change the jQuery.when(jQuery('.saveBtn').trigger('click',{'evtData':'link'})) as it may not be getting the Promise state which it should and immediately getting marked as Resolved thereby executing the callback without waiting?.
I tried return doAjax in .saveBtn but that also did not make a difference.
Ideas please.
The issue is because trigger() is not an async function, so then is called immediately. It would make far more sense to just call doAjax() directly from the click of .link instead of faking DOM events. Try this:
jQuery(function($) {
$('.parentDiv').on('click', '.link', function(e) {
doAjax().then(function {
// rest of the logic that should be performed on click of .link
});
});
$('.saveBtn').on('click', function() {
doAjax()
});
function doAjax() {
var ajaxCall = $.ajax(ajaxObject);
ajaxCall.done(function(data, status, xhr) {
// some logic go here
});
return ajaxCall;
}
});

(document).ready is a global scope?

Guys i have this function inside my script.js:
$(document).ready(function() {
function alert() {
alert('AAAAAAAA');
}
});
And i am trying to call here in my index.html:
$('.something').on('click', function() {
e.preventDefault();
alert();
});
But is showing my this error - alert is not defined.
But when i take off the document ready in the external script, the click handler will work. Why is that?
The document ready is creating a separate scope?
Using $(document).ready() creates a new function scope (note the function() after the .ready), so when you call
$(document).ready(function() {
function alert() {
alert('AAAAAAAA');
}
});
alert is only defined within the document.ready block. There are two ways to solve this issue:
Define the function outside of the document.ready block:
function customAlert() {
alert('AAAAAAAA');
}
Attach the function to the window object:
$(document).ready(function() {
window.customAlert = function() {
alert('AAAAAAAA');
};
});
Include the click event into the document.ready
Check it here http://jsfiddle.net/fbrcm45q/1/
$(document).ready(function() {
function showAlert() {
alert('AAAAAAAA');
}
$('.something').on('click', function(e) {
e.preventDefault();
showAlert();
});
});
First of all e.preventDefault is a function so you have to add braces at the end:
e.preventDefault()
Second alert is a function in javascrpt, so you need to rename your function to something else, for example:
$(document).ready(function() {
function special_alert() {
alert('AAAAAAAA');
}
});
and:
$('.something').on('click', function() {
e.preventDefault();
special_alert();
});

call function when click button

i have simply js file but i can't call function with parameter
the code
function removetr(str){
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr(1) );
});
the class of inputs that i want to remove it's values are g1,ga1 and gb1
i want to note that if i change the code to
function removetr(){
str=1;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr );
});
it's work
You need to pass a function reference to an event handler, your current code is calling the function directly. Either build your function as an event handler, or pass an anonymous function reference to the click handler.
as event handler:
function removetr(e) {
var str;
str = e.data.str;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(function () {
$("input.buttonno1").click({str: '1'}, removetr);
});
as anonymous function reference:
function removetr(str) {
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(function () {
$("input.buttonno1").click(function () {
removetr(1)
});
});

JQuery: how to name click functions?

I have a script and I need to be able to name some of my anonymous click functions. For instance, here is some code:
Document ready:
$(function(){
$('#map').imagemap([
{top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: #id1 anonymous function},
{top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: #id2 anonymous function},
{top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: #id3 anonymous function}
]);
$('#id1').click(function() {
....
});
$('#id2').click(function() {
....
});
$('#id3').click(function() {
....
});
...
});
How do I write my callbacks so that I don't have to duplicate the code outside the document.ready? I tried putting it all inline, following the callback:, but it didn't work. So what do I put in place of my anonymous function callback calls?
It sounds like you want to have the click functions use a named function which is callable from elsewhere in the code. If so just define the functions outside the jQuery ready function and use them by name in the click method.
function id1Click() {
...
}
...
$(function() {
$('#id1').click(id1Click);
});
Instead of using an anonymous function like in your example
$('#id3').click(function() {
....
});
you can define your function elsewhere and use that function
$('#id3').click(myClickCallback);
function myClickCallback{
...
}
function id1_click() { ... }
function id2_click() { ... }
function id3_click() { ... }
$(function(){
$('#map').imagemap([
{top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: id1_click },
{top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: id2_click },
{top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: id3_click }
]);
$('#id1').click(id1_click);
$('#id2').click(id2_click);
$('#id3').click(id3_click);
...
});

calling Jquery function from javascript

How can i call a jQuery function from javascript?
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
});
//just js
function js_fun () {
my_fun(); //== call jquery function
}
Yes you can (this is how I understand the original question).
Here is how I did it. Just tie it into outside context.
For example:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
I encountered this same problem when trying to access methods of the object, that was instantiated
on DOM object ready only. Works. My example:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
now you can use something simple like:
function() = {
MyCtrl.update(); // yes!
}
You can't.
function(){
function my_fun(){
/.. some operations ../
}
}
That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.
$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.
Of course, if you want to run this function when the DOM has fully loaded, you should do the following:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
jQuery functions are called just like JavaScript functions.
For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:
$("#orderedlist").addClass("red");
As opposed to a regular line of JavaScript calling a regular function:
var x = document.getElementById("orderedlist");
addClass() is a jQuery function, getElementById() is a JavaScript function.
The dollar sign function makes the jQuery addClass function available.
The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.
In your code
$(function() {
// code to execute when the DOM is ready
});
Is used to specify code to run when the DOM is ready.
It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.
So, to answer your question, just call functions you defined as you normally would.
//create a function
function my_fun(){
// call a jQuery function:
$("#orderedlist").addClass("red");
}
//call the function you defined:
myfun();
I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
My problem was that I was looking at it from the long angle:
function new_line() {
var html= '<div><br><input type="text" value="" id="dateP_'+ i +'"></div>';
document.getElementById("container").innerHTML += html;
$('#dateP_'+i).datepicker({
showOn: 'button',
buttonImage: 'calendar.gif',
buttonImageOnly: true
});
i++;
}
<script>
$.myjQuery = function() {
alert("jQuery");
};
$(document).ready(function() {
alert("Welcome!");
});
function display() {
$.myjQuery();
};
</script>
<input type="button" value="submit" onclick=" display();">
Hope this will work for you!

Categories