Colorbox Was Smarter Than I Thought

I was doing some work on a custom CMS recently. It’s been utilizing the really nice jQuery ColorBox plugin, and I was using it to preview a page with the following code:

jQuery('#previewPage').click(function() {
   var data = jQuery('#editpage').serializeArray();
   jQuery.colorbox({href:"/pages/preview/", data: data, speed: 200, 
   opacity: 0.25, title: "", width: 1024, height: 550});
 })

It’s pretty straightforward, with #editpage being the form containing the new page’s contents. The problem was that the preview would work once, but any subsequent preview call would cause the following error:

TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'colorbox'

The issue was that I wasn’t using the ColorBox plugin properly. It was actually a little bit smarter than I thought. Here’s the proper way to do things:

    jQuery('#previewPage').colorbox({
        href:"/pages/preview/",
        data: function(){
                var data =  jQuery('#editpage').serializeArray();
                return data;
                },
        speed: 200,
        opacity: 0.25,
        title: "",
        width: 1200,
        height: 650
        });

It’s pretty close to the original code, except that instead of binding the click of #previewPage to call ColorBox, the plugin is smart enough to just bind directly to #previewPage.

The one thing that tripped me up slightly was the data option in the colorbox binding. When the colorbox is bound to #previewPage the data is pulled. If the data you pass in will change, you will want to pass in an anonymous function that will retrieve the updated data you want. For me, the data getting passed in was the contents of the #editpage form.

This entry was posted in jQuery / Javascript and tagged , , . Bookmark the permalink.

Leave a Reply

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