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.
Related
I have a JavaScript function that displays text based on input in a text field. When a value is entered into the text field, my program will check to see if the value is correct. If it is correct, my program displays, "You are correct!" and if it is incorrect, my program displays, "Try again!"
The text field and button are both centered horizontally on the page, but I cannot figure out how to center the "You are correct!" and "Try again!"
I feel like I have tried everything, but obviously I haven't, considering I can't get it to work.
Here is the code for my JavaScript function:
<center><p>Can you remember how many books I listed at the bottom of the page?</p></center>
<center><input id="numb"></center>
<center><button type="button" onclick="myFunction()">Submit</button></center>
<p id="demo"></p>
<div class="jsFunction">
<script>
function myFunction()
{
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than five or greater than five
if (isNaN(x) || x < 5 || x > 5)
{
text = "Try again!";
}
else
{
text = "You are correct!";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</div>
Here is the CSS code for the function:
.jsFunction
{
margin-left: auto;
margin-right: auto;
}
This specific CSS code is only one of many, many attempts I have made at centering the text in the function.
Here is a link to a picture that will show you the problem I am having:
http://i.stack.imgur.com/Hb01j.png
Please help!
Try setting a class on the p tag that contains text-align: center;
Edit
Nesting your script in a div is meaningless as script tags don't get rendered
You can either target #demo in your css (for the text alignment) or add a class align-center that contains the correct style.
I would recommend the latter as the becomes more reusable, whereas you can't reuse an id on the same page
The fact that you are using JavaScript isn't important to this question. I mention it because of the title "How to Center Text in a JavaScript Function" and your attempt to center the actual script element containing your JavaScript code.
You want to center the contents of an element that happens to be controlled by JavaScript, but the answer is CSS-only.
As Ryuu's answer mentions, text-align: center will do the job for (you guessed it) text and other inline-level content.
You should not use the deprecated center tag.
Your attempt to use margins will center something if you apply it to the correct element and the element has a width. That "something" is the element, however, not the contents of the element.
In other words, margin can be used to align the box, not the stuff within the box.
Example 1: centers the element, but the text is still left-aligned.
Example 2: centers the element and its inline-level contents.
.margin-example1 {
width: 200px;
background-color: #ddd;
/* shorthand for margin: 0 auto 0 auto, which is shorthand for specifying each side individually */
margin: 0 auto;
}
.margin-example2 {
width: 200px;
background-color: #aaccee;
margin: 0 auto;
/* we still need this to get the desired behavior */
text-align: center;
}
<div class="margin-example1">Example 1</div>
<div class="margin-example2">Example 2</div>
So how about a text input? Browsers usually style inputs as display:inline-block. This means we can center something inside them (Examples 1 & 2), but to center them within their container we need to change to display:block (Example 3) or because they are inline-like elements themselves, we can set text-align on the parent container (Example 4), see also.
.example1 {
width: 100%;
text-align: center;
}
.example2 {
width: 200px;
text-align: center;
}
.example3 {
display: block;
width: 200px;
text-align: center;
margin: 0 auto;
}
.example4 {
width: 200px;
text-align: center;
}
.example4-parent {
text-align: center;
}
<div>
<input type="text" value="Example 1" class="example1">
</div>
<div>
<input type="text" value="Example 2" class="example2">
</div>
<div>
<input type="text" value="Example 3" class="example3">
</div>
<div class="example4-parent">
<input type="text" value="Example 4" class="example4">
</div>
Layout in CSS can be complicated, but the basics aren't hard.
Note that I have over-simplified my explanation/definitions a bit (you can read all about the formatting model when you are ready).
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();
})
So, I use this Javascript for hide - show effect:
function effect(id) {
var h = document.getElementById(id);
h.style.display = ((h.style.display != 'none') ? 'none' : 'inline');
}
HTML:
<div class="div">
<img src="http://i.imm.io/1jf2j.png"/>
Home
</div>
and CSS:
.div {
background: #000;
}
.div .url {
font-size: 17px;
}
Here you can test (and edit!) the code: http://codepen.io/anon/pen/dhHiw
JSFiddle doesn't work for me.
All is good. Except when you click on image. It's moved 1px above. Should I use another image?
Where is the problem? And possible solutions. Thank you!
You are basically removing the text element. Since the <div class="div"> does not have a set height, it depends on the elements inside it. When the text is not displayed (display=none), the div will resize to only the image.
You can fix this by either setting a height for the div, or by setting visibility=hidden for the text instead of display=none. When making it hidden, it still has the same dimensions, but it's invisible instead.
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;
}
as you can see in the following image, i have a simple form that validates the fields in real time and generates a span that says whether that field is valid or not. problem is, for some reason that span would not extend out of the containing div even though its has position:absolute in its css rule. by the way, the span gets its right position using javascript, that calculates the width of that field (since every field differs in width). any suggestions?
here is the css code:
div.row {
background:url('/img/formBackground.gif') repeat;
margin:0 2px 2px 2px;border-radius:10px 0 10px 0;
position:relative
}
.row span.valid,
.row span.invalid {
line-height:18px;
height:20px;padding:0 22px 0 5px;
display:block;font-size:13px;
border-radius:3px;position:absolute;
z-index:100;top:4px;right:160px
}
here is the html code:
<div class="row">
<label for="email">דואר אלקטרוני: <span class="required">*</span></label>
<div class="divider"></div>
<input type="text" name="email" id="email" style="width:250px" dir="ltr"/>
</div>
here is the javascript code:
email.onchange = function validateEmail() {
span = document.getElementById('span4');
span.style.right = calcDistance(email);
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
el = email.value;
if(el == null || el == '') {span.setAttribute('class','invalid');span.innerHTML = "<span></span>עליך להזין דוא\"ל";return false;}
if(reg.test(el) == false) {span.setAttribute('class','invalid');span.innerHTML = "<span></span>כתובת הדוא\"ל אינה תקינה";return false;}
else {span.setAttribute('class','valid');span.innerHTML = "<span></span>תקין";return true;}
}
function calcDistance(el) {
var spanDistance = 160 + 20;
var targetWidth = el.offsetWidth;
return targetWidth + spanDistance + 'px';
}
This is how I want it to look (the span extends out of the containing div). I was able to get this result only by giving a certain width to the span, which is not a good solution because every message differs in it's width:
Elements with position:relative will "trap" any absolutely positioned child elements. In other words, the absolute element's coordinates are relative to the parent.
http://css-tricks.com/absolute-positioning-inside-relative-positioning/
http://www.quirksmode.org/css/position.html (see "The containing block" section)
While calculating the input widths to create your error message width is clever, this might just be too fragile of a design. You may end up with error messages that are simply too small for the message itself, especially when you consider that you don't truly have 100% control over the user's font size.
There's not enough code here to reproduce the output in your image, but possible solutions or workarounds may include:
Remove position:relative from div.row
Change your design, and move the error message underneath the input instead
After looking into some old posts, I managed to solve the problem by adding white-space:no-wrap; to the span CSS rule.