Skip to content

Instantly share code, notes, and snippets.

@mafikes
Last active October 12, 2022 11:42
Show Gist options
  • Save mafikes/d453c2844112b6eceed086fcfd2cd9a0 to your computer and use it in GitHub Desktop.
Save mafikes/d453c2844112b6eceed086fcfd2cd9a0 to your computer and use it in GitHub Desktop.
Simple javascript scale content
"use strict";
class ScaleContent {
/**
* @param component => div
* @param resize => allow / disable resize scale listener
* @param width => original width
* @param height => original height
*/
constructor(component, resize = true, width = null, height = null) {
this.component = document.querySelector(component);
this.originalWidth = width ? width : 1920;
this.originalHeight = height ? height : 1080;
this.zoomScale = 1;
this.component.style.width = `${this.originalWidth}px`;
this.component.style.height = `${this.originalHeight}px`;
this.component.style.position = 'absolute';
this.component.style.overflow = 'hidden';
this.component.style.top = '50%';
this.component.style.left = '50%';
this.component.style.transform = 'translate(-50%, -50%)';
document.addEventListener('DOMContentLoaded', (event) => {
this.scale();
})
if (resize) this.resize();
}
scale() {
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
let cof = this.originalWidth / this.originalHeight;
let curCof = windowWidth / windowHeight;
if (curCof > cof) {
this.zoomScale = (windowHeight / this.originalHeight);
} else {
this.zoomScale = (windowWidth / this.originalWidth);
}
this.component.style.transform = "translate(-50%, -50%) scale(" + this.zoomScale + ")";
this.component.dataset.zoom = this.zoomScale;
}
resize() {
window.addEventListener('resize', (event) => {
this.scale();
});
}
}
// Usage
new ScaleContent('.my-crazy-div'); // default resize true, and original width and height fullHD
// More inputs
new ScaleContent('.div', false, 600, 900); // div, resize true/false, original design width, original design height
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment