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).
Related
I have a <div> with checkbox and button inside and wanna put field between them, but the field is always leftmost. I tried to use text instead of filed and that worked, but filed doesn't want to obey to my CSS rules.
Also, I need to position all of those using JavaScript.
var list = document.getElementById("list");
var item = document.createElement("div");
item.className="item";
list.appendChild(item);
var itemsField = document.createElement("input");
itemsField.setAttribute('type', 'input');
itemsField.className = '.itemsField';
item.appendChild(itemsField);
var taken = document.createElement("input");
...
item.appendChild(taken);
...
item.appendChild(del);
Some CSS rules:
.itemsField {
display: inline-block;
float:center;
margin-left:1%;
}
checkbox {
display: inline-block;
float:left;
width:auto;
}
I think the reason why the css classes don't obey the rules is due to your script. So try changing
itemsField.className = '.itemsField';
to
itemsField.className = 'itemsField';
Besides, I don't think that there is a "center" value for the "float" property ...
.itemsField {
display: inline-block;
float:center;
margin-left:1%;
}
If you want to center something, use text-align : center instead. Hope this help.
You can use string literals. The other issue is the use of class name as .itemsField, you need to remove the dot. In your code you are appending the div with innerText X at the last
var list = document.getElementById("list");
let innerDOM = `<div>
<input type = 'input' class ='itemsField'><span>X</span><input type ='checkbox' name ='taken'>
</div>`;
list.innerHTML = innerDOM;
.itemsField {
display: inline-block;
float: center;
margin-left: 1%;
}
checkbox {
display: inline-block;
float: left;
width: auto;
}
<div id='list'></div>
float: center doesn't exist.
Above answers are pretty clear.
But if you need a very simple answer, use this.
<center>
<input type="checkbox"> <input type="textarea"> <input type="submit" value="Submit"><br>
</center>
if you want to move the whole thing into a specific position or style, use tag.
In Qualtrics, I am trying to create something like this:
https://dl.dropboxusercontent.com/u/8114735/Screen%20Shot%202015-05-12%20at%2017.49.17.png
The only way to have text boxes both next to and on top of each other is by using a matrix table with text entry. However, this only gives you the text boxes, without a space above the text entry box to insert an image. So I'm now trying to append these images using javascript. The ID of the text boxes is in the format of QR~QID17~3~2~TEXT (for the box on row 3, column 2).
Here is a sample I made of the text boxes in a 3x3 matrix.
https://eu.qualtrics.com/WRQualtricsSurveyEngine/?SID=SV_b30tGcjTmJWTlYN&SVID=&Preview=Block&ID=BL_enEP0YjUHaK5yPX&Q_DONT_SAVE=1
Does anyone know how you can append an image on top of these boxes? Thanks.
I will start with a working example:
Working Example
This uses numbers, in place of images, but is still a valid example.
First, you will select the "Position text above" option, and in the rows of text you will place the following code:
<td class="c4">1</td><td class="c5">2</td><td class="c6 last">3</td>
replacing 1,2,and 3 with the images for that row(you will have to use an image tag to get this to work in a friendly way).
Once you have setup all three of your rows, add the following to the question javascript:
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place Your Javascript Below This Line*/
$$('.c1').each(
function (e) {
e.remove();
}
);
});
This hides a placeholder inserted by qualtrics and allows your rows to line up nicely!
Enjoy! Note though that this will likely require the images to be sized properly(I havent tested images)
How about using DIV container?
HTML
<div class="container">
<div class="box">
<div class="box-image">
<img src="http://lorempixel.com/output/city-h-c-150-230-4.jpg" />
</div>
<div class="box-input">
<input type="text" />
</div>
</div>
</div>
CSS
.box {
float: left;
width: 200px;
margin: 5px;
}
.container {
max-width:420px;
background:#CCCCCC;
overflow: hidden;
}
.box-image, .box-input {
text-align: center;
width: 100%;
}
.box-image {
background: #FFFFFF;
}
.box-input input{
margin-top: 2px;
width: 200px;
border: 1px solid #AAAAAA;
}
FIDDLE
I have a problem where I will be displaying a variable number of items displayed, and they will have a margin setting which is updated uniformly over the set.
So basically to put it simple if I have a set that is [1,2,3,4,5] it might be something like:
1 2 3 4 5
while if the number of number were to double they would require the same amount of space:
1 2 3 4 5 6 7 8 9 10
I have some solutions for this but what hit me was that if I have an css-class (as the margin is uniform over the given set) I could share the layout. So I would have liked it if it were possible to update the class dynamically if that makes sense I haven't found any information of that being possible to do, so if we assume that in the first example the margin is something like margin-right: 10px; then if I could change the class, (similar to how I set style on an element I guess is how I am thinking, but for the whole class), it would be really smooth. So let's assume a functionality to do this I could have a class:
.myclass {
margin-right: 10px;
}
and through our magic function .myclass.setProperty('margin-right', '5px'); (or whatever the syntax would be :P). It would act as if i had defined the class:
.myclass {
margin-right: 5px;
}
I hope that is enough to grasp my ideas and problem thus far. The way I am going about it at the moment is that I use a class for all shared behavior and set style for each element. However this is a bit tedious as it become something like:
for (var i in mynumbers) {
mynumbers.style.marginRight = new_margin;
}
Where new_margin is calculated based on a scale (i.e. it could change many times in a short period of time).
So to the question-part. Is there perhaps a way to achieve something like the first part (a way to dynamically change a class), or any thoughts or ideas how to implement it if the way I am doing it feels like a bad idea or if you feel there are better ways of handling this.
Thanks for reading and hope you find the problem interesting.
Ah, just another typical use case of flex layout:
.container {
display: flex;
border: 1px solid;
justify-content: space-between;
}
<h2>5 elements in a line with equal width gaps</h2>
<div class="container">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>
<h2>10 elements in a line with equal width gaps</h2>
<div class="container">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>
If your browser supports the feature, you would see something like this:
Here for browser compatibility.
EDIT: another interesting use case, although OP didn't ask about:
.container {
display: flex;
border: 1px solid;
justify-content: space-between;
}
.container:before, .container:after {
content: '';
width: 0;
}
<h2>5 elements in a line with equal width gaps</h2>
<div class="container">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>
<h2>10 elements in a line with equal width gaps</h2>
<div class="container">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>
If your browser supports the feature, you would see something like this:
Space is divided equally not only between elements, but also include both ends of the container. And you could see how simple the code is!
This sounds like a job for table-layout: fixed. Your browser computes the width of each "column" (element) in the first "table-row" based on the number of columns in the "table".
.table {
display: table;
table-layout: fixed;
width: 100%;
}
.table > span {
display: table-cell;
text-align: center;
}
<div class="table">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
</div>
<div class="table">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>
Yes. This is possible. One thing to be aware of is that changing a class's property may cause the browser's renderer to recalculate the entire page's layout (it needs to figure out how your class change affects the overall layout). So if you plan on changing your margin-right in a way to animate the change, it's not going to perform very well depending on the complexity of your page. That said, here is a quick and dirty implementation that should work on everything IE9+:
<html>
<head>
<style>
.thing {
display: inline-block;
width: 20px;
height: 20px;
background: #f00;
}
</style>
</head>
<body>
<div>
<div class="thing myClass"></div>
<div class="thing myClass"></div>
<div class="thing myClass"></div>
<div class="thing myClass"></div>
<div class="thing myClass"></div>
<div class="thing myClass"></div>
</div>
<div>
<button id="doit">Make bigger</button>
</div>
</body>
<script>
var styleTag = document.createElement("style"),
styleSheet, index, cssRule, style;
// Create a <style> tag that will hold our CSS rule
document.head.appendChild(styleTag);
styleSheet = styleTag.sheet;
// Insert an empty .myClass rule into the style sheet
index = styleSheet.insertRule(".myClass {}", styleSheet.cssRules.length);
// Get the 'style' object from the rule. This is nearly identical to elem.style
cssRule = styleSheet.cssRules[index];
style = cssRule.style;
// Sets .myClass { margin-right: 5px; }
style.marginRight = "5px";
// Demo to show that it works when you click a button
document.querySelector("#doit").addEventListener("click", function() {
style.marginRight = "20px";
});
</script>
</html>
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.
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;
}