开发者

How can I activate Colorbox following successful ajax injection?

I see that Colorbox can load external HTML but that only loads the entire page referenced. I'd like to inject only the part of the page needed for some login and register forms and then fire up Colorbox only if the process is successful.

I've sketched out the following...

$('.gateway').click(function(e) {
  var _link = $(this);
  var $error = $('<div id="error" />');
  var $modal = $('<div id="modal" />');

  var $url = _link.attr('href') + ' #gateway'; 
    // I only want to load #gateway from the target page

  $modal.load($url, function (response, status, xhr) {
    if (status == 'success') {
      $('body').append($modal);
      $modal.hide().colorbox({
        width:'60%', 
        inline:true, 
        href:'#gateway',
        onLoad:function(){ $modal.show(); },
        onCleanup:function(){ 
          $modal.remove(); 
          $error.remove(); 
        }
      });
    }
    if (status == 'error') {
      var $msg = 'Sorry, something went wrong: ';
      $error.html($msg + xhr.status + ' ' + xhr开发者_如何学Python.statusText);
      // Do something with this message!
    }
  });

  e.preventDefault();
});

$modal is injecting fine with the right #gateway contents but Colorbox does nothing. I sense I've mangled my events and methods here. I'm guessing the Colorbox method (is that the right terminology?) only responds to the click event and not to the subsequent successful load event.

I'd be grateful if someone can help me have Colorbox respond to the load event or show me a more elegant way to achieve what I'm after!


ColorBox uses jQuery's load method for it's ajax functionality, so you can use it to just pull an snippet from your HTML document. Instead of everything you posted, try this:

$('.gateway').colorbox({
    width:'60%', 
    href: function(){ return $(this).attr('href') + ' #gateway';}
});

If the ajax request is unsuccessful, colorbox will give a messaging saying so. If you decide you need custom error handling, you can make your ajax/load request for your HTML snippet and pass it directly to colorbox's 'html' property instead of adding it to your DOM and trying to use the inline property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜