euvl/vue-js-toggle-button

Toggle width depending on label length

Opened this issue · 1 comments

Hello :)

Is there a way to automatically set the width of the toggle depending on the label length.
For instance if you use it on a app that has multi language and the English is on/off but on some other languages may be longer words (xxxxx / xxxxxxxx). So if the width is statically set to 50 it will cut the word.

Best regards,
Simona

I had to do this for one of my projects and used the following solution (I've simplified a lot for this post)

My code is in TypeScript and using Vue 2. But should be very similar in vanilla JS.

To sum it up. I am calling a function on the width attribute of toggle-button and you pass in the ref of the button. Then in the function you can access the lastchild element of the html and get the clientWidth of the text label. Kinda hacky solution but best I could think of without editing the package itself.

<toggle-button
    :labels="{ checked: toggleText, unchecked: toggleText }"
    :height="32"
    :width="calculateToggleButtonWidth('myToggleButton')"
    :ref="myToggleButton"
></toggle-button>

calculateToggleButtonWidth(name: string): number {
    let toggleButton: any = this.$refs[name];
    let paddingWidth: number = 45;

    if (toggleButton) {
        return toggleButton[0].$el.lastChild.clientWidth + paddingWidth;
    }

    // Default (Also acts as maximum text width)
    return 180
}