Coding Tips: jQuery Callbacks
First a quick apology. I haven’t posted as much as I wanted to recently because of trying to get some improvements to a forum I maintain completed. They took longer than I had hoped.
Callbacks
One of the most useful parts of most jQuery methods are their callback feature. You can use it to execute any code you like after the method has completed it’s actions. This can be extremely useful, let’s say you have a button that deletes a row from the database via AJAX. Instead of just removing the row & it disappearing you can make it slide up, you could do something like this:
1 2 3 4 5 6 7 8 9 |
$('#delbutton').click(function() { $.post('file.php', { delete: '2' }, function(response) { $('.'+response).animate({ height: '0px' }, { duration: 600 }, function() { $(this).remove(); }); }); //return false //only needed if the button would normally go somewhere on click }); |
Here we attach an on click event to the delete button. We set off a AJAX post request to our php file, you would have to dynamically get the id in the delete parameter here I am just using 2 as an example. On getting a response from the server it uses that response to find the row to delete, animates it to 0 height (to make it slide closed) and then on completion of the animation it removes the row from the DOM. If your delete button is a hyperlink or a submit button you’ll need return false
to stop the normal action from completing.
this
‘this’ is a selector generally available inside callbacks. It normally refers to the element on which the callback is being used. So take the following example:
1 2 3 |
$('#submit').click(function() { $(this).fadeOut(500); }); |
Here ‘this’ refers to the element with the ID of ‘submit’ as that is the element that you are attaching the click event to. There is also another meaning for ‘this’, but unless you are developing jQuery functions it isn’t very useful. In general though ‘this’ can refer to a DOM element (as we have shown here) or a jQuery object.