Reputation: 555
I have this code which dynamically displays value from input field inside the documents 'div'. I've set up 'div' max-width property, but it looks like it works only if there is a space inside input string, if there isn't the string inside 'div' can go on and on and on... in one line. How do I fix that?
<!DOCTYPE html>
<html>
<head>
<style>
div {
max-width: 300px;
font-size:40px;
color:red;
font-weight:bold;
background-color:yellow;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").keyup(function(){
$("div").text($("input").val());
});
});
</script>
</head>
<body>
Sample value: <input type="text">
<div></div>
</body>
</html>
Upvotes: 0
Views: 256
Reputation: 56
if you wanna display the value in line, just set the overflow of div to hidden, and if you want to display the value in multiple lines, just set the word-wrap of div to break-word.
The word-wrap CSS property is used to to specify whether or not the browser is allowed to break lines within words in order to prevent overflow when an otherwise unbreakable string is too long to fit.
The overflow property specifies whether to clip content, render scrollbars, or display overflowing content when it is too large for its block-level container.
Upvotes: 1
Reputation: 1369
Have a look at this fiddle max width property
HTML :-
Sample value: <input type="text">
JQuery :-
$(document).ready(function(){
$("input").keyup(function(){
$("div").text($("input").val());
});
});
CSS :-
div {
max-width: 300px;
font-size:40px;
color:red;
font-weight:bold;
background-color:yellow;
word-wrap : break-word;
}
Upvotes: 1
Reputation: 4398
You can use the css property word-wrap:break-word;
in the div element. It works for all browsers.
word-break: break-all;
Upvotes: 1
Reputation: 11502
You need to add word-wrap: break-word;
property for this:
$(document).ready(function(){
$("input").keyup(function(){
$("div").text($("input").val());
});
});
div {
max-width: 300px;
font-size:40px;
color:red;
font-weight:bold;
background-color:yellow;
word-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Sample value: <input type="text">
<div></div>
Upvotes: 2