Make Div Smallest Possible Width - javascript

The Fiddle: http://jsfiddle.net/GosuWhite/sXgAY/
You input numbers separated by any characters and it calculates some summary statistics. The summary statistics are output in area designated for the calculator in this divs:
<div id="solWrap">
<div id="solTitles"></div>
<div id="solStats"></div>
</div>
So You'd basically have something like this:
Sample Variance: 12.212
Population Variace: 12.291
I wanted to essentially center these statistics in the calculator area, but I don't know the width, so I used this:
solWrap.offsetWidth = outputTitles.offsetWidth + outputStats.offsetWidth + "px";
Cool, should work right? It turns out it doesn't and that's because outputStats is HIGHLY greedy and uses more width than it needs, and in fact, it actually uses all the remaining width available.
What can I do? Don't throw Jquery at me. Libraries are nice but I prefer sweet, sweet vanilla.
Edit: This is what I want: http://i.imgur.com/l6l4XD5.jpg
I want that effect, but that was achieved through actually literally setting the width of the solWrap div. Since this calculator is dynamic, I want the width dynamically generated.
New Edit: No one has answered correctly yet.
Here is what is going on:
JavaScript is generating content inside two divs:
Sample Variance: 12.212
Population Variace: 12.291
Div 1 will contain "Sample Variance Populati..."
And the other div will contain the data.
These are inside of the calculator text area which has a width of 400px and are both being displayed as inline-blocks.
The thing is when JavaScript generates this content inside of the divs, it does it corrently for the "sample variance...". It sets the width to the smallest possible value it can have.
But when JavaScript generates the content inside the div for the numbers, it sets the width way bigger than it needs to be and in fact takes up the rest of the area inside the calculator div.
How can I force the div that contains the numbers to be as small as it can?]
SOLUTION: I found a solution. Instead of display: inline-block, I used display: table and set the inner divs to display:table cell and it worked.

Try this:
Live demo
html
<form id="calcForm">
<div id="outercalcTextArea">
<div id="calcTextArea" contenteditable="true">
</div>
</div>
<div id="calcButton"><center><button id="submit" type="submit">Submit</button></center></div>
</form>
css
#outercalcTextArea{
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #C9C9C9;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15) inset, -5px -5px 0 0 #F5F5F6, 5px 5px 0 0 #F5F5F6, 5px 0 0 0 #F5F5F6, 0 5px 0 0 #F5F5F6, 5px -5px 0 0 #F5F5F6, -5px 5px 0 0 #F5F5F6;
border-radius: 2px 2px 2px 2px;
min-width: 400px;
width:auto;
font-size:12px;
height:200px;
white-space:nowrap;
}
#calcTextArea {
width:100%;
height:100%;
padding: 8px;
padding-left:21%;
box-sizing:border-box;
}

html
<div id="solWrap" class='parentDiv'>
....Child divs
css
.parentDiv {
width: 100%;
text-align:center;
}
.chilDiv {
width: 90%;
text-align:left;
margin-left:auto;
margin-right:auto;
}

I apologize if I'm way off here but why can't you use a table?
<table id="stats_table">
<tbody id="stats_table_body">
<tr>
<td class="title">Sample Variance:</td>
<td class="value">12.212</td>
</tr>
<tr>
<td class="title">Population Variace:</td>
<td class="value">12.291</td>
</tr>
</tbody>
</table>
If you need to create though javascript:
var myStats = [{title: 'Sample Variance', value: 12.212},
{title: 'Population Variace', value: 12.291}];
function makeStatsTable(stats){
var table = document.getElementById("stats_table_body");
stats.forEach(function(stat){
var tr = document.createElement("tr");
var title = document.createElement("td");
title.className = "title";
title.textContent = stat.title;
tr.appendChild( title );
var value = document.createElement("td");
value.className = "value";
value.textContent = stat.value;
tr.appendChild( value );
table.appendChild( tr );
});
}
makeStatsTable( myStats );
Here is a jsfiddle: http://jsfiddle.net/xiondark2008/8X7MZ/

Related

Get width of div with javascript [duplicate]

This question already has answers here:
How to find the width of a div using vanilla JavaScript?
(8 answers)
Closed 2 years ago.
Why document.getElementById("mydiv").style.width doesn't return the width of mydiv ? It returns an empty string. Some people suggested using offsetWidth, but it doesn't make sense to me why you can't get it from style.width.
The topic of DOM element dimensions is complicated.
You probably want one of :
offsetWidth
The HTMLElement.offsetWidth read-only property returns the layout
width of an element as an integer.
Typically, offsetWidth is a measurement in pixels of the element's CSS
width, including any borders, padding, and vertical scrollbars (if
rendered). It does not include the width of pseudo-elements such as
::before or ::after.
If the element is hidden (for example, by setting style.display on the
element or one of its ancestors to "none"), then 0 is returned.
clientWidth
The Element.clientWidth property is zero for inline elements and
elements with no CSS; otherwise, it's the inner width of an element in
pixels. It includes padding but excludes borders, margins, and
vertical scrollbars (if present).
When clientWidth is used on the root element (the <html> element), (or
on <body> if the document is in quirks mode), the viewport's width
(excluding any scrollbar) is returned. This is a special case of
clientWidth.
getBoundingClientRect
The Element.getBoundingClientRect() method returns the size of an
element and its position relative to the viewport.
The element's size is equal to its width/height + padding in the case
that the standard box model is being used, or width/height only if
box-sizing: border-box has been set on it.
jQuery hides some of this complexity behind a .width method.
const $ = document.querySelector.bind(document)
const d1 = $('#unstyled')
const d2 = $('#stylesheet')
const d3 = $('#inline')
const details = $('#details')
details.innerHTML = (`
<table>
<tr>
<td><h2>A</h2> offsetWidth: '${d1.offsetWidth}', clientWidth: '${d1.clientWidth}', getBoundingClientRect().width: '${d1.getBoundingClientRect().width}', style.width: '${d1.style.width}'
</td>
</tr>
<tr>
<td><h2>B</h2> offsetWidth: '${d2.offsetWidth}', clientWidth: '${d2.clientWidth}', getBoundingClientRect().width: '${d2.getBoundingClientRect().width}', style.width: '${d2.style.width}'
</td>
</tr>
<tr>
<td><h2>C</h2> offsetWidth: '${d3.offsetWidth}', clientWidth: '${d3.clientWidth}', getBoundingClientRect().width: '${d3.getBoundingClientRect().width}', style.width: '${d3.style.width}'
</td>
</tr>
</table>`)
* {
box-sizing: border-box;
font-family: sans-serif;
font-size: .9rem;
}
#stylesheet {
line-height: 50px;
width: 100px;
height: 50px;
text-align: center;
padding: 5px;
margin: 5px;
border: 5px solid red;
}
div {
display: inline-block;
box-shadow: 0 0 0px 1px silver inset;
}
table {
border: 0px;
}
td {
text-align: left;
padding: 0px;
}
<div id="unstyled">A</div>
<div id="stylesheet">B</div>
<div id="inline" style="width:100px;height:50px;text-align: center;line-height: 50px; padding: 5px; margin: 5px; border: 5px solid red;">C</div>
<section id="details"></section>

How to guarantee an element will have a particular height

Say that I have this element on my page:
<div style="height: 1em;"> </div>
I want to use JavaScript to measure the height of the div to figure out how many px are equivalent to 1em for that element.
So if I did:
document.querySelector('div').getBoundingClientRect()
Then I might get 16.
But what if users can inject arbitrary styles onto this webpage? What if they do something like:
div { border: 1px solid black; }
Then I would get 18, because of the unexpected border applied to all div elements.
To avoid this, I could add a laundry list of styles to the div to remove potential "unexpected styles:"
<div style="border: 0; margin: 0; padding: 0; height: 1em;"> </div>
But is that list of styles comprehensive? If not, what other styles do I need? Or is there a better way to make this calculation?
Set the font-style: 1em !important; on the element, and get the font size in px using Window#getComputedStyle:
var fontSize = window.getComputedStyle(div).fontSize;
console.log(fontSize);
<div id="div" style="font-size: 1em;"></div>
My previous not bullet proof answer:
This fails if the user uses borders and/or paddings which height is greater than 16.
You can use box-sizing: border-box on the element. With this box sizing, the borders and the paddings don't increase the dimensions of the element. The content area is the original width/height minus any paddings and borders.
console.log(div.getBoundingClientRect().height);
div {
padding: 3px;
border: 2px solid black;
}
<div id="div" style="height: 1em; box-sizing: border-box;">

How to put css code in javascript

i want to add a css code in a javascript function, this is the function that I have
function test1() {
document.getElementById("p1").innerHTML = "test";
}
and i want this css code in it
p1 {
text-shadow: 0 1px 0 #ccc,
0 2px 0 #c9c9c9,
0 3px 0 #bbb,
0 4px 0 #b9b9b9,
0 5px 0 #aaa,
0 6px 1px rgba(0,0,0,.1),
0 0 5px rgba(0,0,0,.1),
0 1px 3px rgba(0,0,0,.3),
0 3px 5px rgba(0,0,0,.2),
0 5px 10px rgba(0,0,0,.25),
0 10px 10px rgba(0,0,0,.2),
0 20px 20px rgba(0,0,0,.15);
}
-
Basically, I have a paragraph (p1) and I use javascript because I made a button which onclick="test1()" so when it clicks it it will change the text to the one I put which is "test", but I don't want the whole paragraph to have the shadows, I only want the 'test' to have it, hope I was clear enough!
thank you
Try this,
<p id="p1">
This is a <span>test.</span>
</p>
<button id="button1">Button</button>
From what I understand from your question, you want the function to add a shadow to JUST the word test. In that case using a <span> element might be the easiest way to achieve that. .innerHTML() does not select the text inside the <p> instead it sets the text so you would have been left with an element with just the word 'test' inside.
And the javascript below can be modified to your liking, but the basic concept is there.
var button = document.getElementById("button1");
button.addEventListener("click", function(){
var p = document.getElementById("p1");
var test = p.getElementsByTagName("span")[0];
test.style.textShadow = "5px 5px 1px #ff0000,10px 10px 1px #0000ff";
});
Fiddle: https://jsfiddle.net/0Lhc4tav/
Something like that ?
document.getElementById("p1").style.textShadow = "5px 5px 1px #ff0000,10px 10px 1px #0000ff";
Found here : http://www.w3schools.com/jsref/prop_style_textshadow.asp
It's hard to say, you should really post your HTML as well so we can better understand it. You can also try this if you can use jQuery:
$('.p1').css('text-shadow','0px 5px...etc');
But I agree that you may not need to do this via JS.

html page max-width by knowing the size of inside divs

This is my HTML code
<div class="container">
<div class="menu-vertical">menu-vertical</div>
<div class="mainContent">mainContent</div>
</div>​
This is my CSS
.container {
border: 3px solid #666;
overflow: hidden
}
.menu-vertical {
width: 230px;
float: left;
padding: 10px;
border: 2px solid #f0f
}
.mainContent {
overflow: hidden;
padding: 30px;
border: 2px solid #00f
}​
Now i want to make few div inside mainContent of fixed size lets say 150px however if the mainContent width became, lets say 650px then i'll be having 4 div in a row then again 4 in a row. So 4 div means it will be of 600px, hence i'll be having an extra 50px of space.
Now finally what exactly i want to do is to detect this empty space and making the mainContent max-width to 600px`. Any trick which can do this. Javascript or something.
Here is the solution using jquery:
$(function(){
var outerdiv = $('.mainContent');
var innerdivs = $('.mainContent > div');
var sum =0;
innerdivs.each(function(index){
sum += $(this).width(); //calculate and add the widths of every div
});
//outerdiv.width(sum); //set new width for .maincontent
outerdiv.css("max-width", sum); //you can also set max-width like this.
});
You can check out the jsfiddle for this here: http://jsfiddle.net/jqYK6/
Regards,
Saurabh
https://stackoverflow.com/a/10011466/1182021
Here is the link for the answer... after waiting for long i come up to this.

Auto resize child divs so they equally share width of parent

Let's say I have a parent div with a fixed width of 320px and I want to be able to (or I want my users to be able to) add any amount of child divs to the parent and have them all adjust automatically to share the width of the parent.
I don't want the parent width to change, nor do I want to do this with any sort of scrolling overflow - I just need for the divs inside to fit the width of the parent equally.
For example,
If there is only one child then the width is 100%, if there are two then their width is 50% each etc
How would I go about doing this?
I've approached this many different ways with css, but can't seem to figure it out. I'm assuming this has to be done with some sort of javascript, but I don't know enough to pull it off.
But, If it can be done with just css, that would be great.
Thanks in advance.
(Don't know if you'll need to know this, but the child divs will have no text. They're just blank with background-color and fixed height)
Example code:
CSS
.box {
margin: 10px;
background: white;
border-radius: 6px;
border: 1px solid darken(white, 12%);
-webkit-box-shadow: 0px 1px 4px rgba(50, 50, 50, 0.07);
-moz-box-shadow: 0px 1px 4px rgba(50, 50, 50, 0.07);
box-shadow: 0px 1px 4px rgba(50, 50, 50, 0.07);
float: left;
}
.line {
height: 6px;
opacity: 0.4;
-moz-opacity: 0.4;
filter:alpha(opacity=4);
margin-bottom: -1px;
float: left;
}
HTML
...
<div class="box">
<div class="line"> </div>
</div>
...
#will be able to add any amount of .lines
Use display: table (and table-layout: fixed with fixed width for container if you need equal-width columns) for container and display: table-cell for child elements.
Hope this helps!
<html>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script tye="text/javascript">
function resizeChildren( $div ){
var $children = $div.children(".child"); // Change .line to the appropriate class of the children
var $count = $children.length; // Determine how may children
var $width = $div.width(); // Get width of parent
var $cellwidth = Math.floor( $width / $count ); // Calculate appropriate child width
$children.width( $cellwidth ); // Apply width
}
function addChild( $div, $html ){
$( $html ).prependTo ( $div ); // Add a new child
resizeChildren ( $div ); // Call the resize function
}
$(document).ready( function(){
$("#add").click( function(){ // When <a id="add" is clicked...
addChild( $(".parent"), '<div class="child">Random...</div>' );
return false;
});
});
</script>
<style type="text/css">
.parent {
width: 500px;
border: 1px solid #000;
}
.child {
float: left;
}
</style>
<div class="parent" style="width: 500px;">
<div class="child">Random...</div>
<br clear="all" /></div>
Add DIV
</body>
</html>
Some browsers require also rule font-size:0px to show DIV which height is below 1em, otherwise their height will be 1em.
EDIT
There has came more info while I was writing my answer. If that table lay-out is working, answer to the last comment is above. I removed the part of my answer considering positioning, because I missunderstood your question also.

Categories