1

I'm working with Svelte and I'd like to ask how can I get the value of offset width of a div?

This is my code

<script>
  export let students // string array
  let divWidth;
  console.log(divWidth) // this returns undefined, even though I bound it below
</script>

<style>
  .container {
    width: 250px;
  }
</style>

<div class="container">
  {#each students as student}
    <div bind:offsetWidth={divWidth} >
    {student}
    </div>
  {/each}
</div>

So basically I'd like to get the value of the offset width from each div, but it returns undefined. Any help would be appreciated!

2
  • It may take a moment to bind, what happens when you put that console log into onMount or a reactive statement? You are binding correctly but you need to handle moments where it’s not yet bound. Commented Jun 22, 2021 at 3:42
  • Ahh I can see the values of I do it in onMount! Thanks!
    – ffx292
    Commented Jun 22, 2021 at 5:23

2 Answers 2

2

Try to replace this line:

console.log(divWidth)

with

$: console.log(divWidth)

read more here: https://svelte.dev/tutorial/reactive-statements

0

In your example the offsetWidth of all the items would be 250 since they're in a div with an explicit width of 250px.

Also you are binding all of your items to a single variable. Instead you can turn your array of strings (students) into an array of objects and include width as one of the properties, then in your #each loop bind:offsetWidth to the variable dedicated to width for each of the items.

For instance if your array looks like:

let students = [
        {
            name: 'Jim',
            width: ''
        },
        {
            name: 'Dwight the fucking Schrute',
            width: ''
        },
        {
            name: 'Pam',
            width: ''
        },
    ]

Then you could bind to the width inside your #each block like so <div bind:offsetWidth={student.width} >.

But even then, you will still get 250 as the answer for all of these unless you are doing something else (like inlining) that will cause the individual items to have a different offsetWidth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.