How to hide a div in Backbone when the user clicks outside div?

advertisements

I have a View in Backbone that contains an inner div. I want to hide the div when the user clicks outside of the div.

I'm not sure how to set up an Event inside of the View that says "click NOT #inner_div": "removeDiv".

Any suggestions on how to do this?


The usual approach is to attach a click handler directly to <body> and then have that close or hide your <div>. For example:

render: function() {
    $('body').on('click', this.remove);
    this.$el.html('<div id="d"></div>');
    return this;
},
remove: function() {
    $('body').off('click', this.remove);
    // This is what the default `remove` does.
    this.$el.remove();
    return this;
}

If you just want to hide the <div> rather than remove it, just bind clicks on <body> to a different method than remove; you'll still want to remove the click handler from <body> in your remove though. Also, you'll want to trap click events on your view's el to keep them from getting to <body>.

Demo: http://jsfiddle.net/ambiguous/R698h/

If you have other elements that care about click events then you could absolutely position a <div> to cover up the <body> and then bind your click handler to that. You could have a look at the jQuery BlockUI plugin to see how this is done.