Last active
May 13, 2019 12:33
-
-
Save Septdir/e7a765b33c9f953b49df997e9dc25458 to your computer and use it in GitHub Desktop.
JS - Ratio Height
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
} | |
} | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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