Close jQuery ColorBox on an Action

jQuery is awesome. If you use Javascript on your website, you should use jQuery. If you don’t, you don’t know what you’re missing.

Recently, on a new site I’m about to launch, I was looking for some better ways to use jQuery and ColorBox when estimating shipping charges for customers. Previously, I called out to an internal web service to do some calculations and then do a redirect with the values to display to the user. I was thinking, meh, a redirect? You really need to do that?

So I ripped it all out and started over. I basically decided I could use jQuery and element IDs to do the same thing. Hide some controls, set the html or text values of others where I wanted calculated values to show up. But the kicker was, I could easily do that from my ColorBox modal window, but I wanted it to close after hitting the submit button. Turns out this is stupid simple. From the ColorBox documentation, you can manually close the ColorBox window:


$.colorbox.close();

The key to making it work is to find the element that actually opened the ColorBox window. I managed to only get this to work by finding the form that owned the element that opened the window first, then get the element in question, i.e.

var myForm = $("#myForm ");
var myElement= shoppingCartForm.find('#myElement');
if (myElement!= null) {
    myElement.colorbox.close();
}

For some reason, just doing this didn’t work:

$('#myElement').colorbox.close();

That would have been simpler, but I got it to work and that’s all that I really cared about. Anyway, hopefully this will be useful to someone else!

Update: So it turns out, that I could simply do this too on a button:

$('#lnkButton').click(function () {
    $(this).colorbox.close();
});

Simple and clean! Love it!

Leave a Reply

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