Skip to content

Methods, Callbacks & Events

Vasileios Mitsaras edited this page May 2, 2019 · 2 revisions

The offcanvas API offers a couple of methods to control the offcanvas and are publicly available to all active instances.

var dataOffcanvas = $('#off-canvas').data('offcanvas-component');

Methods

open

dataOffcanvas.open();

close

dataOffcanvas.close();

toggle

dataOffcanvas.toggle();

Callbacks

onInit

Fires an event when offcanvas is initialized.

dataOffcanvas.onInit = function() {
    console.log(this);
};

onOpen

Fires an event when offcanvas is opened.

dataOffcanvas.onOpen = function() {
    console.log('Callback onOpen');
};

onClose

Fires an event when offcanvas is closed.

dataOffcanvas.onClose  = function() {
    console.log(this);
};

Events

jQuery.offcanvas fires several events. Simply listen for them with the jQuery.on function. All events are namespaced with offcanvas.

$('.js-offcanvas')
.on( "create.offcanvas", function( e ){ } )
.on( "open.offcanvas", function( e ){ } )
.on( "opening.offcanvas", function( e ){ } )
.on( "close.offcanvas", function( e ){ } )
.on( "closing.offcanvas", function( e ){ } )
.on( "resizing.offcanvas", function( e ){ } );

beforecreate

Fires an event before the offcanvas is initialized.

$( document ).on( "beforecreate.offcanvas", function( e ){
	var dataOffcanvas = $( e.target ).data('offcanvas-component');
	console.log(dataOffcanvas);
	dataOffcanvas.onInit =  function() {
		console.log(this);
	};
} );

create

Fired once the Plugin is initialized.

$( document ).on( "create.offcanvas", function( e ){ } );

open

Fired when the open method is called.

$( document ).on( "open.offcanvas", function( e ){ } );

close

Fired when the close method is called.

$( document ).on( "close.offcanvas", function( e ){ } );

resizing

Fired when the window is resized.

$( document ).on( "resizing.offcanvas", function( e ){ } );

clicked

Fired when the trigger-btn is clicked.

$( document ).on( "clicked.offcanvas-trigger", function( e ){
    var dataBtnText = $( e.target ).text();
    console.log(e.type + '.' + e.namespace + ': ' + dataBtnText);
} );

Examples

  $( document ).on( "beforecreate.offcanvas", function( e ){
    var $offcanvas = $( e.target ),
        dataOffcanvas= $offcanvas.data('offcanvas-component');

    function close() {
     dataOffcanvas.close();
    }

    $offcanvas.on('click', 'button.js-close', close);
}); 

// Open js-offcanvas on Pageload
 $( '.js-offcanvas' ).on( "create.offcanvas", function( e ){
    var dataOffcanvas = $(this).data('offcanvas-component');
    setTimeout(function(){
      dataOffcanvas.open();
    }, 400);
  });

// Send Event to Google Analytics
 $( document ).on( "open.offcanvas", function( e ){
    var dataOffcanvasID = $( e.target ).attr('id');
      if (typeof(ga) == 'function') {
        ga('send', 'event', 'Offcanvas opened', 'click', dataOffcanvasID);
      }
  });