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();
});
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With