Home > Software engineering >  Autoscrolling when the last word of line is reached in a div
Autoscrolling when the last word of line is reached in a div

Time:01-31

I am thinking of adding an effect that when the last word of the line in div is reached. Then the div should auto-srcoll and the second line should appear at the top of the div. For example in this image 'can' is the last word of the line. Once user has typed 'can' and hit space then the div should auto-scroll and the line starting with 'estimate' should appear at the top. Number of words in a single line of the div changes based on the width of the viewport. I have tried searching this one the web but couldn't find a solution. Please help.

enter image description here

CodePudding user response:

You can check here: https://www.w3schools.com/howto/howto_css_custom_scrollbar.asp

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scrollbars

https://www.educba.com/scrollbar-in-html-table/

Using above links you can easily get the scrollbar.

CodePudding user response:

You can achieve this by using JavaScript and CSS to determine the last word in a line and dynamically set the scrollTop property of the div to scroll to the next line.

// Get the div element
var div = document.getElementById("yourDivId");

// Get the height of a single line in the div
var lineHeight = parseInt(window.getComputedStyle(div).lineHeight);

// Listen for changes to the div's content
div.addEventListener("input", function() {
  // Get the current scroll position
  var scrollTop = div.scrollTop;

  // Get the height of the div
  var divHeight = div.offsetHeight;

  // Check if the last word is at the bottom of the div
  if (scrollTop   divHeight >= div.scrollHeight - lineHeight) {
    // If so, scroll to the next line
    div.scrollTop = scrollTop   lineHeight;
  }
});
  • Related