Determine the dimensions of a div element with overflow property and utilize the information to establish a boundary for the scrollbar

While this may seem like a straightforward question, I'm struggling to find a solution.

Consider a div with an overflow property set, causing a scroll bar to appear when the text added is larger than its dimensions. You can see an example of this here: http://jsfiddle.net/Lddxgzvz/

My goal is to use vanilla JavaScript to determine the new dimensions of the div with the scroll bar and then use that information to restrict the amount of text that can be added to the div.

Let me explain further...

Suppose the limit for how much can be added to the div is 200px. Once the div reaches this size, I want the scroll bar to remain static. For instance, if the total width of the following text is 250px:

Hello World Foo Bar

and the word Bar is 50px wide, only this portion should be visible within the div:

Hello World Foo

I attempted to use JavaScript to retrieve the height and width of the div, but it doesn't account for the overflow property. It simply returns the initial height and width that I set for the div.

I hope my intentions are clear, and I will provide additional edits if needed.

Answer №1

If you're looking to enhance the styling, consider implementing an inner wrapper using this CSS:

display: inline-block;
max-width: 300px; /* Adjust as needed */
overflow: hidden;

.main-container {
  border: solid 1px gray;
  height: 150px;
  width: 150px;
  overflow: auto;
}
.inner-wrapper {
  display: inline-block;
  max-width: 300px;
  overflow: hidden;
}
<div class="main-container">
  <div class="inner-wrapper">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  </div>
</div>
<div class="main-container">
  <div class="inner-wrapper">
    Short text
  </div>
</div>

Answer №2

It seems like you're looking for the properties scrollWidth and scrollHeight

console.log(document.getElementById('content').scrollWidth);
console.log(document.getElementById('content').scrollHeight);

Check out this live demonstration: http://jsfiddle.net/JPzLWbqx/3/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on changing the color of a dropdown select option in Angular 8

I have been experimenting with changing the color of a dropdown select menu based on the value selected by the user. Here is the code I have been working with: App.component.ts @Component({ selector: 'my-app', templateUrl: './app.comp ...

CSS selectors can be used to alter the styling of the container surrounding the text

My current content includes: <span> Hello </span> I am looking to apply CSS selectors to either replace or enclose the text inside the element with an <h1> Is it doable using only CSS selectors? ...

What could be the reason for the absence of this Javascript function in my attribute?

I have been working on an app using electron, and I have a function that successfully adds tabs to the app. The issue arises when I try to add tabs via JavaScript with the onclick attribute - they show up as expected but do not execute the code to hide and ...

Organizing the directory layout for the /profile/username/followers route in NextJs

I want to set up a folder structure for my website that can accommodate the URL /profile/username/followers, where the username will be different for each user. The proposed folder structure is as follows: pages -- profile -- [username].js Curren ...

Utilizing Javascript for a Stopwatch/Countdown in the Format: 00:00:00

I am currently working with this block of code: function startStopwatch() { vm.lastTickTime = new Date(); $interval.cancel(vm.timerPromise); vm.timerPromise = $interval(function() { var tickTime = new Date(); ...

Tips for preventing text wrapping in off-canvas design

Seeking advice for my Web Application prototype - looking to prevent text wrapping in off-canvas menu paragraphs using CSS or JS. New to building this type of menu, I used an example from W3Schools to achieve the current design. <!DOCTYPE html> ...

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

Reloading specific content on an ASP.NET CORE Razor Pages website

Hello, I am new to Razor pages and recently integrated the AdminLTE template into my Razor Page application successfully. In the _Layout.chtml file, I inserted the sidebar menu with anchor tags that link to specific pages, as well as the header bar and fo ...

Trouble arises when trying to open a new window using the Angular 8 CDK

I am attempting to open my component in a new window, similar to this example: https://stackblitz.com/edit/angular-open-window However, when the window opens, my component is not displayed and I receive the following error in the console: Error: Must pro ...

Is JavaScript overwriting the existing value?

I am completely new to JavaScript and I am struggling with a seemingly simple issue. I have an array of usernames that I am iterating over. My goal is to map these usernames to click event methods, although I am aware that this may not be the most efficien ...

Retrieving the current date in React from a distinct date format

Does anyone know how to retrieve today's date in the following format using React? "2019020420" I have a function that currently retrieves the current date. How can I modify it to output the desired date format shown above? getCurrentDate( ...

Upon page reload in Nuxt.js middleware, Firebase authentication is returning as null

Just started with nuxtjs and using the Nuxt firebase library for firebase integration. After a successful login, I'm redirecting the user to the "/member/desk" route. However, if I refresh the page on that particular route, it redirects me back to "/a ...

I keep encountering an issue with Nodemailer where it keeps throwing the error message "TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument needs to be a string or.."

The error message is incredibly long, but here is a brief excerpt: TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object at PassThrough.Writable.write ( ...

.eslintignore not functioning as intended

Recently, I started working on a Vue template project that includes ESLint. However, I found that I wanted to disable ESLint for some reason. To do this, I followed the recommended steps and created a file with the following content: **/*.js This file wa ...

Insert a new, unique div onto an HTML webpage using JavaScript, ensuring no duplicates are created

Having an issue with this code snippet where nothing is being added. It seems like the variable result may not be taking a number or something else, but I'm not entirely sure why. $(document).ready(function () //document.getElementById(1).style. ...

Switch a div to a computed location

I'm having trouble getting this code to animate a div to a calculated position. Can someone please help me troubleshoot? $(document).ready(function() { var is_Clicked = false; $("#togglebutton").click(function() { if (is_Cli ...

Error: Module not found - Unable to locate 'dropzone'

Since migrating from Angular 4.4 to Angular 8.0, I encountered the following issue: ERROR in ./src/attributes/import/import.component.ts Module not found: Error: Can't resolve 'dropzone' in 'C:....\src\attributes\imp ...

Designing a custom HTML calendar

I am currently working on a school project where I am creating a calendar using HTML. So far, I have set up the basic structure of the page. What I want to achieve is a functional calendar where users can create appointments that will be displayed accordi ...

What is the best way to continuously execute the ajax request for downloading a pdf file?

if( $.isArray(certTypeReq) ){ $.each(certTypeReq,function(key,certType){ $.ajax({ url: baseUrl+"/user/certificate/getlink", type: 'GET', data: { 'certType' : certType}, ...