Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get full width of an element inside an "overflow-x: auto;" area?

I coded this:

$(document).ready(function() {
  $("button").click(function() {
    alert("Width of #text: " + $("#text").width());
  });
});
* {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

#container {
  width: 300px;
  height: 150px;
  background-color: grey;
  position: relative;
}

#scroll-area {
  overflow-x: auto;
  height: 100%;
}

#text {
  white-space: nowrap;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div id="container">
  <div id="scroll-area">
    <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
  </div>
</div>

<button>Get width of #text</button>

I would like to calculate the width of the #text element that is inside the #container element. Currently, it shows me 300px as result. But that is the width of the container, and not of the text element.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try with scrollWidth feature

$(document).ready(function() {
  $("button").click(function() {
    alert("Width of #text: " + $("#scroll-area")[0].scrollWidth);
  });
});
* {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

#container {
  width: 300px;
  height: 150px;
  background-color: grey;
  position: relative;
}

#scroll-area {
  overflow-x: auto;
  height: 100%;
}

#text {
  white-space: nowrap;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div id="container">
  <div id="scroll-area">
    <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
  </div>
</div>

<button>Get width of #text</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading