Skip to content

Instantly share code, notes, and snippets.

@JWardee JWardee/equate-height.js
Last active Jan 8, 2018

Embed
What would you like to do?
Vue directive that will equalise the height of elements on initial load, window resize and component update
$ = require('jquery');
_ = require('lodash');
Vue.directive('equate-height', {
inserted: function (el, binding) {
this.equateHeight = new EquateHeight(el, binding.value);
},
componentUpdated: function() {
this.equateHeight.setHeight();
},
unbind: function() {
this.equateHeight.unbind();
}
});
class EquateHeight
{
constructor(startPoint, cssSelectorToMatch)
{
this.startPoint = $(startPoint);
this.cssSelectorToMatch = cssSelectorToMatch;
$(window).bind('resize', () => _.debounce(this.setHeight, 150));
this.setHeight();
}
get tallestElement()
{
var elements = this.startPoint.find(this.cssSelectorToMatch).map(function () {
return $(this).outerHeight();
}).get();
return Math.max.apply(null, elements);
}
setHeight()
{
this.startPoint.find(this.cssSelectorToMatch).css('height', this.tallestElement + 'px');
}
unbind()
{
$(window).unbind('resize', () => this.setHeight);
}
}
<template>
<div class="row" v-equate-height="'.col-md-6'">
<div v-for="string in strings" class="col-md-6">
{{ string }}
</div>
</div>
</template>
<script>
export default {
name: 'example',
data: function() {
return {
strings: ['We', 'Will be all the same height, and will auto update on window resize and unbind whenever the component is no longer loaded by Vue. We use lodash to debounce the recalculation on window resize']
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.