Created
September 29, 2021 20:48
-
-
Save ten1seven/2553ccd852d86aed292c602cf6fdfe15 to your computer and use it in GitHub Desktop.
Expand/collapse JavaScript from Urban Land Institute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import debounce from 'lodash.debounce' | |
export default class Expand { | |
constructor(el) { | |
this.variables(el) | |
this.setup() | |
this.events() | |
} | |
variables(el) { | |
this.el = el | |
this.maxHeight = this.el.dataset.expandHeight | |
const buttonText = this.el.dataset.expandButtonText | |
const buttonClasses = this.el.dataset.expandButtonClasses | |
this.button = this.createButton(buttonText, buttonClasses) | |
} | |
setup() { | |
if (this.el.offsetHeight > this.maxHeight) { | |
this.el.parentNode.insertBefore(this.button, this.el.nextSibling) | |
this.el.style.maxHeight = this.maxHeight + 'px' | |
} | |
} | |
events() { | |
this.button.addEventListener('click', this.onClick) | |
window.addEventListener('resize', debounce(this.resize, 200)) | |
} | |
createButton = (buttonText, buttonClasses) => { | |
const button = document.createElement('button') | |
button.innerHTML = buttonText | |
button.setAttribute('class', buttonClasses) | |
return button | |
} | |
reset = () => { | |
this.el.style.maxHeight = '' | |
this.button.remove() | |
} | |
resize = () => { | |
this.reset() | |
this.setup() | |
} | |
onClick = () => { | |
this.reset() | |
} | |
} | |
/* | |
Usage: | |
====== | |
<div | |
data-module="expand" | |
data-expand-height="190" | |
data-expand-button-text="Show More" | |
data-expand-button-classes="link mb-2" | |
> | |
Possibly long text here | |
</div> | |
options | |
-- | |
data-expand-height="190" - height at which to start showing the expand button | |
data-expand-button-text="Show More" - translated text for the button | |
data-expand-button-classes="link mb-2" - classes to put on the expander button | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment