Search code examples
backbone.jsmarionette

Backbone Marionette - Add a visual effect when switching view


Is there a convenient way to add an effect when I leave a page (close a view/layout) and open a new one in the same region ? (something like a fade effect)


Solution

  • Marionette regions have a method called open that by default just replace the HTML of the old view with the new view. You can override this method to do any animation you like. From the region documentation:

    Set How View's el Is Attached

    If you need to change how the view is attached to the DOM when showing a view via a region, override the open method of the region. This method receives one parameter - the view to show.

    The default implementation of open is:

    Marionette.Region.prototype.open = function(view){
      this.$el.html(view.el);
    }
    

    This will replace the contents of the region with the view's el / content. You can change to this be anything you wish, though, facilitating transition effects and more.

    Marionette.Region.prototype.open = function(view){
      this.$el.hide();
      this.$el.html(view.el);
      this.$el.slideDown("fast");
    }
    

    This example will cause a view to slide down from the top of the region, instead of just appearing in place.