I have a variable that gets the height of the scrollbar when overflow-x-auto
and I am using a svelte javascript framework.
for solving this issue I used this code:
<script> let hWith = 0; let hNot = 0; $: scrollBarHeight = hWith - hNot; </script> <div bind:offsetHeight={hWith} bind:clientHeight={hNot} > my content... </div>
and is working fine and outputs: 17
the problem is that bind:
will always fire at every rerender.
As you know a scrollbar will not magically change the size, so it is not important to recalculate always the value of height
once we get the 17 value (that can be different depending on the browser), stop recalculating.
and where is the problem?
the problem is that the variable need to be reactive with $:
at the start,
because since the container will not overflow this means is 0
but once we get a number greater than 0. (returnedValue > 0
)
the variable doesn’t need to be reactive anymore
I basically want that when I save the scrollBarHeight
(a simple calculation hWith - hNot
), I will not calculate it anymore.
you know I don’t like the fact that I can’t write directly the formula inside one variable instead of 3.
with bind:
it will always set the variable with the new value. (that can be inefficient since I the value don’t change a lot)
❌
let hWith = 0; let hNot = 0; $: scrollBarHeight = hWith - hNot;
✅ something like this.
$: scrollBarHeight = if (div.offsetHeight - div.clientHeight > 0) { // logic/code to make this variable not reactive anymore return div.offsetHeight - div.clientHeight; }
why do I need it?
this logic is a child, not the body. so this is why something is overflowing. and I need that value for correcting some bugs.
the problem the child changes a lot and rerenders and this maybe can rerender and also bind the values a lot.
Advertisement
Answer
You can just declare a regular variable and add a reactive statement without immediate assignment. E.g.
let scrollBarHeight = 0; $: if (scrollBarHeight == 0 && div.offsetHeight - div.clientHeight > 0) { scrollBarHeight = div.offsetHeight - div.clientHeight; }