Skip to content
This repository has been archived by the owner on Oct 20, 2023. It is now read-only.

theme-rte - Additional script for image wrappers with aspect-ratio #128

Open
ConduciveMammal opened this issue Sep 14, 2020 · 0 comments
Open

Comments

@ConduciveMammal
Copy link

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;
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant