Skip to content

Instantly share code, notes, and snippets.

@timrross
Last active April 24, 2019 08:26
Show Gist options
  • Save timrross/ec845296d51cd629e7b0396854ef097e to your computer and use it in GitHub Desktop.
Save timrross/ec845296d51cd629e7b0396854ef097e to your computer and use it in GitHub Desktop.
A simple vanilla javascript class to implement a two column, left-to-right layout.
.article {
width: 50%;
float: left;
clear: left;
.article.right {
float: right;
clear: right;
}
/**
* A simple vanilla javascript class to implement a two column, left-to-right layout
*
* @author Tim Ross <timrross@gmail.com>
*/
/**
* A class that implements the two column layout.
* Called like this:
* <code>
* let layout = new TwoColumnLayout('.article)
* </code>
*/
class TwoColumnLayout {
constructor(selector, rightClassName = 'right') {
this.selector = selector
this.rightClassName = rightClassName
this.debounceLayout = debounce(() => {
this.layout()
}, 100)
this.layout()
this.addEventListeners()
}
/**
* Add the class 'right'
*/
layout() {
let leftColumnHeight = 0, rightColumnHeight = 0
let articles = document.querySelectorAll(this.selector)
articles.forEach((el, index) => {
el.classList.remove(this.rightClassName)
let outerHeight = this.calculateOuterHeight(el);
if (leftColumnHeight > rightColumnHeight) {
el.classList.add(this.rightClassName)
rightColumnHeight += outerHeight
} else {
leftColumnHeight += outerHeight
}
})
}
addEventListeners() {
window.addEventListener(
"resize",
() => {
this.debounceLayout();
},
false
);
}
/**
* Include margins in the outerheight calculation
* @param {Element} el
*/
calculateOuterHeight(el) {
var height = el.offsetHeight;
var style = getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
}
}
function debounce(func, wait, immediate) {
var timeout
return function () {
var context = this,
args = arguments
var later = function () {
timeout = null
if (!immediate) func.apply(context, args)
};
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
export default TwoColumnLayout
import TwoColumnLayout from './two-column-layout.js'
let layout = new TwoColumnLayout('.article');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment