create an ajax pop-up box using jquery colorbox

It is often useful to create a pop-up window to show contents retrieved via an ajax call. Then the user can do some kind of interaction on the popup window such as filling a form, and the result will be transferred back to the server via ajax call. We can implement this using jquery colorbox plugin as many wordpress themes and plugins have already done.

First we should create an element which is to be clicked to bring up the pop-up window:

click here to bring up a pop-up window

Note that href=”#” will scroll to the top of the current page, href=”#id” will scroll to the #id element, href=”#nonexistingid” does nothing.

We do not actually want to navigate to the location specified by the href attribute of the anchor, so we will take over the click event using jquery.

$(document).on('click','a#myid',function(){ ...  return false;});

The event handler returns false so the browser won’t go to the href.

In the click event handler, we can use jquery colorbox function to create the popup window.

jQuery.colorbox({
href: ajaxurl ,
transition:'fade',
maxWidth:'100%',
onLoad: function(){
},
onComplete: function() {
},
onCleanup: function() {
}
});

In the jQuery colorbox example above, the window created is displayed in a fading way. Before the content from the ajaxurl is fetched, the onLoad function is called. After the ajax call, the popup window will display the fetched content. Then the onComplete function is called. When the jQuery colorbox closes, the onCleanup funtion is called. You can echo a form in the ajax url, then transfer the form data back to the server in the onCleanup function via ajax. There are many other parameters for jQuery.colorbox that can be used to set, e.g., the colorbox width and height.

Next time, use jQuery colorbox with ajax to make your website more responsive.

Leave a Reply