Generate div columns using jquery - javascript

following code on jsfiddle:
<div id="container">
<div class="b">test1</div>
<div class="b">test2</div>
<div class="b">test3</div>
<div class="b">test4</div>
<div class="b">test5</div>
<div class="b">test6</div>
</div>
CSS
.b {
display:inline-block;
position: relative;
margin: 2px;
float:left;
width: calc(16.7% - 10px);
height:400px;
background-color: white;
border: 1px solid black;
}
http://jsfiddle.net/329vcLLc/ does work, it shows 5 columns the way I would like them to be formatted.
I must loop over an array to generate the divs according to the number of elements of the div. I thought I could use the append() function, what do you think? and how can I set the width property for each div (cause it depends on the number of columns)
any ideas?

I don't quite understand what the number of the divs depends on, but if you need to generate some known number of divs you may do this:
var n=8;
var $cont=$('#container');
for(var i=1; i<=n; i++)
{
var d=$('<div>').addClass('b').html('test '+(i)).css('width', 'calc('+(100/n)+'% - 10px)');
$cont.append(d);
}
.b {
display:inline-block;
position: relative;
margin: 2px;
float:left;
height:400px;
background-color: white;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>

According to your provided css you can do something like this:
var divs = ['a','b','c','d','e', 'f', 'g'];
var con_width = parseInt($('#container').width()); //get the width of the container
var width = (con_width / divs.length) - 10; //divide trough the number of divs,
//subtract 10 to make them fit
$.each(divs, function(index, value){
var div = $('<div />').addClass('b').text(value).css('width', width + 'px'); //generate new div
$('#container').append(div); //append it to the container
});
Demo
Reference
.each()
.width()
.css()
.addClass()
.text()

Related

How to display a js variable value in HTML,<div id> with mouseover effect

In javascript I have a variable which contains some value which i get from JSON.
var a =recipe[0].step[1].processingTime;//here processing time is stored in var a
I want to display this value by showing a description box, when I hover my mouse over a small div id in HTML.
<tr>
<td>Recipe 0</td>
<td>
<div id="p1"><div>
</td>
</tr>
How to do that? Can anyone please show me a easy solution.
If you only want the simple native html tooltip you can just set the elements title atrribute. For example the ones that get shown when you hover over the SO voting arrows
document.getElementById("p1").setAttribute("title",recipe[0].step[1].processingTime);
Demo
var text = "13ms";
document.getElementById("p1").setAttribute("title",text);
#p1 {
width:80px;
height:80px;
background:#323232;
}
<div id="p1"></div>
If however you are wanting a fancier one, you can do this with a little javascript and using css :hover, :after, attr css function, and the content property.
Give your div (or whatever element) a css class like below:
.withTooltip:hover:after {
content:attr(data-tooltip);
display:block;
padding:10px;
background:#323232;
border-radius:4px;
border:#000000;
color:#FFFFFF;
}
:hover will cause the style to applied only when the element is
hovered over.
:after will create a pseudo-element
conent you can use to set the text that the pseudo-element will display
attr will take the passed attribute name and get the value of that
attribute
Then use javascript to set the attribute to your saved text (in this case using data-tooltip)
document.querySelector("p1").dataset.tooltip = recipe[0].step[1].processingTime;
//or
document.querySelector("p1").setAttribute("data-tooltip",recipe[0].step[1].processingTime);
Demo
var someData = ["13ms","100ms","8ms","67ms"];
var elements = document.querySelectorAll(".withTooltip");
for(var i=0; i<elements.length; i++){
elements[i].dataset.tooltip = someData[i];
}
.box {
width:50px;
height:50px;
background:#86DDFF;
margin:10px;
position:relative;
display:inline-block;
}
.withTooltip:after {
content:attr(data-tooltip);
display:block;
padding:10px;
position:absolute;
right:-40px;
top:0px;
background:#323232;
border-radius:4px;
border:#000000;
color:#FFFFFF;
opacity:0;
transition:all 0.3s;
z-index:100;
pointer-events:none;
}
.withTooltip:hover:after {
opacity:1;
}
<div class="box withTooltip"></div>
<div class="box withTooltip"></div>
<div class="box withTooltip"></div>
<div class="box withTooltip"></div>
Here's a vanilla javascript version:
var a = "something to show";
function showProcTime(elem) {
elem.addEventListener("mouseout", clearProcTime);
elem.innerHTML = '<div class="popupBox">' + a + '</div>';
elem.style.backgroundColor = "#EFEFEF";
}
function clearProcTime(e) {
var elem = e.target;
elem.removeEventListener("mouseout", clearProcTime);
elem.innerHTML = "";
elem.style.backgroundColor = "#CCCCCC";
}
.popupBox {
display: block;
width: 200px;
height: 20px;
position: absolute;
top: 20px;
left: 20px;
background-color: #EFEFEF;
border: 1px solid;
padding: 10px;
}
<div id="p1" style="background-color:#CCCCCC;display:inline-block;width:200px;height:20px;" onMouseOver='showProcTime(this)'>roll over me
<div>
You could use jQuery:
var a =recipe[0].step[1].processingTime;
$('#p1').mouseenter(function(){
$(this).html(a)
}).mouseout(function(){
$(this).html('');
});
Have you tried jquery hover method? http://www.w3schools.com/jquery/event_hover.asp
and if you are using simple javascript try this: http://www.w3schools.com/jsref/event_onmouseover.asp
I think this is simple:
<html>
<script>
var a = 'the processing time you got from json';
function displayTitle(e){
e.title = a;
}
</script>
<body>
<table border>
<tr>
<td>Recipe 0</td>
<td onMouseOver='displayTitle(this);'>
<div id="p1"><div>
</td>
</table>
</body>

Count children + change CSS

I am trying to dynamically give child A tags an even width based on the number of tags contained in a list. (eg. if 4 A's they will all be 25% width, 3 tags they will be 33%).
I have tried counting the number of children inside the div and dividing 100 by the var number with no success
jQuery
var numChildren = $("div a").size()
$('a').css({ width : 100/numChildren });
CSS
a { width: /*DYNAMIC*/ (all even) }
div {width: 100%; }
HTML
<div>
<a></a>
<a></a>
<a></a>
<a></a>
</div>
You can do it CSS-only, without counting the number of elements:
HTML:
<div class="wrapper">
<a></a>
<a></a>
<a></a>
</div>
CSS:
.wrapper {
display: table;
width: 100%;
height: 50px;
margin: 10px 0;
}
.wrapper > a {
display: table-cell;
border: 1px solid #000;
}
Demo
With your current code, if there are four elements, you are setting this:
width: 25;
I think you want this:
$('a').css({ width : 100/numChildren + '%' });
Try changing the jquery to:
var numChildren = $("div a").length;
$('a').css({ 'width', 100/numChildren + '%' });
HTML
<div>
<a>Test Me</a>
<a>Test Me</a>
<a>Test Me</a>
<a>Test Me</a>
</div>
JAVASCRIPT
var numChildren = $("div a").length;
$('a').css({ width : 100/numChildren+'%' });
alert(100/numChildren);
CSS
div
{
width:300px;
}
a
{
position:relative;
float:left;
background-color:#EEE;
}
JSFIDDLE LINK
I don't think you need to set width in percentage. As you are ultimately going to use javascript to evenly distribute width
HTML:
<div>
<a>One</a>
<a>Two</a>
<a>Three</a>
<a>Four</a>
</div>
Javascript:
var parent = $("div");
var anchors = parent.find('a');
anchors.css({ width : parent.width() / anchors.length });
CSS:
div > a {
background: red;
display: inline-block;
}
Demo
You can use this code :
jsFiddle here
HTML
<div id="content">
<a></a>
<a></a>
<a></a>
<a></a>
</div>
CSS
#content{
width:100px;
height:20px;
background:#888;
}
a{
height:20px;
background:red;
display:block;
float:left;
}
jQuery
$(document).ready(function(){
var numberChild = $("#content a").length;
$("#content a").css("width",(100/numberChild)+"%");
});
Oriol's answer is the correct one, if you don't need to support IE7 and below.
If you need support for these browsers, you can calculate the relative width as others already explained.
But if you know that you will never have more than n children, you can also do:
// assuming that will never have more than 4 children
$('div:has(a)').addClass('one');
$('div:has(a+a)').addClass('two');
$('div:has(a+a+a)').addClass('three');
$('div:has(a+a+a+a)').addClass('four');
and the css
div a { width: 100%; }
div.two a { width: 50%; }
div.three a { width: 33.3%; }
div.four a { width: 25%; }
demo

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.

Creating a Pyramid using CSS and JS

I have a wrapper div and many content blocks. The content block can be of any number.
<div class="wrapper">
<div class="content-block">Something goes here</div>
<div class="content-block">Something goes here</div>
.
.
.
<div class="content-block">Something goes here</div>
</div>
I wish to form a pyramid structure using these content-blocks as it appears below:
Is it possible to achieve pyramid like this? The above image is just an example, there can be more than 10 content-blocks or even less.
Check out this very simple JavaScript/CSS solution:
var objContainer = document.getElementById("container"),
intLevels = 10,
strBlocksHTML = '';
// Using innerHTML is faster than DOM appendChild
for (var i = 0; i < intLevels; i++) {
for (var n = 0; n < i + 1; n++) {
strBlocksHTML += '<div class="buildingBlock"></div>';
}
strBlocksHTML += '<div></div>'; // Line break after each row
}
objContainer.innerHTML = strBlocksHTML;
.buildingBlock {
display: inline-block;
width: 20px;
height: 20px;
margin: 2px 5px;
background-color: #eee;
border: 2px solid #ccc;
}
#container {
text-align: center;
}
<div id="container"></div>
Yes, it is perfectly possible, but hard to write down without more precise requirements. Number of divs would obviously equal number of elements = 10. Length of bottom row = (10/2 - 1) with each next row to top taking one less element, etc. Either use absolute positioning in div style or treat table as matrix and draw with cells. Table solution will be progressively slower with more rows, because all the empty "pixels" and quadratically increasing overhead on recalculating cell sizes and positions in browser.
Hm, not a trivial task. I don't think it is possible to write (finite) CSS for any number of elements. It would need something like this:
#wrapper {
text-align: center;
}
.content-block {
display: inline-block;
width: 5em;
height: 4em;
margin: 0 2.5em;
}
.content-block:nth-child(n*(n+1)/2)::after {
display: block; /* linebreak */
}
Where the nth-child-selector would contain a triangular number, but it must have the form an+b.

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