Skip to content

Instantly share code, notes, and snippets.

@Septdir
Last active May 13, 2019 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Septdir/e7a765b33c9f953b49df997e9dc25458 to your computer and use it in GitHub Desktop.
Save Septdir/e7a765b33c9f953b49df997e9dc25458 to your computer and use it in GitHub Desktop.
JS - Ratio Height
document.addEventListener("DOMContentLoaded", function () {
setRatioHeight();
setMinRatioHeight();
});
window.addEventListener('resize', function () {
setRatioHeight();
setMinRatioHeight();
});
function setRatioHeight() {
document.querySelectorAll('[ratio-height]').forEach(function (element) {
let data = element.getAttribute('ratio-height').match(/(\d+):(\d+)/);
if (data) {
let width = data[1],
height = data[2];
if (width && height) {
element.style.height = Math.round((element.offsetWidth / width) * height) + 'px';
}
}
});
}
function setMinRatioHeight() {
document.querySelectorAll('[min-ratio-height]').forEach(function (element) {
let data = element.getAttribute('min-ratio-height').match(/(\d+):(\d+)/);
if (data) {
let width = data[1],
height = data[2];
if (width && height) {
element.style.minHeight = Math.round((element.offsetWidth / width) * height) + 'px';
}
}
});
}
(function ($) {
function setRatioHeight() {
$($('[data-ratio-height]')).each(function () {
// data-ratio-height="4:3"
var data = $(this).data('ratio-height').match(/(\d+):(\d+)/);
if (data != null) {
var width = data[1];
var height = data[2];
if (width && height) {
$(this).height(Math.round(($(this).width() / width) * height));
}
}
else {
console.error('data-ratio-height syntaxis eror');
}
});
}
$(document).ready(function () {
setRatioHeight();
});
$(window).resize(function () {
setRatioHeight();
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment