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.
CodePudding user response:
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>