Помогите пожалуста уменшить и оптимизировать мой код
Голову ломаю, и уже не знаю, как оптимизировать код, чтоб он не повторялся, пробовал через атрибуты, функцию неправильную сложил-удалил, помогите.
HTML:
<div class="form__group">
<div class="form__text">Year</div>
<div class="form__collapse">
<div class="form__collapse-from">
<input class="form__control" type="text" placeholder="from" id="YearFrom">
</div>
<div class="form__collapse-to">
<input class="form__control" type="text" placeholder="to" id="YearTo">
</div>
</div>
</div>
<div class="form__group">
<div class="form__text">Price</div>
<div class="form__collapse">
<div class="form__collapse-from">
<input class="form__control" type="text" placeholder="from" id="PriceFrom">
</div>
<div class="form__collapse-to">
<input class="form__control" type="text" placeholder="to" id="PriceTo">
</div>
</div>
</div>
JS
window.onresize = function () {
let currentWidth = document.documentElement.clientWidth
let YearFrom = document.getElementById("YearFrom")
let YearTo = document.getElementById("YearTo")
let PriceFrom = document.querySelector("#PriceFrom")
let PriceTo = document.querySelector("#PriceTo")
// Year:
//year from
if (currentWidth < 991) {
YearFrom = YearFrom.setAttribute("placeholder", "Year from")
}
else {
YearFrom = YearFrom.setAttribute("placeholder", "from")
}
//year to
if (currentWidth < 991) {
YearTo = YearTo.setAttribute("placeholder", "Year to")
}
else {
YearTo = YearTo.setAttribute("placeholder", "to")
}
// Price
//price from
if (currentWidth < 991) {
PriceFrom = PriceFrom.setAttribute("placeholder", "Price from")
}
else {
PriceFrom = PriceFrom.setAttribute("placeholder", "from")
}
//year to
if (currentWidth < 991) {
PriceTo = PriceTo.setAttribute("placeholder", "Price to")
}
else {
PriceTo = PriceTo.setAttribute("placeholder", "to")
}
}
Ответы (1 шт):
Автор решения: Pavel Grishaev
→ Ссылка
Например так:
window.addEventListener( 'resize', ()=>{
let isSmallScreen = document.documentElement.clientWidth < 991;
document.getElementById("YearFrom").placeholder = isSmallScreen ? "Year from" : "from";
document.getElementById("YearTo").placeholder = isSmallScreen ? "Year to" : "to";
document.getElementById("PriceFrom").placeholder = isSmallScreen ? "Price from" : "from";
document.getElementById("PriceTo").placeholder = isSmallScreen ? "Price to" : "to";
});