Scroll left/right with Buttons in Blazor

Viewed 651

I have a few images in one row. Not all images can be seen. By scrolling to the right it would be possible to see the other images. I want to scroll to the right by clicking a button. How do I write my method ScrollRight to achieve my goal?

<div style="display:flex;">
    <button @onclick="ScrollLeft">A</button>
    <div style="overflow:hidden;">
        <div style="display:flex;position:relative;bottom:-30px;overflow-y:auto;">
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <img width="300" height="300" src="https://www.dogstrust.org.uk/help-advice/_images/164742v800_puppy-1.jpg" />
            <!-->and so on/!-->
        </div>
    </div>
    <button @onclick="ScrollRight">B</button>
</div>


@code {

    public void ScrollLeft()
    {

    }

    public void ScrollRight()
    {

    }

}
1 Answers

I created a .js file:

function ScrollRight(Element, Width) {
    document.getElementById(Element).scrollBy({
        top: 0, left: Width * Math.floor((document.getElementById(Element).offsetWidth / Width)), behavior: "smooth"
    })
}
function ScrollLeft(Element, Width) {
    document.getElementById(Element).scrollBy({
        top: 0, left: -Width * Math.floor((document.getElementById(Element).offsetWidth / Width)), behavior: "smooth"
    })
}

added @inject IJSRuntime JsRuntime and

@code {


    async Task ScrollRight()
    {
        await JsRuntime.InvokeVoidAsync(identifier: "ScrollRight", "scrollable-events", 255);
    }

    async Task ScrollLeft()
    {
        await JsRuntime.InvokeVoidAsync(identifier: "ScrollLeft", "scrollable-events", 255);
    }

}

in my .razor file.

Related