Body class
Copy the class of the body from the new page, so page-specific styling keeps working.
Import it from pagefold/body-class (about 0.8 KB minified and compressed, shared code included).
import PagefoldBodyClass from 'pagefold/body-class'
new Pagefold({ plugins: [new PagefoldBodyClass({ prefix: 'page-' })] })
Only the containers are replaced, so without this plugin the body would keep the class of the first page.
Without a prefix, the whole class attribute is replaced with the new page’s. Use a prefix when JavaScript adds classes to the body (js-ready, menu-open) that must survive a visit.
A before and after
Two pages with different body classes:
<!-- /index -->
<body class="page-home theme-light">
<!-- /blog -->
<body class="page-blog theme-light">
The visitor is on /index, your script opens the menu (menu-open) and then clicks to /blog:
| Body classes after the visit | |
|---|---|
| Without the plugin | page-home theme-light menu-open (the old page’s classes stay) |
With the plugin, no prefix | page-blog theme-light (menu-open is lost) |
With the plugin, prefix: 'page-' | theme-light menu-open page-blog |
With a prefix, only the classes that start with it are swapped. Everything else on the body stays, including theme-light here, even if the new page has a different value. A class that must change with the page needs a name that starts with the prefix.
Common problems
- Styles of the new page do not apply. The class you rely on is set by JavaScript after load rather than in the HTML. Pagefold copies what the server sent, so set it on the server.
- The menu closes on every visit. Without a
prefixthe whole attribute is replaced. Add one, and give state classes names that do not start with it. - Only the body is wrong. This plugin does not touch
html. Itslanganddirattributes are handled by Head, which can sync more with itsattributesoption.
Other attributes
By default only the classes change. If your pages also differ in other attributes of the body, such as lang, dir or data-* values, list them:
new PagefoldBodyClass({ attributes: ['lang', 'dir', /^data-/] })
An attribute that matches a name or a pattern is copied from the new page, and removed if the new page does not have it. Attributes that match nothing in the list are left alone.
Options
| Option | Type | Default | What it does |
|---|---|---|---|
prefix | string | '' | Only manage classes that start with this. Classes added by your scripts to the body are left alone. Default: all classes. |
attributes | (string | RegExp)[] | [] | More attributes of the body to copy from the new page, such as lang, dir or /^data-/. |