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;
}
Related
I am developing a web application using AngularJS. I find myself in a situation where I have a bar (with the css I created a line) that must dynamically lengthen and shorten.
I know that JQuery scripts are sufficient to do this. For example, if my css is like this:
.my_line{
display:block;
width:2px;
background: #FFAD0D;
height: 200px; /*This is the part that needs to dynamically change*/
}
I could in the controller resize the line (of my_line class) simply with:
$(".my_line").css("height", someExpression*100 + 'px');
The thing is, I would like to dynamically resize the line based on the size of another div element (Or, in general, any HTML element of my choice).
I don't know how to get (at run-time) the size of a certain page element in terms of height.
Only in this way I would be able to create a line that dynamically lengthens or shortens as the size of a div (or some other element) changes!
How do you do this? So I will avoid writing hard-coded the measures but I want make sure that they vary as the dimensions of other elements on the page vary
I hope this is helping:
$(".my_line").css("height", $("#referenceElement").height()*5 + 'px');
.my_line{
display:inline-block;
width:2px;
background: #FFAD0D;
}
#referenceElement {
display:inline-block;
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my_line"></div>
<div id="referenceElement">Hi, I'm 5 time smaller than the orange line!</div>
Here I am using the setInterval to track the div's height (you can do width as well) and storing it in a previousHeight variable and comparing it every interval
Then according to the comparison, it will determine if the height of the div has changed. If it has then it will change the height of the other div according to the height of the first div
You can create multiple variables and track multiple elements in the same setInterval
$(document).ready(function(){
var previousHeight = parseInt($("#my-div").css("height"));
setInterval(function(){ checkHeight(); }, 100);
function checkHeight() {
// Check height of elements here
var currentHeight = parseInt($("#my-div").css("height"));
if(currentHeight != previousHeight) {
previousHeight = currentHeight;
$("#dynamic-div").css("height", parseInt(currentHeight) + "px");
}
}
$("#button").click(function() {
$("#my-div").css("height", parseInt(previousHeight) + 5 + "px");
})
})
#my-div{
background: #000000;
height: 20px;
width: 20px;
}
#dynamic-div{
background: teal;
height: 20px;
width: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my-div">
</div>
<button id="button">Increase div height</button>
<div id="dynamic-div">
</div>
I want to display something e.g div under text area where user typing
I managed to obtain where he's currently typing via selectionStart/End, but how can I actually calculate coordinates (x,y) of his cursor?
I suppose there are other ways of achieving that than these two:
Calculating in which row user is (based on font size, text area width and characters count in that text area).
x as textarea.X + selectionStart in this row
y as textarea.Y + rows * font size
I found this, but it is almost 10 years old
https://github.com/Codecademy/textarea-helper
$('textarea').on('keyup paste cut mouseup', function () {
// Get the textarea's content height.
var contentHeight = $(this).textareaHelper('height')
// Set the textarea to the content height. i.e. expand as we type.
$(this).height(contentHeight);
// Follow the caret arounbd.
$('.tail').css(
$(this).textareaHelper('caretPos')
);
});
// Call it manually at first.
$('textarea').keyup();
.tail {
background: red;
width: 50px;
min-height: 50px;
position: absolute;
}
textarea {
width: 250pxpx;
min-height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://rawgit.com/Codecademy/textarea-helper/master/textarea-helper.js"></script>
<textarea></textarea>
<div class="tail"></div>
Situation is as follows: I made a tool allowing a user to create flashcards (stored in a mysql-library). Now if you want to print the flashcards, the script generates a table in which the td's have a fixed width (in px), inside is a div containing the user-entered text for the front or backside of the flashcard. Since the amount of text can vary, the standard font-size is reduced if necessary. Looks like that:
HTML:
<table class="cardtable">
<tr>
<td class="cardtd wrap"><div class="adjustsize">
Shorter Text here in the first td
</div></td>
<td class="cardtd wrap"><div class="adjustsize">
Might be a loooooooooooooooong text here in the second td
</div></td>
</tr>
</table>
CSS:
table.cardtable {
table-layout:fixed;
border-collapse:collapse;
page-break-before:always;
}
td.cardtd {
width: 470px;
max-width: 470px;
height:300px;
max-height:300px;
font-size:11px;
padding-top:20px;
padding-bottom:20px;
padding-left:22px;
padding-right:22px;
}
td.wrap { /*if a word is too long -> break it */
white-space: pre; /* CSS 2.0 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3.0 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: -moz-pre-wrap; /* Mozilla */
white-space: -hp-pre-wrap; /* HP Printers */
word-wrap: break-word; /* IE 5+ */
}
div.adjustsize {
display:block;
max-width:inherit;
max-height:inherit;
font-size:100%;
overflow:hidden;
vertical-align:middle;
text-align:center;
}
Js:
<script type='text/javascript'>
$(function() {
$('div.adjustsize').each(function() {
var fontSize = 100;
while (this.scrollHeight > $(this).height() && fontSize > 0) {
fontSize -= 0.2;
$(this).css('font-size', fontSize + '%');
}
});
});
</script>
So now my big problem is: When I let the script render the table in Firefox, the JS adjusts the size of the font correctly, meaning that if a text is too long at first, the JS reduces the font size until it fits the div. But if I want to print the page afterwards, in the print-mode of firefox the text suddenly exceeds the div, meaning that a part of it is not visible anymore (scaling 100%)!
PS: I chose the width and height of the td to fit it more or less on a A4 sheet of paper.
EDIT:
Thanks for the suggestions. I tried using the #media css styles and I checked every css value I could imagine with the window.onbeforeprint and window.onafterprint function to see if anything somehow changed but nothing. Every value including padding, margin, letter-spacing, etc. is exactly the same as before, yet when I press "print" in Firefox, the preview somewhat compresses/narrows some elements causing the text to take up more lines. Strangely, when using some plugins in Firefox that allows you to edit code in print mode that plugin displays the rendered elements correctly.
Concluding, the problem seems somehow only to occur in print preview (and the actual printing later) but I cannot find a corresponding "error" or mismatch in the code.
I read a couple of articles about dpi, is it possible that the print preview uses a different dpi from my browser because it is trying to imitate/preview a printer (which have a different dpi than screens) ?
check this link link
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
console.log('onbeforeprint equivalent');
} else {
console.log('onafterprint equivalent');
}
});
or
var beforePrint = function() {
//your code
};
var afterPrint = function() {
//your code
};
You can use a print css
<link rel="stylesheet" type="text/css" href="your file css here .css" media="print" />
Problem and source code
I'm trying to create <div>s within another <div> at the click of a button. When the button is clicked, a new inner <div> is created (within the outer <div>) with a unique id. I have this part working but here's where I'm running into an issue: I want each inner <div> to have a random margin-top.
Javascript
function pressButton() {
number += 1;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("innerDiv" + x);
outer.appendChild(innerDiv);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + ";display:inline-block;width:48px;height:48px;background-color:#000;");
};
CSS:
#outer {
position:absolute;
white-space:nowrap;
height:118px;
overflow:auto;
width:100%;
padding:2px;
}
Result (after button is clicked 4 times)
<div id="outer">
<innerDiv1 style="margin-top:15;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv1>
<innerDiv2 style="margin-top:23;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv2>
<innerDiv3 style="margin-top:37;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv3>
<innerDiv4 style="margin-top:0;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv4>
</div>
The result (which I got from inspecting the inner elements in my browser) looks like everything worked - all the margin-tops are random like I wanted. However, the visual result is this:
As you can see, the black inner <div>s all have the same margin-top. What am I doing wrong? How can I make the created <div>s all have random margin-tops?
The CSS spec requires that a length (other than zero) that is missing a unit be treated as an error (and thus ignored). Therefore, add px to the end of your generated margin number, and all should be well.
Live Demo
Description
This happens, because you set the display:inline-block; property. This makes them all to be in one line, so they will allign to the innerDivx that has the highest margin-top.
Delete the display:inline-block; property and give them float:left;. If you want to keep the gap between them, also add margin-left:5px;. And don't forget that margin-top's value needs a unit. I think you wanted to use px.
Also <innerDivx> is not a valid HTML tag. You should change them to a <div> and use innerDivx as an id attribute. Also your tags use almost the same CSS styles so you should put the same ones to a class and add the class instead.
Full solution code
HTML
<button id="button1">Add box</button>
<div id="outer"></div>
JavaScript
var number = 0;
document.getElementById("button1").addEventListener("click", pressButton, false);
function pressButton() {
++number;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(innerDiv);
innerDiv.className += " box";
innerDiv.setAttribute("id", "innerDiv" + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
CSS
#outer {
position: absolute;
white-space: nowrap;
height: 118px;
overflow: auto;
width: 100%;
padding: 2px;
}
.box {
float: left;
width: 48px;
height: 48px;
background-color: #000;
margin-left: 5px;
}
This is likely caused by the position model used for inline-block elements - they're all being vertically-aligned at their bottom line in a row.
I suggest that you simplify this and use position: block with float: left
http://jsfiddle.net/2y5bJ/4/
I also suggest that you stick to standard elements to ensure cross-browser compatibility - don't create your own elements called innerDiv1 etc, but use div elements with unique IDs.
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(div);
innerDiv.setAttribute('id', 'innerDiv' + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
I think there is no tag available with name
<innerDiv1>
This may be the cause.
I am developing a jquery/PhoneGap application. I have been trying hard to get the buttons behave the way I want to. In short I am trying to achieve the following:
I put a set of six Jquery-Mobile buttons (mini, normal or button-group).
The above set needs to be in one horizontal line so I have put them in a div.
The numbers of buttons and its text dynamically changes, so I need a CSS/JS trick that allows me to resize the button size and text based on the div/screen size. When I started with Jquery mobile (two weeks ago), I thought that this will be a basic functionality :) but alas !
Some code that I am trying right now is:
//TO CREATE BUTTONS
for(var button_id=0; button_id < window.g_maxLength/2; button_id++){
var bt_id= "<button class =\"tile\" data-theme=\"e\" data-inline=\"true\" data-mini=\"true\" id =\"button_tid"+button_id+"\";>.</button>";
$("#buttoncontainer1").append($(bt_id));
}
//HTML
<div id="tiled" align="center">
<div data-role="controlgroup" data-type="horizontal" id="buttoncontainer1">
<!-- Button will be added by JS-->
</div>
</div>
//CSS
#tiled {
align:center;
height:23%;
position:absolute;
text-align :center;
padding: 1px;
width:90%;
top:73%;
margin-right:4%;
margin-left:4%;
background-color:#b0e0e6;
border-radius: 10px;
border-width: 3%;
border-style:double;
Right now what I have is works fine on small screen devices, but as soon as I open my app in large screen device the buttons look very small with lot of empty spaces. Any help here will be appreciated !!
PS: Also used media queries - but they somehow do not work on jquery-mobile.
#media (min-width: 500px) {
html { font-size: 120%; }
}
Here's a workaround for auto-adjust width and font-size of buttons.
Demo: http://jsfiddle.net/Palestinian/UYa4Y/
// Number of buttons
var buttons = $('[data- role=controlgroup]').find('a').length;
// Parent div width
var btn_width = $('#tiled').width() / buttons;
// Remove left/right button padding
$('.ui-btn-inner').css({
'padding-left': 1,
'padding-right': 1
});
// Set button new width
$('.ui-btn-inner').width(btn_width - 4);
// Adjust font-size for each button based on text
$('.ui-btn-text').each(function () {
while ($(this).width() > $('.ui-btn-inner').width()) {
var font = parseFloat($(this).css('font-size')) - 1 + "px";
$(this).css('font-size', font);
}
});