Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

@ConduciveMammal ConduciveMammal commented Sep 14, 2020

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 join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.