Home >Web Front-end >CSS Tutorial >How Can I Make My Footer Responsive to Window Resize Using jQuery or JavaScript?

How Can I Make My Footer Responsive to Window Resize Using jQuery or JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 21:54:15384browse

How Can I Make My Footer Responsive to Window Resize Using jQuery or JavaScript?

jQuery for Window Resize

The provided jQuery code checks the height of the window only when the page loads. To rectify this, we need to check the window height on resize as well.

Using jQuery

A straightforward solution is to bind the resize event to the window object using jQuery's on() method:

$(window).on('resize', function() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    } else if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
});

Using JavaScript and CSS

Alternatively, you can combine JavaScript and CSS to handle resize events:

CSS:

.footer {
    position: static;
    bottom: auto;
    left: auto;
}

@media screen and (min-height: 820px) {
    .footer {
        position: absolute;
        bottom: 3px;
        left: 0px;
    }
}

JavaScript:

window.onresize = function() {
    if (window.innerHeight >= 820) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    } else if (window.innerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
}

Performance Optimization

By default, the resize event will be triggered frequently, which can impact performance. To mitigate this, you can use debounce or throttle functions to limit the frequency of the code execution.

The above is the detailed content of How Can I Make My Footer Responsive to Window Resize Using jQuery or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn