Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

go to top of div, but do not reposition div at top of page. JavaScript

  • SOLVED

<button onclick = "topOfDiv();"> click me </button>

<div id = "skyfall" style = "height:10rem; overflow-x: scroll">

<input id = "P1"> <br />
<input id = "P2"> <br />
<input id = "P3"> <br />
...
<input id = "P1000">

</div>

I want javascript or jquery function to go to id "P1". That is, I want <div id = "skyfall"> which is only 10rem in height to reposition itself at its beginning.
And of course, <a href = "#skyfall"> or <a href = "#P1"> do not work because that would load the page with the element at the top. And there is stuff at the page top which must remain intact.

<script>
function topOfDiv() {
....
}
</script>

Answers (1)

2018-12-05

Rainner Lins answers:

If I understand correctly, you want the div #skyfall to scroll back to it's top position when a button is clicked without scrolling the main page? You can do that by using the scrollTop property of the div. Give the button an ID also, like #btn and try something like this:


<button id="btn"> click me </button>
<div id="skyfall">...</div >



const btn = document.querySelector( '#btn' );
const div = document.querySelector( '#skyfall' );

btn.addEventListener( 'click', e => {
div.scrollTop = 0;
})


Here's the code running on JSfiddle:

https://jsfiddle.net/xzunmqyk/


User180435 comments:

It works but there is a problem. I have 8 sort buttons which must reposition the div. This needs to be done in a function(). Can you please change it to a function so the user sees the first line after a sort and display?


Rainner Lins comments:

Yeah sure, something like this?


function topOfDiv() {
const div = document.querySelector( '#skyfall' );
div.scrollTop = 0;
}


User180435 comments:

Got it! Thanks!