As you can see it I am not able to scroll down the page when I click on the button, This all code running in one file in App.js
Even I tried with useRef() and UseState() also but not working
I need help in JavaScript logic only
Javascript:
const myFunction = () => {
const element = document.getElementById("myDIV");
element.scrollLeft = 50;
element.scrollTop = 10;
};
HTML:
<div
id="myDiv"
style={{ height: "250px", width: "250px", overflow: "auto" }}
>
<div
id="content"
style={{
height: "800px",
width: "2000px",
backgroundColor: "coral",
}}
>
<button onClick={myFunction}>Scroll</button>
<p>Some text inside a div element.</p>
<p>Some text inside a div element.</p>
<p>Some text inside a div element.</p>
<p>Some text inside a div element.</p>
</div>
</div>
Here:
the ID is wrong. It should be
myDivbecause you set the div's ID tomyDiv:and also you can use the
scrollfunction ofElementinstead of settingscrollLeftandscrollTop:But I recommend using refs (I know you mentioned it but I'm not sure if you used it correctly).
Create a ref:
Assign the ref to the div:
Then scroll it (you don't need the element variable anymore):