Web Development » Close a fancybox when submitting a form

Close a fancybox when submitting a form

Today I was presented with something rather strange. A client wanted a delayed lightbox presenting their user with an incentive to register on their site. The user would be given 3 available options; Never, Later, or Sign Up Now. The lightbox needed to contain a form and “Sign Up Now” would submit the data… but the other two would both close the lightbox, one setting a cookie for 90 days and the other setting a cookie for 1 day. La la la, set everything up like usual… but wait, how do I get these stinking buttons to close the form? (I’m using fancybox and jQuery by the way)

 

Here’s my solution:

function fancybox_close(){
    $('#fancy_outer').hide();
    $('#fancy_overlay').hide();
    $('#fancy_title').hide();
    $('#fancy_loading').hide();
    $('#fancy_ajax').remove();
}

If you’ll notice in the source of your page fancybox loads your desired content (if using the ajax method) into the div #fancy_ajax. To ensure the form is not just hidden, we call $(‘#fancy_ajax’).remove(); The others just hide the fancybox, which enables it to be reused for any other instances on your page. Then, simply call this function when your buttons are clicked, as so:

$('.close_popup_never').live('click',function(){
    fancybox_close();  //closes the fancybox
    return false;
}

That’s it! It took a little figuring out, but it seems to do the trick.

Note: I’ve revisited this and settled on a new approach that plays well with the newer versions of Fancybox. Check it out here: Close Fancybox when you submit a form (revisited)

Comments