import { debounce } from "throttle-debounce";

class FitText {
constructor(options) {
this.options = options;

this.containerEl = document.querySelector(options.containerSelector);

this.textRowEl = this.containerEl.querySelectorAll(
options.textRowSelector
);

this.updateFontSize();

const debouncedResize = debounce(
200,
this.handleWindowResize.bind(this)
);

window.addEventListener("resize", debouncedResize);

screen.orientation.addEventListener("change", debouncedResize);
}

handleWindowResize() {
this.updateFontSize();
}

updateFontSize() {
const currentFontSize = getComputedStyle(this.containerEl).fontSize;

const rowsWidths = [...this.textRowEl].map((row) => {
return row.offsetWidth;
});

const maxWidth = Math.max(...rowsWidths);

const containerWidth = this.containerEl.offsetWidth;

const multiplier = containerWidth / maxWidth;

const breakpoint = Math.max(
...Object.keys(this.options.responsive).filter(
(breakpoint) => window.innerWidth >= breakpoint
)
);

const maxFontSize =
breakpoint > 0
? this.options.responsive[breakpoint].maxFontSize
: this.options.maxFontSize;

const newFontSize = Math.min(
parseInt(currentFontSize) * multiplier,
maxFontSize || Infinity
);

this.containerEl.style.fontSize = newFontSize / 10 + "rem";
}
}

$(document).ready(function () {
new FitText({
containerSelector: ".section-intro__h1",
textRowSelector: ".animation-title > div",
maxFontSize: 30,
responsive: {
1000: {
maxFontSize: 80,
},
},
});
});

0 комментариев

Добавить комментарий

Avatar placeholder

Ваш адрес email не будет опубликован. Обязательные поля помечены *