theme-scripts
theme-scripts copied to clipboard
theme-rte - Additional script for image wrappers with aspect-ratio
There's probably a nicer way to achieve this but I cooked up a new script to add support for image wrappers with an additional class for aspect ratio-support.
It'd be great to see this added in for future use.
// Example Usage
const imageSelectors = '.rte img'
wrapImage({
$images: $(imageSelectors),
imageWrapperClass: 'rte__image-wrapper'
});
// Returns
<div class="rte__image-wrapper rte__image-wrapper--(portrait|landscape|square)">
<img src="..." alt="">
</div>
/**
* Wrap images in a container div with an additional class for its aspect ratio
*
* @param {object} options - Options to be used
* @param {jquery} options.$images - jquery object(s) of the table(s) to wrap
* @param {string} options.imageWrapperClass - image wrapper class name
*/
function wrapImage(options) {
const imageWrapperClass =
typeof options.imageWrapperClass === 'undefined' ?
'' :
options.imageWrapperClass;
options.$images.each(function () {
const height = $(this)[0].clientHeight
const width = $(this)[0].clientWidth
const imageAspectRatio = aspectRatio(height, width)
$(this).wrap(`<div class="${imageWrapperClass} ${imageWrapperClass}--${imageAspectRatio}"></div>`);
})
}
function aspectRatio(height, width) {
let aspectRatioValue = (height > width) ? 'portrait' :
(height === width) ? 'square' :
(height < width) ? 'landscape' : null;
return aspectRatioValue;
}