How to scroll to div/top/bottom in LWC that works in mobile app?

what should I do to scroll view to the certain place in my component DOM? I want both solutions to work on pc and salesforce app.
I’ve tried below functions:

  • this.template.querySelector('.selected-products').scrollIntoView() works but not on mobile (android nor ios)
  • window.scrollTo(0,0); doesn’t work at all
  • this.template.querySelector('.mydiv').scrollTop=0 doesn’t work at all

Answer

I have tried scrollIntoView() and it works just fine for me in desktop, mobile browser(chrome android) and salesforce mobile publisher(app). I do not have a physical iOS device to test but it works in emulator. Code sample –

scrollIntoView.html

<template>
    <lightning-combobox
        name="select"
        label="Select"
        value={value}
        options={options}
        onchange={handleChange}
    ></lightning-combobox>
    <div class="container_1">div 1</div>
    <div class="container_2">div 2</div>
    <div class="container_3">div 3</div>
    <div class="container_4">div 4</div>
</template>

scrollIntoView.js

import { LightningElement } from 'lwc';

export default class ScrollIntoView extends LightningElement {
    value = '1';
    get options() {
        return [
            { label: 'Div 1', value: '1' },
            { label: 'Div 2', value: '2' },
            { label: 'Div 3', value: '3' },
            { label: 'Div 4', value: '4' }
        ];
    }

    handleChange(event) {
        this.value = event.detail.value;
        let containerChoosen = this.template.querySelector('.container_' + this.value);
        containerChoosen.scrollIntoView();
    }
}

scrollIntoView.css

div {
    border: 1px solid;
    height: 25rem;
    margin: 1rem;
}

.container_1 {
    background-color: yellow;
}

.container_2 {
    background-color: blue;
}

.container_3 {
    background-color: green;
}

.container_4 {
    background-color: red;
}

I have also tried with scrollIntoViewOptions and found it to be working in Desktop and on Android device –

this.template.querySelector('.container_' + this.value).scrollIntoView({
            block: 'center',
            behavior: 'smooth'
        });

However, the MDN documentation suggests compatibility issue with Safari browsers. You can check proof of my implementation here.

Attribution
Source : Link , Question Author : naveen.singh , Answer Author : pk1772

Leave a Comment