Ajinkya
Ajinkya

Reputation: 22710

callback in jquery function

Can we callback jquery function with selector in another jquery function ?
Like I have two jquery functions

// Function 1: 
   $("#slideUp").click(function(){
      $("#testDiv").slideUp("slow",CALLBACK);
   });

// Function 2: 
   $("#slideDown").click(function(){
      // Do some stuff
   });  

How can I call Function 2 in Function 1's callback ?

*EDIT: Adding correct terminologies *

Can we callback one jquery listener with selector in another jquery listener ?
Like I have two jquery listener

// Listener 1: 
   $("#slideUp").click(function(){
      $("#testDiv").slideUp("slow",CALLBACK);
   });

// Listener 2: 
   $("#slideDown").click(function(){
      // Do some stuff
   });  

How can I call Listener 2 as Listener 1 callback ?

I want to execute click listener of slideDown once testDiv is silde up.
Thank you Spycho.

~Ajinkya.

Upvotes: 1

Views: 858

Answers (5)

Alnitak
Alnitak

Reputation: 339786

Function 2 isn't a callback, it's an invocation of jQuery that registers a callback. You need to create an accessible reference to f2's callback function.

Assuming that your intent is for f2 to be invoked after the slideUp animation has finished, try:

function f1() {
    $("#testDiv").slideUp("slow", f2);
}

function f2() {
    // do some stuff
}

$('#slideUp').click(f1);
$('#slideDown').click(f2);

EDIT this is technically cleaner than triggering a new event, since all it does is use .slideUp's built-in "completion callback" functionality passing a direct function reference, rather than futz around injecting stuff into the event queue.

Upvotes: 1

Spycho
Spycho

Reputation: 7788

Is this what you are after?

It defines a callback function which is called both when #slideDown is clicked and when #testDiv has finished sliding up.


Update

To call the handler without defining a function elsewhere, you could 'trigger' the event that the hanlder is listening for e.g. $("#slideDown").click();.

Upvotes: 1

australis
australis

Reputation: 481

Try .trigger() http://api.jquery.com/trigger/

In your case,

// Function 1:
$("#slideUp").click(function(){
  $("#testDiv").slideUp("slow", function() { $("#slideDown").trigger('click') } );
});

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816242

It is a bit unclear what you want, because "Function 2:" is not a function, it is a statement.

Either you want:

$("#testDiv").slideUp("slow",function() {
    $("#slideDown").click();
});

to trigger the click event.

Or

$("#testDiv").slideUp("slow",function() {
   $("#slideDown").click(function(){
      // Do some stuff
   });  
});

to assign a click handler.

Upvotes: 1

James Allardice
James Allardice

Reputation: 165941

If you mean you want to trigger a click on the element with ID slideDown then use $("#slideDown").click() in your callback function. That will trigger the event handler for that element.

Upvotes: 3

Related Questions