Last active
October 12, 2022 11:42
-
-
Save mafikes/d453c2844112b6eceed086fcfd2cd9a0 to your computer and use it in GitHub Desktop.
Simple javascript scale content
This file contains 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
"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(); | |
}); | |
} | |
} |
This file contains 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
// 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