I have this simple code:
<input type="text" value="Some Extremely Really Long Word" />
How do I make sure the value (in this case 'Some Extremely Really Long Word') shows up completely (ie. is not clipped).
I tried to apply the style: overflow:visible and display:nowrap but it didn't work.
I don't want to apply a style like: width: 200px because I don't know how long the words will be.
Fiddle: http://jsfiddle.net/TfKbp/3/
I've used this in the past to dynamically expand the width of a text INPUT to the width of its contents. Basically, you create a SPAN with the exact same font family, font size, etc. and use the keypress event to add the characters, measure its size, and resize the INPUT.
EDIT 1
To dynamically size the text box for its initial value requires just a little more code...
HTML
<input id="txtLong" type="text" value="What does the fox say? Ring-ding-ding-ding-dingeringeding! Gering-ding-ding-ding-dingeringeding! Gering-ding-ding-ding-dingeringeding! What the fox say?" />
<span id="spanLong" style="display: none;"></span>
JavaScript
var txtLong = $("#txtLong");
var spanLong = $("#spanLong");
spanLong.text(txtLong.val());
txtLong.css("width", spanLong.width());
txtLong.keypress(function(e){
if (e.which !== 0 && e.charCode !== 0) {
var char = String.fromCharCode(e.keyCode | e.charCode);
spanLong.text(txtLong.val() + char);
txtLong.css("width", spanLong.width());
}
});
CSS
input, span {
padding: 2px 3px;
font-size: 11px;
font-family: Sans-serif;
white-space: pre;
}
New and Improved Fiddle
EDIT 2
Since you're looking for a way to select text by clicking on it, I thought I'd also point out that you don't necessarily need an INPUT to do that. Check out this JSFiddle. And as an added bonus, it doesn't use JQuery. I know you were kinda opposed to that.
EDIT 3
I found a way to simply resize a textbox to the width of its initial value using only plain JavaScript by adapting this blog post.
HTML
<input type="text" id="txtLong" value="Some very long text that all needs to show"/>
<span id="ruler"></span>
JavaScript
String.prototype.visualLength = function()
{
var ruler = document.getElementById("ruler");
ruler.innerHTML = this;
return ruler.offsetWidth;
}
window.onload = function() {
var txtLong = document.getElementById("txtLong");
var width = txtLong.value.visualLength();
txtLong.setAttribute("style", "width:" + width + "px");
}
CSS
#ruler {
visibility: hidden;
white-space: nowrap;
}
#txtLong, #ruler {
font-family: sans-serif;
font-size: 11pt;
}
JSFiddle
There is no declarative way (that I know of) to do this, but it is fairly easy to do using jQuery. What you essentially need to do is make a second element (not an input) that contains all the same styling as the input. Then measure the width of the second element, and set width of the input to that new width.
Here's how you'd do that:
HTML:
<input type='text' value='Some Extremely Really Long Word' id='my-input' />
jQuery:
$(document).ready(function() {\
var $input = $('#my-input'),
$clone = $('<div></div>');
$clone.html($input.val());
$clone.css({
whiteSpace: 'nowrap',
font: $input.css('font'),
paddingLeft: $input.css('padding-left'),
paddingRight: $input.css('padding-right')
});
$clone.appendTo($('body'));
$input.css({
width: $clone.width();
});
$clone.remove();
})
Related
I am building a simple chat bot.On each new message received from the server, a new HTML element is created and pushed to the browser. So, for example, message 1 will be:
<div class="message-computer"><p>Hi, how are you?</p></div>
Then you (the user) types/sends a message, which shows up as:
<div class="message-user"><p>I am good, thanks!</p></div>
and so on and so forth. I created a slider to change the size of the text being sent to/from the chat bot. It now works, but it only edits EXISTING HTML elements. New messages sent to/from the server are still in the original size.
$('input').on('change', function() {
var v = $(this).val();
$('.message-computer p').css('font-size', v + 'em')
$('.message-user p').css('font-size', v + 'em')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" value="1" min="1" max="1.6" step=".1" id="slider" ondrag="changeSize()" />
How can I make the change in font size apply to all new elements sent to the browser?
Thanks
Not sure I understand well your problem, your code snippet doesn't contain any text.
But when using jQuery to update style, CSS statment is added individualy into each element style attribute (look at your browser inspector).
So newly added elements wont have their style attribute modified until you rechange the input value, and so will inherit from global CSS rules.
I suggest to apply the font style to the parents .message-computer & .message-user.
If you can't, wrap p elements into a dedicated div and apply the style to the div.
If you really need to apply it individually to each element, run $('input').trigger('change'); just after inserting new elements into the DOM.
What you want to do is add a class to a parent tag of your HTML, and to then have a CSS rule which applies to all of the like-elements on the page.
Then, no matter how many .message element you add to your .parent element, a CSS rule applies to them equally.
For instance, something like this would work. You could make this approach more efficient, but this illustrates the idea.
$('input').on('change', function() {
var v = $(this).val();
$('.parent').removeClass('font-1');
$('.parent').removeClass('font-2');
$('.parent').removeClass('font-3');
$('.parent').removeClass('font-4');
$('.parent').removeClass('font-5');
$('.parent').addClass('font-' + v);
});
.parent.font-1 .message {
font-size: 1em;
}
.parent.font-2 .message {
font-size: 2em;
}
.parent.font-3 .message {
font-size: 3em;
}
.parent.font-4 .message {
font-size: 4em;
}
.parent.font-5 .message {
font-size: 5em;
}
.message-computer {
color: red;
}
.message-user {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" value="1" min="1" max="5" step="1" id="slider" ondrag="changeSize()" />
<div class="parent font-1">
<div class="message-computer message"><p>I AM ROBOT</p></div>
<div class="message-user message"><p>Only human.</p></div>
</div>
You're only modifying existing node.
If you want that new node take those rules simply build a javascript function that add or update dynamically a css node
function changeSize(v)
{
var css = [
".message-computer p, .message-user p {font-size: "+v+"em;}"
].join("");
var head = document.head || document.getElementsByTagName('head')[0];
var style = null;
if(!document.getElementById("customTextSize"))
{
style = document.createElement('style');
style.id = "customTextSize";
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
else
{
style = document.getElementById("customTextSize");
style.removeChild(style.firstChild);
style.appendChild(document.createTextNode(css));
}
}
On your on change simply call the function :
changeSize(v)
I'm trying to make an auto resize like input, like when the user type in, the input will adjust automatically to fit the value inside the input but seem's I can't make it right or working. Any ideas, help please?
$(document).ready(function(){
$('input').on('input',function(){
$(this).css('width',$(this).width()+$(this).val().length );
});
});
input{border:1px solid red;width:30px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
I suggest using contenteditable-span in this case, i hope it helps.
#test{border:1px solid red;width:30px;}
<span id="test" contenteditable>I'm trying to make an auto resize like input</span>
If your goal is for it to be just as wide as necessary, maybe with a 30px buffer, then the issue is you're adding to the width every time rather than recalculating it from scratch. It would also help if you knew how wide a character might be, so probably best to set the font size specifically or even use another hidden element to measure how wide the rendered text is; here I use a span for that:
$(document).ready(function(){
$('input').on('input',function(){
var $this = $(this);
// Get the value
var val = $this.val();
// Put it in the hidden span using the same font information
var $hidden = $(".hidden");
$hidden.text(val);
// Set the input to the span's width plus a buffer
$this.css('width', $hidden.width() + 30);
});
});
input {
border:1px solid red;
font-size: 14px;
width:30px;
}
.hidden {
font-size: 14px;
display: none;
}
<input type="text">
<span class="hidden"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have been scratching my head since yesterday on this problem, which I cannot solve. I am a new starter to Twitter Bootstrap and everything was going well until yesterday.
I am using the latest JQuery v1.11.1 and Twitter Bootstrap v3.3.1. Yesterday I downloaded Bootstrap Tags Input, from here: http://timschlechter.github.io/bootstrap-tagsinput/examples/
The plugin works and I have changed the CSS styles to match my page layout but the problem I am having is that the placeholder attribute will not disappear when on focus. If I type in a tag and add a comma value the placeholder will show until I start typing and then it will disappear again.
I have tried using JQuery onfocus function to remove the attribute when onfocus but it doesn't do anything. What I want to achieve is that when onfocus the placeholder does not show at that point not even on blur.
My input field is demonstrated below:
<input type="text" name="customer_tags" id="customer_tags" value="" placeholder="Enter you tags" data-role="tagsinput" required />
two years later, but i found how to work around this issue. First, if you inspect the DOM , you will see a new input text, which inherits our placeholder text, but without the extra function onblur, onfocus that everybody mention before.
<div class="bootstrap-tagsinput">
<input placeholder="text inherited from our input" size="23" type="text">
</div>
Then, to fix this issue, you had to create a jquery function to point that input. Like this:
$('.bootstrap-tagsinput input').blur(function(){jQuery(this).attr('placeholder', '')})
pointing to element with the class "bootstrap-tagsinput" and then the "input" objects inside. You can add a .focus function too if you prefered. In my case, works when the user leave the object and the input tags look clean without placeholder.
HTML5 placeholder attribute will not disappear when you focus in the input tag... it will only disappear when you start typing. It is the default behavior.
You can see it # W3Schools as well...
Following code works in my case:
<input type="text" name="add_image_tags" id="add_image_tags" data-role="tagsinput"
class="form-control" placeholder="Enter tags" data-placeholder="Enter tags" value="" />
handlePlaceHolder(); //Call during page load
function handlePlaceHolder()
{
if($('#add_image_tags').val())
{
$('.bootstrap-tagsinput input').attr('placeholder', '');
}
else
{
$('.bootstrap-tagsinput input').attr('placeholder',$('#add_image_tags').attr('data-placeholder'));
}
}
$('#add_image_tags').on('itemRemoved', function(event) {
// event.item: contains the item
handlePlaceHolder();
});
$('#add_image_tags').on('itemAdded', function(event) {
// event.item: contains the item
handlePlaceHolder();
});
Try this, i hope it's working:
<form>
<div>
<label for="name" class="left-label">Your Name</label>
<input type="text" class="example-two" placeholder="Enter you tags" id="name" name="name">
</div>
</form>
CSS:
[placeholder]:focus::-webkit-input-placeholder {
transition: opacity 0.5s 0.5s ease;
opacity: 0;
}
.example-two:focus::-webkit-input-placeholder {
transition: text-indent 0.5s 0.5s ease;
text-indent: -100%;
opacity: 1;
}
body {
}
form {
display: inline-block;
margin-top: 20px;
}
label {
display: block;
text-align: left;
font: bold 0.8em Sans-Serif;
text-transform: uppercase;
}
.left-label {
float: left;
padding: 8px 5px 0 0;
}
input[type=text] {
padding: 5px;
text-indent: 0;
}
form div {
margin: 20px;
clear: both;
text-align: left;
}
JSFiddle
EDIT:
Working on IE too:
JSFiddle
That's how the plugin behaves. As soon as you hit "enter" or "comma" it creates a span tag (see image attached)and shift the input to the right. So now the input has no value and should show the placeholder.
In their docs it's mentioned [Search for confirmKeys]
Array of keycodes which will add a tag when typing in the input.
(default: [13, 188], which are ENTER and comma)
Change the confirmkeys to remove creation of tags when you type comma
Edit:
On your site I tried the below method in console and it worked.
$('input').tagsinput({
confirmKeys: [13]
});
I was able to do a quick fix using jquery. The behavior I wanted should do two things:
1) Remove placeholder while on page after I've focused and started typing. So I will run it on keyup.
$(document).on('keyup', '.bootstrap-tagsinput input', function(){
$(this).attr('placeholder', '')
})
2) If there are already labels in an input, then I don't obviously need a placeholder. I run this on page load.
$('.labels').each(function(){
var len = $(this).tagsinput('items');
if(len){
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', '');
}
})
In my case, after a little modification, it works fine.
$('#txtTimeSlot').on('change', function () {
var len = $(this).tagsinput('items').length;
if (len > 0) {
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', '');
} else {
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', $(this).attr('placeholder'));
}
});
for all who are still having this problem, just change the line in the javascript file:
from:
cancelConfirmKeysOnEmpty: true,
to
cancelConfirmKeysOnEmpty: false,
And thats all!
This question already has answers here:
Creating a textarea with auto-resize
(50 answers)
Closed 8 years ago.
On one of my pages, I have a text area html tag for users to write a letter in. I want the content below the text area to shift down, or in other words, I want the text area to resize vertically with each line added to the text area and to have the content below simply be positioned in relation to the bottom of the text area.
What I am hoping is that javascript/jquery has a way to detect when the words wrap, or when a new line is added and based on that do a resize of the text area container.
My goal is to make the content below the text area stay the same distance from the bottom of the text no matter how much a user writes.
The text area creates a scroll bar when the text overflows.
Since I wasn't too happy with several solutions I found on the web, here's my take on it.
Respects min-height, max-height.
Avoids jumping around and flashing the scrollbar by adding a buffer to the height (currently 20, may replace by line-height). However still shows scrollbar when max-height is reached.
Avoids resetting the container scroll position by incrementally reducing the textarea height instead of setting it to 0. Will thusly also remove all deleted rows at once. Works in IE and Chrome without browser sniffing.
http://jsfiddle.net/Nd6B3/4/
<textarea id="ta"></textarea>
#ta {
width:250px;
min-height:116px;
max-height:300px;
resize:none;
}
$("#ta").keyup(function (e) {
autoheight(this);
});
function autoheight(a) {
if (!$(a).prop('scrollTop')) {
do {
var b = $(a).prop('scrollHeight');
var h = $(a).height();
$(a).height(h - 5);
}
while (b && (b != $(a).prop('scrollHeight')));
};
$(a).height($(a).prop('scrollHeight') + 20);
}
autoheight($("#ta"));
http://www.jacklmoore.com/autosize/
Download the plugin first:
Step 1: Put "jquery.autoresize.min.js" where you keep your jquery plugins.
Step 2: Link the file in HTML -> <script src="jquery.autosize.min.js" type="text/javascript" ></script> Be sure that this link comes after your jquery link, and before your own javascript/jquery code links.
Step 3: In your javascript code file simply add $('#containerToBeResized').autosize();
$('textarea').keyup(function (e) {
var rows = $(this).val().split("\n");
$(this).prop('rows', rows.length);
});
this work sample.
See this Fiddle from this answer. That increases the height of the textarea based on the number of lines.
I think that's what you're asking for.
Copied the code from the answer below:
HTML
<p>Code explanation: Textarea Auto Resize</p>
<textarea id="comments" placeholder="Type many lines of texts in here and you will see magic stuff" class="common"></textarea>
JS
/*global document:false, $:false */
var txt = $('#comments'),
hiddenDiv = $(document.createElement('div')),
content = null;
txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common');
$('body').append(hiddenDiv);
txt.on('keyup', function () {
content = $(this).val();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content + '<br class="lbr">');
$(this).css('height', hiddenDiv.height());
});
CSS
body {
margin: 20px;
}
p {
margin-bottom: 14px;
}
textarea {
color: #444;
padding: 5px;
}
.txtstuff {
resize: none; /* remove this if you want the user to be able to resize it in modern browsers */
overflow: hidden;
}
.hiddendiv {
display: none;
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: break-word; /* future version of deprecated 'word-wrap' */
}
/* the styles for 'commmon' are applied to both the textarea and the hidden clone */
/* these must be the same for both */
.common {
width: 500px;
min-height: 50px;
font-family: Arial, sans-serif;
font-size: 13px;
overflow: hidden;
}
.lbr {
line-height: 3px;
}
Using this javascript to show more-less, is there a simple way to make the text cut off clean so that it displayes whole lines of text (doesn't slice them horizontally)?
<div id="description" style="height: 20px; overflow: hidden">
Lots of text.
</div>
Show more/less>>
<script>
var open = false;
$('#more-less').click(function() {
if (open) {
$('#description').animate({height:'20px'});
}
else {
$('#description').animate({height:'100%'});
}
open = !open;
});
If it makes it easier I can truncate on <br /> tags.
Change 20px to a value in ems, such as 2em. One em is (approximately?) equal to the height of one line. You should also set the margin and padding on the p tag in ems.