Home > OS >  Jump to right side of html page
Jump to right side of html page

Time:02-26

I have an HTML page with a big table and many columns, I need to scroll right of page automatically on page load.

I've tried this code but it doesn't work for me :

</script><script type="text/javascript">  
                               
   var myDiv = document.getElementById('containerDiv');
   myDiv.innerHTML = variableLongText;
   myDiv.scrollRight = 0;

</script>

Is it a correct approch to auto scroll the page?

CodePudding user response:

You can try this code.

<script type="text/javascript">  
                           
  var myDiv = document.getElementById('containerDiv');

  myDiv.scrollTo(0, myDiv.scrollRight)

</script>

CodePudding user response:

Try like this:

// Getting div from DOM
const myDiv = document.getElementById('containerDiv');

// Getting div's position 
divRect = myDiv.getBoundingClientRect();

// Scrolling to div's position
window.scrollTo({
  top: divRect.top,
  left: divRect.left,
  // behavior: 'smooth'
});

/* 
behavior: 'smooth' will give a smooth sensation with a slow transition on scroll. 
I would personally recommend using it (mainly if this is not intended to run on load).
*/

Better & without comments:

const divRect = document.getElementById('containerDiv').getBoundingClientRect();
window.scrollTo({ top: divRect.top, left: divRect.left });

For information about getBoundingClientRect(), check this article https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

CodePudding user response:

if you want to scroll window then use

window.scrollTo(x-axis,y-axis);

or for specific div use

document.getElementById('container').scrollLeft  = 10000;

so full program be like

window.onload = function() {
 // for specific div
  document.getElementById('nan').scrollLeft  = 100000;
 
 //for window 
 /* window.scrollTo(10000, 0) */;
};

you can also see example https://jsfiddle.net/zcmhp2de/38/

  • Related