Coding Tips: jQuery Callbacks

/ jQuery / by Paul Robinson / 0 comments
This post was published back on March 4, 2010 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more