Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing callback functions

I'm using jQuery to write things like this:

    $('#current_image').fadeOut(function(){
        $('#current_image').attr('src',newImage).show();
    });

This is lovely, once the fadeOut has completed, the nested bit executes.

I'd like to make my own function here that would replace fadeOut. What would my function look like so that this code would work?

    $('#current_image').customFadeOut(function(){
        $('#current_image').attr('src',newImage).show();
    });
like image 693
Rich Bradshaw Avatar asked Sep 18 '10 16:09

Rich Bradshaw


People also ask

How do you write a callback function?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

How do you write a callback function in C?

We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function. In C we have to use the function pointer to call the callback function. The following code is showing how the callback function is doing its task.

What is callback function and how it works?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

What is the callback function in JavaScript?

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.


1 Answers

The key is just passing the function reference to the prototypal method you define, and binding that passed function to $.animate or whatever jquery animation function you use internally in that.

HTML:

<div id="blah" style="color:#fff; opacity:1; background:black; height:50px; position:relative; ">fsdljfdsjfds</div>
<a id="click" href="#">fjsd</a>

JS:

$.fn.customFadeOut = function (callback) {
    return $(this).animate({
        opacity: 0.25,
        fontSize: "3em",
        height: 'toggle'
    }, 5000, function () {
        callback.apply(this)
    });

}

$('#click').click(function () {
    $('#blah').customFadeOut(function () {
        alert('hi')

    })

})​

Live Demo

like image 78
meder omuraliev Avatar answered Oct 16 '22 04:10

meder omuraliev