Skip to content

manageBehavior options

Mike Byrne edited this page Mar 8, 2023 · 2 revisions

With "critical behaviors"

import { manageBehaviors } from '@area17/a17-behaviors';
import * as Behaviors from './behaviors'; // Critical behaviors

window.A17 = window.A17 || {}; // currently namespaced name *is* important
window.A17.breakpoints = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl']; // tell this app what your breakpoint names are, in size order, manageBehaviors will read a CSS variable and compare for media scoped behaviors

document.addEventListener('DOMContentLoaded', () => {
    // expose manageBehaviors
    window.A17.behaviors = manageBehaviors;
    // init behaviors!
    window.A17.behaviors.init(Behaviors);
});

Without exposing a global behaviors object

import { manageBehaviors } from '@area17/a17-behaviors';
import * as Behaviors from './behaviors'; // Critical behaviors

window.A17 = window.A17 || {}; // currently namespaced name *is* important
window.A17.breakpoints = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl']; // currently, breakpoints need to be exposed globally for breakpoint checking to work

document.addEventListener('DOMContentLoaded', () => {
    // init behaviors!
    manageBehaviors.init(Behaviors);
});

No "critical behaviors"

Maybe you want to dynamically load all your behaviors for the smallest possible initial JavaScript load:

import { manageBehaviors } from '@area17/a17-behaviors';

window.A17 = window.A17 || {};

document.addEventListener('DOMContentLoaded', () => {
    window.A17.behaviors = manageBehaviors;
    window.A17.behaviors.init(null, {
        breakpoints: ['sm', 'md', 'lg', 'xl']
    });
});

Note: It is likely you're going to want to bundle and import at least some of your behaviors, for key items above the fold and mission critical items.

Data attribute options

If you don't want to use data-behavior as your binding attribute, you can alter this:

window.A17.behaviors = manageBehaviors;
window.A17.behaviors.init(Behaviors, {
  dataAttr: 'action',
  lazyAttr: 'action-lazy',
  breakpoints: ['sm', 'md', 'lg', 'xl']
});

Then you'd want to use data-action and data-action-lazy in your markup:

<button data-action="showAlert">Click me</button>

Intersection options

For lazy loaded behaviors, manageBehaviors uses an IntersectionObserver to watch for elements entering the viewport. The default rootMargin is set to 20% - that is, when the element comes within 20% of the viewport, the observer reports an intersection. You can change this threshold and the the other IntersectionObserver options by setting intersectionOptions:

  window.A17.behaviors.init(Behaviors, {
    intersectionOptions: {
      rootMargin: '50%',
    },
    breakpoints: ['sm', 'md', 'lg', 'xl']
  });