Reputation:
I'm building a little sticky notes app for fun, and sometimes this happens:
(It's because the first word is wider than the width of the note.)
Is there a way to check whether the scrollbar is present with Javascript? If I can do that, I can resize the note until it contains the text without the scrollbar.
Upvotes: 2
Views: 1613
Reputation: 21
For best cross-browser support I would recommend the word-wrap approach plus giving the element a set width (100%, or some pixel width) so it does not widen. This should provide the best solution.
You can also set overflow-x: hidden; to simply hide the scroll bar but it does not work in IE7/8 and also will cause the overflowed text to be not displayed instead of wrapped, which is probably not what you want.
Upvotes: 2
Reputation: 10119
What I've done in similar circumstances is append the text to a temporary element with visibility hidden, measure it, and if too large, do something to address it (which could include manually wrapping the text inserting BRs, or just widening the final element that you eventually place the text into). This gives a lot more control than using word-wrap: break-word;
Upvotes: 0
Reputation: 50187
Here's a way to accomplish what the OP asked for, to widen a div if it has a scroll bar until there's no longer one:
var autoWiden = function ( elem ) {
var checkForScroll = function() {
var tsl;
elem.scrollLeft += 10; // try to scroll
tsl = elem.scrollLeft; // will be 0 if no scroll bar
elem.scrollLeft = 0; // reset scroll
return tsl;
};
while (checkForScroll() > 0) {
elem.style.width = (elem.offsetWidth + 10) + 'px';
}
};
Upvotes: 2
Reputation: 10743
This CSS3 property will break a word within if it is too large for its container:
#selector {
word-wrap: break-word;
}
word-wrap: normal;
to toggle style
This works in basically every browser and believe it or not, support for the property goes as far back as IE5. Credit for this goes to Louis Lazaris for his post, Word-Wrap: A CSS3 Property That Works in Every Browser.
Upvotes: 7