Code
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
Parameters
| Parameter | Description |
|---|---|
value | Value you want to clamp. |
min | Lower bound allowed. |
max | Upper bound allowed. |
Nuxt Example
<script setup lang="ts">
const clamp = (value: number, min: number, max: number) =>
Math.max(min, Math.min(max, value))
const maxScroll = 400
const progress = ref(0)
const updateProgress = () => {
const ratio = window.scrollY / maxScroll
progress.value = clamp(ratio, 0, 1)
}
onMounted(() => {
updateProgress()
window.addEventListener('scroll', updateProgress)
})
onUnmounted(() => {
window.removeEventListener('scroll', updateProgress)
})
</script>
<template>
<div class="progress">
<div class="progress__fill" :style="{ width: (progress * 100) + '%' }" />
</div>
<p>Clamped progress: {{ (progress * 100).toFixed(0) }}%</p>
</template>
<style scoped>
.progress {
height: 6px;
background: #e5e7eb;
}
.progress__fill {
height: 100%;
background: #2563eb;
transition: width 0.1s linear;
}
</style>