Last active
January 8, 2018 10:17
-
-
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
This file contains 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
$ = 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); | |
} | |
} |
This file contains 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
<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