• documentation
  • examples
  • about
  • FAQ
  • journal
  • Gitlab

Push things

Work with pagedjs v. 0.4.0 and up

  1. csstree

CSS order is a great property, put Paged.js doesn’t really like Flex (for now!). This script allows to move elements around.

How to use it

Add the script to your head after pagedjs has been called

<script src="https://unpkg.com/css-tree@1.1.2/dist/csstree.min.js"></script>
<script src="https://pagedjs.org/plugins/pagedjs-pushthings.js"></script>

For example, consider this html

<p class="x">x</p>
<p class="y">y</p>
<p class="z">z</p>

In the CSS, you can move things using this custom property:

--experimental-push.

/*to move `.x` the element after `.z`*/
.x {--experimental-push: 2}


/*to move `.z` the element before `.x`*/
.z {--experimental-push: -2}

The code

class pushThings extends Paged.Handler {
constructor(chunker, polisher, caller) {
super(chunker, polisher, caller);
this.pushblock = [];
}
onDeclaration(declaration, dItem, dList, rule) {
// move the element to the next bit
if (declaration.property == "--push") {
console.log(declaration);
debugger
let sel = csstree.generate(rule.ruleNode.prelude);
sel = sel.replace('[data-id="', "#");
sel = sel.replace('"]', "");
let itemsList = sel.split(",");
console.log('itemlist', itemsList)
itemsList.forEach((elId) => {
this.pushblock.push([elId, declaration.value.value.trim()]);
});
}
}

beforeParsed(parsed) {
console.log(this.pushblock)
if (this.pushblock.length > 0) {
this.pushblock.forEach((elToPush) => {
const elem = parsed.querySelector(elToPush[0]);
if (!elem) {
console.log("no elem to push!");
return;
}
let move = Number(elToPush[1]);
elem.classList.add(`push-${move}`);
let order = "";
if (elToPush[1].trim() < 0) {
order = "back";
}
console.log(move)
if (order == "back") {
for (let index = 0; index < move; index++) {
if (elem.previousElementSibling) {
elem.previousElementSibling.insertAdjacentElement('beforebegin', elem);
}
}
} else {
for (let index = 0; index < move; move--) {
if (elem.nextElementSibling) {
elem.nextElementSibling.insertAdjacentElement("afterend", elem);
}
}
}
});
}
}
}

Paged.registerHandlers(pushThings);

Paged.js is maintained by the nice folks at Coko.