FORSMILE
JA
JavaScript2020/07/24

[JavaScript] Detect Window Resize and Update Font Size

This is an implementation to detect window size changes and adjust the ratio of font sizes and image sizes.

Back to Blog

This is an implementation to detect window size changes and adjust the ratio of font sizes and image sizes.

I'm using jQuery to explain this, just because I felt like it. I believe this can be applied to other frameworks like Vue.js as well.

javascript
var w = window.innerWidth;

// window幅変更を検知する
jQuery(window).resize(function() {
    baseFontDeside();
});

// window幅からbaseFontSizeを決める
function baseFontDeside () {
    if (w >= 768) {
        var baseFontSize = w/73;
        jQuery('html').css('font-size',baseFontSize + 'px');
    } else if (w >= 576) {
        var baseFontSize = w/46;
        jQuery('html').css('font-size',baseFontSize + 'px');
    } else {
        jQuery('html').css('font-size','medium');
    }
}

Here's a reference article for how to get window width and detect changes in Vue.js.

In `baseFontDeside()`, the font size is set proportionally according to the screen width.

RECOMMENDED JAVASCRIPT BOOKS

There's a lot of online information for JavaScript, and Google search is very convenient, so you might not need to read books.

However, if you're just starting out, reading one simple book might deepen your understanding. While there are good reference books, I think Google search is more convenient for copy-pasting, so they might not be necessary.

Enlightenment! JavaScript – The Essence of JavaScript Learned from Language Specifications

Highly recommended! You can learn JavaScript that doesn't typically appear in Google searches. After finishing this book, I felt my coding skills had improved significantly.

📦
Amazon で関連書籍・ツールを検索
JavaScript programming book
Amazonで探す →(アソシエイトリンク)