DEV Community

François-Emmanuel CORTES
François-Emmanuel CORTES

Posted on

2

SvelteKit responsive helper

Tired of writing complicated media queries ? SvelteKit windiow directives can help you simplifying them programtically. With the help of this layout component ViewoirtSettingsCatcher component and its associated store ViewportSettingsStore, they are presented in this topic.

Grabbing viewport dimensions

Very simple use of svlete:window directive's bindings:

<!-- ViewportSettingsCatchr.svelte -->
<script lang="ts">
    let innerWidth: number = 1600
    let innerHeight: number = 1200
</script>

<svelte:window bind:innerWidth vind:nnerHeight />
Enter fullscreen mode Exit fullscreen mode

Registering inside store

$: ViewportSettingsStore.register ({ innerWidth, innerHeight })
Enter fullscreen mode Exit fullscreen mode

the associated computation store

import { writable} from 'svelte/store'
const { subscribe, update  } = writable ({
    innerWidth: 1600, 
    innerHeight: 1200,
    ratio: 16/12, 
    orientation: 'landscape',   
    wide: false
})

function register ({ innerWidth, innerHeight }) {
    const ratio = innerWidth / innerHeight
    const orientation = ratio >= 1 ? 'landscape' : 'portrait'
    const wide = (ratio > 2) || (ratio < 0.5)

    update ((state) => {
        return {
            innerWidth, 
            innerHeight,
            orientation,
            ratio,
            wide
        }
    })
}

export const ViewportSettingsStore = {
    subscribe, register 
}
Enter fullscreen mode Exit fullscreen mode

simple usage

Just import ViewportSettingsStore in your componentr

<div class:wide={ $ViewportSettingsStore.orientation = === 'landscape' } />
Enter fullscreen mode Exit fullscreen mode

Et voilà... That's done.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay