In JavaScript è semplice avere il footer sempre in fondo alla pagina.
Impostiamo il posizionamento CSS relativo sul footer:
#footer {
position: relative;
}
Quindi creiamo la seguente funzione:
'use strict';
const setFooter = () => {
const footer = document.querySelector('#footer');
const boundingBox = footer.getBoundingClientRect();
const footerHeight = boundingBox.height;
const windowHeight = window.innerHeight;
const footerTop = parseFloat(window.getComputedStyle(footer).getPropertyValue('top'));
const aboveFooterHeight = boundingBox.top - footerTop;
if (aboveFooterHeight + footerHeight <= windowHeight) {
const newFooterTop = windowHeight - (aboveFooterHeight + footerHeight);
footer.style.top = newFooterTop + 'px';
} else if (aboveFooterHeight + footerHeight > windowHeight) {
footer.style.top = '0px';
}
};
Usiamo la funzione in questo modo:
setFooter();
window.addEventListener('resize', setFooter);