colorbox

Setting Colobox options from Anchor tag


I have an .Net 4, MVC 3 site that utilizes the jquery Colorbox plug in. Everything works as expected, however, I want to allow individual <a> tags to customize the options of the colorbox.

On the web page is an <a> tag:

    <a class="AddNewItem" 
       href="@Url.Action("Create", "Phone", new { masterSID = ViewData["MasterSID"] })"
       cboxOptions='transition: "fade", scrolling: false, overlayClose: false, height: "100%"'>
        Add Phone
    <a>

In a js file I have the following code:

$(document).ready(function () {

    $(".AddNewItem").colorbox($.extend({ title: "Add New Item" },
                                   SetCboxOptions($(this))
                             )
    );
});

function SetCboxOptions(obj) {
    var options = {};

    if ($(obj).attr("cboxOptions") != undefined) {
        var hash;
        var hashes = $(obj).attr("cboxOptions").replace(' ', '').split(',');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split(':');
            options[hash[0]] = hash[1];
        }
    }

    return options;
}

When i click the link, a pop-up windows appears with the correct form generated by calling /Phone/Create?masterSID=#. Validation works, and submitting works.

Here is the problem

None of the options set in the <a> tag's cboxOptions attribute take effect on the Colorbox. I am using code from the Colorbox website that states this should work. Can anyone point out why it isn't?


Solution

  • I suggest using the HTML5 data attribute to create an attribute to store your desired settings object in JSON format. Example:

    <a class="AddNewItem" href="@Url.Action("Create", "Phone", new { masterSID = ViewData["MasterSID"] })" data-cbox='{"transition":"fade", "height":"100%"}'>Add Phone<a>
    
    $(".AddNewItem").each(function(){
        var settings = $(this).attr('data-cbox');
    
        if (settings) {
            settings = $.parseJSON(settings);
        }
    
        $(this).colorbox(settings || {});
    });