In this super popular code snippet, I thought it would be useful to have chat GPT add some code comments to explain the magic of what's going on. This is a very useful snippet for folks embedding responsive documents within Wordpress where you want a fixed ratio based on the active responsive layout:
<script>
// Define the layoutRequest function
function layoutRequest(hypeDocument, element, event) {
// Get an array of all layouts for the current scene
var _layouts = hypeDocument.layoutsForSceneNamed(hypeDocument.currentSceneName());
// Get the name of the current layout
var layoutName = hypeDocument.currentLayoutName();
// Initialize a variable to store the data for the current layout
var res = null;
// Loop through the array of layouts
for (var i = 0; i < _layouts.length; i++) {
// Get the current layout object
var Obj = _layouts[i];
// Check if the current layout object matches the current layout name
if (Obj.name === layoutName) {
// If it does, store the layout data in the res variable
res = Obj;
// Stop the loop
break;
}
}
// If layout data was found, use it to resize the Hype document element
if (res) {
// Calculate the ratio of width to height for the current layout
var ratioScale = res['width'] / res['height'];
// Get the Hype document element
var hypeEl = document.getElementById(hypeDocument.documentId());
// Get the current width of the Hype document element
var currentWidth = hypeEl.offsetWidth;
// Calculate the new height of the Hype document element based on the layout ratio
var newHeight = currentWidth / ratioScale;
// Set the height of the Hype document element
hypeEl.style.height = newHeight + 'px';
// Tell the Hype document to relayout its elements and groups
hypeDocument.relayoutIfNecessary();
}
// Return false to indicate that the event should not be propagated further
return false;
}
// Check if the HYPE_eventListeners array exists in the global scope
if ("HYPE_eventListeners" in window === false) {
// If it doesn't, create it
window.HYPE_eventListeners = Array();
}
// Add an event listener for the HypeLayoutRequest event
window.HYPE_eventListeners.push({
"type": "HypeLayoutRequest",
"callback": layoutRequest
});
</script>