### Install Priority Plus via NPM
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Use this command to install the library using npm.
```bash
npm install priority-plus
```
--------------------------------
### Configure Webpack Transpilation
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Example configuration for Webpack to ensure the library is included in the transpilation process for older browser support.
```javascript
exclude: /node_modules\/(?!priority-plus)/,
```
--------------------------------
### Define Mobile Breakpoint with CSS
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Use CSS media queries to define a 'mobile' breakpoint. This example targets the first navigation item to expand to 100% width at a maximum viewport width of 40em.
```css
@media (max-width: 40em) {
.p-plus__primary > li:first-child {
width: 100%;
}
}
```
--------------------------------
### Get Navigation Elements
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Retrieve an object containing references to the generated navigation elements.
```javascript
const inst = priorityPlus(document.querySelector('.js-p-target'));
console.log(inst.getNavElements());
```
--------------------------------
### Initialize Priority Plus
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Import the library and initialize it by passing the target element.
```javascript
import priorityPlus from 'priority-plus';
priorityPlus(document.querySelector('.js-p-target'));
```
--------------------------------
### Initialize Priority Plus with JavaScript
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Configure the library, handle navigation events, and implement custom interaction logic like closing the dropdown on outside clicks.
```javascript
import priorityPlus from 'priority-plus';
// Initialize with full configuration
function initNavigation() {
const navElement = document.querySelector('.js-site-nav');
if (!navElement) {
console.warn('Navigation element not found');
return null;
}
const instance = priorityPlus(navElement, {
collapseAtCount: 2,
innerToggleTemplate: ({ toggleCount, totalCount }) => {
if (toggleCount === 0) return 'Menu';
if (toggleCount === totalCount) return 'Menu';
return `Menu (+${toggleCount})`;
},
classNames: {
main: ['p-plus', 'site-nav-wrapper'],
},
});
// Track overflow state
instance.on('itemsChanged', ({ detail }) => {
const { overflowCount } = detail;
console.log(`Navigation updated: ${overflowCount} items in overflow`);
});
// Close dropdown when clicking outside
document.addEventListener('click', (event) => {
const container = document.querySelector('.p-plus-container');
if (container && !container.contains(event.target)) {
instance.setOverflowNavOpen(false);
}
});
// Close on Escape key
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
instance.setOverflowNavOpen(false);
}
});
return instance;
}
// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', initNavigation);
```
--------------------------------
### Set Up Event Listener
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Attach an event listener to the instance to react to events like 'itemsChanged'.
```javascript
inst.on('itemsChanged', () => console.log('Items changed'));
```
--------------------------------
### Instance Methods
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Methods available on the Priority Plus instance to control navigation behavior.
```APIDOC
## Instance Methods
### getNavElements()
Retrieves an object containing references to each element in the primary generated navigation.
### on(eventType: string, cb: Function)
Sets up an event listener on the instance.
### off(eventType: string, cb: Function)
Destroys an event listener.
### setOverflowNavOpen(open: boolean)
Opens or closes the overflow navigation programmatically.
### toggleOverflowNav()
Opens the overflow nav if closed, closes it if open.
```
--------------------------------
### Initialization
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Initializes the Priority Plus instance on a target navigation element.
```APIDOC
## Initialization
### Description
Creates a new instance of Priority Plus by passing an HTMLElement that acts as the direct parent of the navigation items.
### Request Example
```javascript
import priorityPlus from 'priority-plus';
const inst = priorityPlus(document.querySelector('.js-p-target'), {
openOnToggle: true,
collapseAtCount: 2
});
```
```
--------------------------------
### Define Navigation HTML Structure
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Set up the base HTML navigation list to be initialized by the library.
```html
```
--------------------------------
### Initialize Priority Plus with URL Parameters
Source: https://github.com/jayfreestone/priority-plus/blob/master/www/index.html
Initializes the Priority Plus component, reading configuration from URL query parameters like 'openOnToggle' and 'showOverflow'. It also sets up a callback to change the document title based on a 'titleCB' parameter.
```javascript
const queryParams = new URLSearchParams(window.location.search);
const inst = priorityPlus(document.querySelector('.js-p-target'), {
openOnToggle: queryParams.get('openOnToggle') !== "false",
defaultOverflowVisible: Boolean(queryParams.get('showOverflow')),
classNames: {
main: ['p-plus'],
},
});
/**
* Provides a way to trigger a document title change on an event, e.g:
* ?{title: "Items Changed", event: "itemsChanged"}
*/
const titleCB = queryParams.get('titleCB');
if (titleCB) {
const { title, event } = JSON.parse(titleCB);
inst.on(event, () => document.title = title, false);
}
window.$inst = inst;
```
--------------------------------
### Basic HTML Structure for Priority Plus
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
This is the required HTML structure. The library targets the direct parent of navigation items.
```html
```
--------------------------------
### priorityPlus(element, options)
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Initializes the Priority Plus navigation instance on a target HTMLElement.
```APIDOC
## priorityPlus(element, options)
### Description
Initializes the library on a navigation container. It clones and enhances the navigation structure to support automatic overflow management.
### Parameters
- **element** (HTMLElement) - Required - The direct parent element of the navigation items.
- **options** (Object) - Optional - Configuration object for customizing behavior and classes.
#### Options
- **openOnToggle** (boolean) - Optional - Disable automatic toggle on button click (default: true).
- **collapseAtCount** (number) - Optional - Collapse all items when primary nav has this many or fewer items (default: -1).
- **defaultOverflowVisible** (boolean) - Optional - Start with overflow nav visible (default: false).
- **innerToggleTemplate** (string|function) - Optional - Custom content for the toggle button.
- **classNames** (Object) - Optional - Override default CSS class names for internal elements.
```
--------------------------------
### Include Priority Plus via CDN
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Include the CSS and JavaScript files from a CDN for global availability.
```html
```
--------------------------------
### Style Priority Plus Navigation with CSS
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Apply base styles and customize the primary navigation, toggle button, and overflow dropdown using the library's provided classes.
```css
/* Import base styles */
@import "node_modules/priority-plus/dist/priority-plus";
/* Style the primary navigation */
.p-plus__primary {
display: flex;
background-color: #212529;
list-style: none;
margin: 0;
padding: 0;
}
.p-plus__primary > li a {
display: block;
padding: 1em 2em;
color: #fff;
text-decoration: none;
}
.p-plus__primary > li:hover {
background-color: #495057;
}
/* Style the toggle button */
.p-plus__toggle-btn {
padding: 1em;
min-width: 6rem;
background-color: #343a40;
color: #fff;
border: none;
cursor: pointer;
}
/* Style the overflow dropdown */
.p-plus__overflow {
background-color: #343a40;
padding: 1rem;
min-width: 12em;
list-style: none;
margin: 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.p-plus__overflow li a {
display: block;
padding: 0.75em 1em;
color: #fff;
}
/* Force mobile breakpoint - expand first item to trigger overflow */
@media (max-width: 40em) {
.p-plus__primary > li:first-child {
width: 100%;
}
}
/* Prevent flex collapse in flex parent layouts */
.site-header__nav {
flex-grow: 1;
}
```
--------------------------------
### Include Priority Plus via CDN
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Include the Priority Plus CSS and JavaScript files using a CDN for browser-based usage.
```html
```
--------------------------------
### Import Priority Plus CSS
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Ensure the library's CSS is included, typically via an import statement.
```css
@import "node_modules/priority-plus/dist/priority-plus";
```
--------------------------------
### Event Handling with on() and off()
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Subscribe to navigation events using the `on()` method and remove listeners with `off()`. Four events are available: `showOverflow`, `hideOverflow`, `itemsChanged`, and `toggleClicked`.
```APIDOC
## Event Handling with on() and off()
### Description
Subscribe to navigation events using the `on()` method. Four events are available: `showOverflow`, `hideOverflow`, `itemsChanged`, and `toggleClicked`. Remove listeners with `off()`.
### Methods
`on(eventName: string, handler: function)`
`off(eventName: string, handler: function)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Event Types
- **showOverflow**: Fired when the overflow menu becomes visible.
- **hideOverflow**: Fired when the overflow menu is hidden.
- **itemsChanged**: Fired when navigation items move between primary and overflow states. Provides `detail.overflowCount`.
- **toggleClicked**: Fired when the overflow navigation toggle button is clicked. Provides `detail.original` (the original click event).
### Request Example
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.site-nav'));
// Listen for overflow visibility changes
instance.on('showOverflow', () => {
console.log('Overflow menu is now visible');
document.body.classList.add('nav-dropdown-open');
});
instance.on('hideOverflow', () => {
console.log('Overflow menu is now hidden');
document.body.classList.remove('nav-dropdown-open');
});
// Listen for navigation item changes
instance.on('itemsChanged', ({ detail }) => {
console.log(`Items in overflow: ${detail.overflowCount}`);
if (detail.overflowCount > 0) {
analytics.track('nav_overflow_active', { count: detail.overflowCount });
}
});
// Listen for toggle button clicks
const toggleHandler = ({ detail }) => {
console.log('Toggle clicked', detail.original);
instance.toggleOverflowNav();
};
instance.on('toggleClicked', toggleHandler);
// Remove the listener later
instance.off('toggleClicked', toggleHandler);
```
### Response
#### Success Response (200)
Event handlers are executed when the corresponding event is triggered.
#### Response Example
None
```
--------------------------------
### Priority Plus Configuration Options
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Customize Priority Plus behavior using an options object, including toggle behavior, collapse thresholds, and custom class names. Dynamic templates for toggle buttons are supported.
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.js-nav'), {
// Disable automatic toggle on button click (default: true)
openOnToggle: false,
// Collapse all items when primary nav has 2 or fewer items (default: -1, disabled)
collapseAtCount: 2,
// Start with overflow nav visible (default: false)
defaultOverflowVisible: false,
// Custom toggle button content - static string
innerToggleTemplate: 'Menu',
// Or dynamic template function with item counts
innerToggleTemplate: ({ toggleCount, totalCount }) => {
if (toggleCount === totalCount) return 'Menu';
return `More (${toggleCount})`;
},
// Override default class names (each must be an array)
classNames: {
container: ['my-nav-container'],
main: ['my-nav'],
'primary-nav-wrapper': ['my-nav__wrapper'],
'primary-nav': ['my-nav__primary'],
'overflow-nav': ['my-nav__overflow'],
'toggle-btn': ['my-nav__toggle'],
'nav-item': ['my-nav__item'],
},
});
```
--------------------------------
### Re-run Libraries After Initialization
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Priority Plus clones the menu, so event listeners are not carried over. Re-run any libraries or JavaScript that operate on the menu and its children after Priority Plus initialization.
```javascript
priorityPlus(document.querySelector('.js-p-target'));
// .js-p-target is *not* the same element, but has been cloned and replaced
loadLibrary(document.querySelector('.js-p-target'));
```
--------------------------------
### Basic Initialization of Priority Plus
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Initialize Priority Plus by passing the HTMLElement that is the direct parent of navigation items. The library enhances the navigation, managing items between primary and overflow areas.
```javascript
import priorityPlus from 'priority-plus';
// Target element must be the immediate parent of nav items
const nav = document.querySelector('.site-nav');
const instance = priorityPlus(nav);
// The original element is replaced with enhanced navigation:
//
```
--------------------------------
### Defining a 'mobile' breakpoint with CSS
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
While Priority Plus is designed to be responsive without viewport-based breakpoints, you can define an early 'mobile' view using CSS by targeting the first navigation item.
```APIDOC
## Defining a 'mobile' breakpoint
You should never have to base the amount of visible navigation items visible on the viewport size.
However, if you would like to break (early) to the 'mobile' view at a pre-defined point, you can do so with just CSS.
Simply add a rule that causes the first item in the navigation to expand beyond the viewport, like so:
```css
@media (max-width: 40em) {
.p-plus__primary > li:first-child {
width: 100%;
}
}
```
```
--------------------------------
### innerToggleTemplate Configuration
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
This option allows you to customize the content of the 'view more' button. You can provide a string for static content or a function for dynamic content that updates based on navigation changes.
```APIDOC
## `innerToggleTemplate(String|Function)`
### Description
Overrides the inner contents of the 'view more' button. If you pass a string, then it will only render once, but if you pass it a function it will re-render every time the navigation is updated.
The function receives an object containing two parameters, `toggleCount` (the number of items in the overflow) and `totalCount` (which is the total number of navigation items).
### Request Example
```javascript
priorityPlus(document.querySelector('.js-p-target'), {
innerToggleTemplate: ({ toggleCount, totalCount }) => `
Menu${toggleCount && toggleCount !== totalCount ? ` (${toggleCount})` : ''}
`,
});
```
### Note
Be aware that if you alter the width of the element by changing its content, you could create a loop wherein the button updates, triggering a new intersection, which causes the button to update (and so on). Therefore it's probably a good idea to apply a width to the button so it remains consistent.
```
--------------------------------
### instance.getNavElements()
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Retrieves references to the generated DOM elements managed by the library.
```APIDOC
## instance.getNavElements()
### Description
Returns an object containing references to all generated navigation DOM elements for direct manipulation.
### Response
- **primary-nav** (HTMLElement) - The primary navigation list.
- **overflow-nav** (HTMLElement) - The overflow navigation list.
- **toggle-btn** (HTMLElement) - The toggle button element.
- **primary-nav-wrapper** (HTMLElement) - The wrapper for the primary navigation.
- **nav-item** (Array) - Array of navigation list items.
- **main** (HTMLElement) - The main container element.
```
--------------------------------
### Priority Plus Events
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Priority Plus emits several custom events that you can listen for to react to changes in the navigation's state. Arguments are provided via the `details` property of the event.
```APIDOC
## Events
Arguments are provided via the `details` property.
| Name | Arguments | Description |
|:----------------|:----------------------------------------------------------|:------------------------------------------------------------------------|
| `showOverflow` | None | Triggered when the overflow nav becomes visible. |
| `hideOverflow` | None | Triggered when the overflow nav becomes invisible. |
| `itemsChanged` | `overflowCount` (The number of items in the overflow nav) | Triggered when the navigation items are updated (either added/removed). |
| `toggleClicked` | `original` (The original click event) | Triggered when the overflow toggle button is clicked. |
```
--------------------------------
### Event Handling with on() and off()
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Subscribe to navigation events like `showOverflow`, `hideOverflow`, `itemsChanged`, and `toggleClicked` using `on()`. Remove listeners with `off()`. Useful for reacting to navigation state changes or implementing custom behaviors.
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.site-nav'));
// Listen for overflow visibility changes
instance.on('showOverflow', () => {
console.log('Overflow menu is now visible');
// Maybe add a backdrop overlay
document.body.classList.add('nav-dropdown-open');
});
instance.on('hideOverflow', () => {
console.log('Overflow menu is now hidden');
document.body.classList.remove('nav-dropdown-open');
});
// Listen for navigation item changes (items moving between primary/overflow)
instance.on('itemsChanged', ({ detail }) => {
console.log(`Items in overflow: ${detail.overflowCount}`);
// Example: Update analytics or tracking
if (detail.overflowCount > 0) {
analytics.track('nav_overflow_active', { count: detail.overflowCount });
}
});
// Listen for toggle button clicks (useful when openOnToggle is false)
const toggleHandler = ({ detail }) => {
console.log('Toggle clicked', detail.original); // Original click event
instance.toggleOverflowNav();
};
instance.on('toggleClicked', toggleHandler);
// Remove the listener later
instance.off('toggleClicked', toggleHandler);
```
--------------------------------
### Define Navigation Markup
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
The required HTML structure for the priority-plus navigation, including data attributes for the primary navigation, toggle button, and overflow menu.
```html
```
--------------------------------
### Programmatically Open/Close Overflow Nav
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Control the visibility of the overflow navigation menu using 'setOverflowNavOpen'.
```javascript
inst.setOverflowNavOpen(true);
```
--------------------------------
### Troubleshooting: Navigation event listeners
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Priority Plus clones the menu element, meaning event listeners are not carried over. This section explains how to re-apply event listeners after initialization if you are using additional libraries or custom JavaScript.
```APIDOC
### Navigation event listeners
priorityPlus makes a copy of your menu, rather than reusing the original. Classes and attributes are carried over, but not event listeners. This means that any additional libraries or JavaScript which operate on the menu and its children needs to be run (or re-run) after initialization:
```javascript
priorityPlus(document.querySelector('.js-p-target'));
// .js-p-target is *not* the same element, but has been cloned and replaced
loadLibrary(document.querySelector('.js-p-target'));
```
If your use-case is not covered by this, please raise an issue.
```
--------------------------------
### Set Collapse Count
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Configure the library to collapse navigation items into the overflow when fewer than a specified number can fit in the primary navigation.
```javascript
priorityPlus(document.querySelector('.js-p-target'), {
collapseAtCount: 2,
});
```
--------------------------------
### Programmatically Open/Close Overflow Nav
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Use `setOverflowNavOpen(true)` to open and `setOverflowNavOpen(false)` to close the overflow navigation. This method correctly updates ARIA attributes for accessibility.
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.site-nav'));
// Open the overflow navigation
instance.setOverflowNavOpen(true);
// Result: overflow-nav gets aria-hidden="false", toggle-btn gets aria-expanded="true"
// Close the overflow navigation
instance.setOverflowNavOpen(false);
// Result: overflow-nav gets aria-hidden="true", toggle-btn gets aria-expanded="false"
// Use case: Close dropdown when clicking outside
document.addEventListener('click', (event) => {
const navContainer = document.querySelector('.p-plus-container');
if (!navContainer.contains(event.target)) {
instance.setOverflowNavOpen(false);
}
});
```
--------------------------------
### Toggle Overflow Nav Visibility
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
Switch the state of the overflow navigation menu between open and closed.
```javascript
inst.toggleOverflowNav();
```
--------------------------------
### Prevent Nav Collapsing with Flex Grow
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
If the navigation menu is part of an auto-sized flex-child, apply a positive `flex-grow` value to the navigation element to prevent it from collapsing.
```css
.site-header__nav {
flex-grow: 1;
}
```
--------------------------------
### Troubleshooting: Flex nav collapsing
Source: https://github.com/jayfreestone/priority-plus/blob/master/README.md
If your navigation menu is part of an auto-sized flex-child element, it might collapse. This section provides a CSS solution using `flex-grow` to prevent this behavior.
```APIDOC
## Troubleshooting
### Flex nav collapsing
If your menu is part of an auto-sized flex-child, it will probably need a positive `flex-grow` value to prevent it reverting to its smallest form. For instance:
```html
My great site title
```
```css
.site-header {
display: flex;
align-items: center;
}
/**
* Prevents nav from collapsing.
*/
.site-header__nav {
flex-grow: 1;
}
```
```
--------------------------------
### toggleOverflowNav()
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Toggles the overflow navigation visibility - opens it if closed, closes it if open. This is the same behavior as clicking the toggle button when `openOnToggle` is enabled.
```APIDOC
## toggleOverflowNav()
### Description
Toggles the overflow navigation visibility - opens it if closed, closes it if open. This is the same behavior as clicking the toggle button when `openOnToggle` is enabled.
### Method
`toggleOverflowNav()`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.site-nav'), {
openOnToggle: false, // Disable default toggle behavior
});
// Implement custom toggle with keyboard support
instance.on('toggleClicked', ({ detail }) => {
detail.original.preventDefault();
instance.toggleOverflowNav();
});
// Add keyboard shortcut to toggle menu
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
instance.setOverflowNavOpen(false);
}
if (event.key === 'm' && event.altKey) {
instance.toggleOverflowNav();
}
});
```
### Response
#### Success Response (200)
This method does not return a value, but modifies the DOM and ARIA attributes.
#### Response Example
None
```
--------------------------------
### Toggle Overflow Navigation
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
The `toggleOverflowNav()` method toggles the visibility of the overflow navigation. This is useful for custom implementations, especially when `openOnToggle` is disabled or for keyboard shortcuts.
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.site-nav'), {
openOnToggle: false, // Disable default toggle behavior
});
// Implement custom toggle with keyboard support
instance.on('toggleClicked', ({ detail }) => {
detail.original.preventDefault();
instance.toggleOverflowNav();
});
// Add keyboard shortcut to toggle menu
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
instance.setOverflowNavOpen(false);
}
if (event.key === 'm' && event.altKey) {
instance.toggleOverflowNav();
}
});
```
--------------------------------
### Accessing Navigation Elements with getNavElements()
Source: https://context7.com/jayfreestone/priority-plus/llms.txt
Retrieve references to generated navigation DOM elements using `getNavElements()`. This allows direct manipulation of primary navigation, overflow navigation, toggle button, and other internal elements.
```javascript
import priorityPlus from 'priority-plus';
const instance = priorityPlus(document.querySelector('.site-nav'));
const elements = instance.getNavElements();
// Access individual elements
console.log(elements['primary-nav']); //