Skip to content

Instantly share code, notes, and snippets.

@JWardee
Last active January 8, 2018 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JWardee/5ebebf5ae8953a4be84a337cf5408e0c to your computer and use it in GitHub Desktop.
Save JWardee/5ebebf5ae8953a4be84a337cf5408e0c to your computer and use it in GitHub Desktop.
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