/** * Fits an element inside its parent by setting its width and height *style attributes*. * Respects the aspect ratio defined by the width and height *attributes* of the element. * It is often the case that width and height *attributes* are defined on the iframe video embeds. * Note the distinction between an *attribute* and a *style attribute*. * @param element */ export function fit (element: Element): void { if (element instanceof HTMLElement) { const widthAttribute = element.getAttribute('width') const heightAttribute = element.getAttribute('height') if (widthAttribute === null) return if (heightAttribute === null) return const width = parseInt(widthAttribute) const height = parseInt(heightAttribute) const ratio = height / width const parentWidth = element.parentElement?.clientWidth const parentHeight = element.parentElement?.clientHeight if (parentWidth === undefined) return if (parentHeight === undefined) return let w = parentWidth let h = w * ratio if (h > parentHeight) { h = parentHeight w = h / ratio } element.style.width = `${w.toString()}px` element.style.height = `${h.toString()}px` } } /** * Resets 'src' attribute of an element. * @param element */ export function resetSrc (element: Element): void { const src = element.getAttribute('src') if (src === null) throw new Error('This element does not have the \'src\' attribute defined.') element.setAttribute('src', src) }