css: float blocks to occupy all free space - css

I'm trying to make an "image mosaic" that consists mostly of images of the same size, and some of them the double height.
They all should align neatly like this:
To make automatic generation of those mosaic as easy as possible, I thought floating them would be the best option. Unfortunately, the big block causes the following ones to flow behind it, but not before:
What can I do - apart from manually positioning them - to get the images to the place I want, and still have it easy to automatically create likewise layouts?
The code I'm currently using is :
FIDDLE
HTML :
<div class="frame">
<div id="p11" class="img">1.1</div>
<div id="p12" class="img h2">1.2</div>
<div id="p13" class="img">1.3</div>
<div id="p21" class="img">2.1</div>
<div id="p22" class="img">2.2</div>
</div>
CSS :
.frame {
background-color: blue;
border: 5px solid black;
width: 670px;
}
.img {
width: 200px;
height: 125px;
background-color: white;
border: 1px solid black;
float: left;
margin: 10px;
}
.h2 {
height: 272px;
}

You need to use Javascript to achieve this effect, I had to do that once and I used http://masonry.desandro.com/ -- worked well!

Pure CSS Solution
Tested in Firefox, IE8+ (IE7 looks like it would need to be targeted to add a top margin added to 2.1 because it overlaps 1.1). See fiddle. This assumes .h2 is the middle div (as your example). If left most div it should not need any change. If right most, you would need to expand the negative margin to also include the third div following.
.h2 + div {
float: right;
margin: 10px 14px 10px 0; /*14px I believe also has to do with borders */
}
.h2 + div + div {
margin-left: -434px; /*need to account for borders*/
clear: right;
}

You can use a column layout like this:
http://jsfiddle.net/KKUZL/
I don't know if that will conflict with your automation process though....

I realize this is not a CSS-only solution, but for what it's worth (JSFiddle):
HTML:
<div id='container'></div>
CSS:
html, body {
margin:0px;
padding:0px;
height:100%;
}
body {
background-color:#def;
}
#container {
margin:0px auto;
width:635px;
min-height:100%;
background-color:#fff;
box-shadow:0px 0px 5px #888;
box-sizing:border-box;
overflow:auto;
}
.widget {
float:left;
box-sizing:border-box;
padding:10px 10px 0px 0px;
}
.widget > div{
height:100%;
box-sizing:border-box;
color:#fff;
font-size:3em;
text-align:center;
padding:.5em;
overflow:hidden;
}
.widget > div:hover {
background-color:purple !important;
}
JS:
////////////////////////////////////////
// ASSUMPTIONS
//
var TWO_COLUMN_WIDGET_COUNT = 1;
var ONE_COLUMN_WIDGET_COUNT = 15;
var NUMBER_OF_COLUMNS = 2;
////////////////////////////////////////
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var colorFactory = (function () {
var colors = [
'#CC9A17',
'#9B2C16',
'#1A8B41',
'#D97114',
'#3B9EE6'];
var index = 0;
return function () {
if (index > 4) {
index = 0;
}
return colors[index++];
}
})();
function widgetFactory(columnSpan) {
return {
'height': rand(10, 30) * 10,
'width': 100 * columnSpan / NUMBER_OF_COLUMNS,
'columnSpan': columnSpan,
'color': colorFactory()
}
}
function getWidgets() {
var widgets = [];
for (var i = 0; i < TWO_COLUMN_WIDGET_COUNT; i++) {
widgets.push(widgetFactory(2));
}
for (var i = 0; i < ONE_COLUMN_WIDGET_COUNT; i++) {
widgets.push(widgetFactory(1));
}
return widgets;
}
function getHighestOffset(offsets){
}
function getHighestSlot(offsets, numOfColumns){
}
$(document).ready(function () {
var container = $('#container');
var widgets = getWidgets();
var col1 = Math.floor(container[0].offsetLeft);
var col2 = Math.floor(container[0].clientWidth / 2 + container[0].offsetLeft);
var offsets = {};
offsets[col1] = 0;
offsets[col2] = 0;
var newLine = true;
for (var i = 0; i < widgets.length; i++) {
var w = widgets[i];
var marginTop = 0;
if (offsets[col1] < offsets[col2]) {
marginTop = (offsets[col2] - offsets[col1]) * -1;
}
if(offsets[col1] <= offsets[col2] || w.columnSpan == 2){
newLine = true;
}
var margin = 'margin-top:' + marginTop + 'px;';
var height = 'height:' + w.height + 'px;';
var color = 'background-color:' + colorFactory() + ';';
var width = 'width:' + w.width + '%;';
var padding = newLine ? "padding-left:10px;" : "";
var component = $('<div class="widget" style="' + padding + margin + height + width + '"><div style="' + color + '">' + i + '</div></div>');
component.appendTo(container);
var c = component[0];
var index = 0;
var minOffset = null;
for(var p in offsets){
if(minOffset == null || offsets[p] < minOffset){
minOffset = offsets[p];
}
if(p == Math.floor(c.offsetLeft)){
index = 1;
}
if(index > 0 && index <= w.columnSpan){
offsets[p] = c.offsetTop + c.offsetHeight;
index++;
}
}
newLine = minOffset >= offsets[col1];
}
});

Related

How to get the hovered div position

I want my tooltip to be aligned next to the hovered element. How can I find the position of hovered element such that it works in devices also. I am passing the hovered element event on mouseenter.
I tried setting the ClientX, ClientY or screenX, ScreenY position to top and left but it's not working properly.
Example
As you dont provided any code source I created a sample to show what you can do:
var ul = document.querySelector('ul');
var li = ul.querySelectorAll('li');
var tooltip = document.querySelector('.tooltip');
var removeTooltip;
function onMouseOver(e) {
return function() {
clearTimeout(removeTooltip);
tooltip.innerHTML = e.innerHTML;
var w = window;
var tooltipTopPosition = e.offsetTop + (e.clientHeight / 2) - (tooltip.clientHeight / 2);
var leftPosition = e.offsetLeft + e.offsetWidth + 5;
var toolTipWidth = w.innerWidth - leftPosition - 5;
tooltip.style.top = tooltipTopPosition + 'px';
tooltip.style.left = leftPosition + 'px';
tooltip.style.width = toolTipWidth + 'px';
}
}
function onMouseLeave(e) {
return function() {
clearTimeout(removeTooltip);
removeTooltip = setTimeout(function() {
tooltip.innerHTML = '';
}, 100);
};
}
li.forEach(function(item) {
item.onmouseover = onMouseOver(item);
item.onmouseleave = onMouseLeave(item);
});
.tooltip {
background: rgba(0,0,0,0.9);
color: #ffffff;
position: absolute;
z-index: 1000;
word-break: break-all;
white-space: normal;
}
ul {
width: 200px;
margin: 50px auto 0;
padding: 0;
}
ul li {
list-style-type: none;
background: #ccc;
padding: 5px;
border: 1px dotted;
}
<ul>
<li>Lorem.</li>
<li>Necessitatibus.</li>
<li>Dolorum.</li>
<li>Est.</li>
</ul>
<div class="tooltip"></div>

Set animated html5 canvas as the background without interacting with other elements?

I got the canvas working, I'm having issues trying to position it.
Specifically I want to implement them to the same effect as:
html {
background: url(back.jpg) no-repeat center center fixed;
background-size: cover;
}
for static images. Basically no interaction with other elements, and positioned as low as possible with regards to the stacking context. Additionally, I'd like to have the canvas background as compartmentalized / as segmented as possible from the rest of the code.
By segmented, I mean something like this:
<body>
<div id="backgroundContainer">
<canvas id="myCanvas"></canvas>
</div>
<div id="everythingElseContainer">
....
</div>
<script src="canvasAnimation.js"></script>
</body>
or this:
<body>
<div id="container">
<canvas id="myCanvas"></canvas>
<div id="everythingElse">
....
</div>
</div>
<script src="canvasAnimation.js"></script>
</body>
to minimize the possibility of css conflicts.
var WIDTH;
var HEIGHT;
var canvas;
var con;
var g;
var pxs = new Array();
var rint = 60;
$(document).ready(function(){
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
canvas = document.getElementById('canvas');
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con = canvas.getContext('2d');
for(var i = 0; i < 100; i++) {
pxs[i] = new Circle();
pxs[i].reset();
}
setInterval(draw,rint);
});
function draw() {
con.clearRect(0,0,WIDTH,HEIGHT);
for(var i = 0; i < pxs.length; i++) {
pxs[i].fade();
pxs[i].move();
pxs[i].draw();
}
}
function Circle() {
this.s = {ttl:8000, xmax:5, ymax:2, rmax:10, rt:1, xdef:960, ydef:540, xdrift:4, ydrift: 4, random:true, blink:true};
this.reset = function() {
this.x = (this.s.random ? WIDTH*Math.random() : this.s.xdef);
this.y = (this.s.random ? HEIGHT*Math.random() : this.s.ydef);
this.r = ((this.s.rmax-1)*Math.random()) + 1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
this.hl = (this.s.ttl/rint)*(this.r/this.s.rmax);
this.rt = Math.random()*this.hl;
this.s.rt = Math.random()+1;
this.stop = Math.random()*.2+.4;
this.s.xdrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
this.s.ydrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
}
this.fade = function() {
this.rt += this.s.rt;
}
this.draw = function() {
if(this.s.blink && (this.rt <= 0 || this.rt >= this.hl)) this.s.rt = this.s.rt*-1;
else if(this.rt >= this.hl) this.reset();
var newo = 1-(this.rt/this.hl);
con.beginPath();
con.arc(this.x,this.y,this.r,0,Math.PI*2,true);
con.closePath();
var cr = this.r*newo;
g = con.createRadialGradient(this.x,this.y,0,this.x,this.y,(cr <= 0 ? 1 : cr));
g.addColorStop(0.0, 'rgba(255,255,255,'+newo+')');
g.addColorStop(this.stop, 'rgba(77,101,181,'+(newo*.6)+')');
g.addColorStop(1.0, 'rgba(77,101,181,0)');
con.fillStyle = g;
con.fill();
}
this.move = function() {
this.x += (this.rt/this.hl)*this.dx;
this.y += (this.rt/this.hl)*this.dy;
if(this.x > WIDTH || this.x < 0) this.dx *= -1;
if(this.y > HEIGHT || this.y < 0) this.dy *= -1;
}
this.getX = function() { return this.x; }
this.getY = function() { return this.y; }
}
html, body, div, button, canvas, .containr {
padding: 0;
border: none;
margin: 0;
}
html, body, .containr{
height: 100%;
width: 100%;
background: none;
}
html, body {
font-size: 13px;
text-decoration: none;
font-family: Verdana, Geneva, sans-serif !important;
}
button {
transition: all 0.24s ease;
}
h1 {
font-size: 4rem;
}
button {
font-size: 5.6rem;
}
#pixie {
position:fixed;
z-index: 0;
background: black;
}
.containr>div {
background: blue;
}
.containr {
overflow:hidden;
color: #ffffff;
z-index: 9;
font-size: 256%;
white-space: nowrap;
display: flex;
flex-flow: column nowrap;
justify-content: space-around;
align-items: center;
align-content: center;
}
.btnz {
margin-left: 2.4%;
margin-right: 2.4%;
background: #ffffff;
background: rgba(0, 0, 0, .36);
text-shadow: 1px 1px 3px #000;
padding: 2rem;
}
.btnz:hover {
background: #3cb0fd;
text-shadow: none;
text-decoration: none;
}
/* Outline Out */
.hvr {
display: inline-block;
vertical-align: middle;
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
position: relative;
}
.hvr:before {
content: '';
position: absolute;
border: #e1e1e1 solid 5px;
top: -4px;
right: -4px;
bottom: -4px;
left: -4px;
-webkit-transition-duration: 0.3s;
transition-duration: 0.3s;
-webkit-transition-property: top, right, bottom, left;
transition-property: top, right, bottom, left;
}
.hvr:hover:before, .hvr:focus:before, .hvr:active:before {
top: -18px;
right: -18px;
bottom: -18px;
left: -18px;
border: #ffffff solid 8px;
}
<!doctype html>
<html lang="en">
<head datetime="2015-10-31">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="containr">
<canvas id="canvas"></canvas>
<div>
<h1>Main Title</h1>
</div>
<div>
<button class="btnz hvr">
Button Butt
</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js.js"></script>
</body>
</html>
To move objects down in the visual order use the CSS styling z-index smaller numbers move the element down under other elements, higher numbers bring it up.See MDN z-index for more info.
To set the background of an element to a canvas use
element.style.background= "url(" + canvas.toDataURL() + ")";
To isolate of compartmentalize some code the easiest way is to wrap it in a anonymous function and call it. Everything inside it is isolated. Use 'use strict' directive to ensure you do not accidentally create global scoped variables.
A normal anonymous function does nothing and can not be used.
function(){ console.log(42); }; // does nothing
But if you wrap it in () and then add the function call tokens to the end ( ) you can call it like any function.
(function(){ console.log(42); })(); // send the meaning of life,
// the universe, and everything
// to the console.
The function below wraps up a and nothing can get access to a outside the anonymous function.
(function(){
var a = 1;
})();
But you can easily forget to put var in front of a variable making the variable visible to the entire page.
(function(){
var a = 1;
outThere = 2; // Oh no this is has been placed in
// global scope because it is missing
// the var token.
})();
To stop this use the 'use strict' directive.
(function(){
"use strict"; // this must be the very first line of the function
var a = 1;
outThere = 2; // this will cause the javascript to throw a
// ReferenceError: outThere is not defined
})();
It throws an error and stop the function from running but at least you will know that you have a leak.
Everything inside the anonymous function will manage itself. Deleting itself when not needed any more. Or remaining in memory if the Javascript engine holds an internal reference.
The next function starts up and calls its own function doSomething then exits and is deleted completely including the big array.
(function(){
var bigArray = new Array(100000000);
function doSomething(){
console.log("Whats up?");
}
doSomething();
})();
The next one will create a big array and hold that array in memory for 10 seconds (lifeTime). This is because the setTimeout has given the javascript engine an internal reference to doSomething. As long as that reference exists the bigArray will remain (because of closure). After the timeout the reference his no longer need and thus disposed causing all associated referances to go as well and thus disappear. All done via the magic of garbage collection.
Info on Clouser
Info on Garbage collection MDN is out of date but I am sure a quick search on StackOverflow will help.
(function(){
var bigArray = new Array(100000000);
function doSomething(){
console.log("Big Array has had its time.");
}
setTimeout(doSomething,10000);
})();
Attaching an object to items outside the anonymous function scope will expose data in that object to the global scope.
The next function adds a property to a DOM element. This is visible to the global scope and also means that the lifetime of the function will be as long as that element exists.
(function(){
function Info(){
... create info ..
}
var element = document.getElementById("thisOutsideWorld");
var importantPrivateInfo = new Info();
element.keepThis = importantPrivateInfo;
})();
But this does not apply to primitive types as they are copied not referenced. These are Numbers, Strings, Booleans , Undefined, Null...
So to set the background to a canvas via a compartmentalized function see the following function
(function(){
'use strict';
var myCanvas = document.createElement("canvas");
myCanvas .width = 1024;
myCanvas .height =1024;
var ctx = canvas.getContext("2d");
// toDo
// draw the stuff you want.
var el = document.getElementById("myElement");
if(el !== null){
el.style.background = "url("+canvas.toDataURL()+")";
}
// all done
})(); // once run it will delete the canvas and ctx and leave only the copied dataURL
You may think that this exposes the canvas. But it is safe as the canvas is converted to a string and strings are copied not referenced.
If you need to keep the canvas for some period then use a timer to create an internal reference to the anonymous function
The following function will create a canvas and update it every second for 100 seconds. After that it will be deleted and completely gone.
(function(){
'use strict';
var myCanvas = document.createElement("canvas");
myCanvas .width = 1024;
myCanvas .height =1024;
var lifeCounter = 0;
var ctx = canvas.getContext("2d");
// toDo
// draw the stuff you want.
var el = document.getElementById("myElement");
function update(){
// draw stuff on the canvas
if(el !== null){
el.style.background = "url("+canvas.toDataURL()+")";
}
lifeCounter += 1;
if(lifeCounter < 100){
setTimeout(update,1000);
}
}
update(); //start the updates
// all done
})();
Hope this helps.

Dynamic Text with surrounding line, whose container has a background image

I need to implement something like this..
-------------------------
| |
| |
|---- dynamic text --- |
| |
-------------------------
I want the line surrounding the "dynamic text" in css.
I tried using &::before and &::after css, but still when the dynamic text changes i need to stretch/decrease that one. Any ideas?
You could use JavaScript to set the width of :before and :after :pseudo-elements dynamically.
function foo() {
var ss = document.styleSheets;
var text = document.getElementById('text');
var box = document.getElementById('box');
var totalWidth = getComputedStyle(box).width.slice(0, -2);
var textWidth = text.offsetWidth;
var lineWidth;
var margin = 4; // Set the margin between text and line.
for (i = 0; i < ss.length; i++) {
var rules = ss[i];
for (j = 0; j < rules.cssRules.length; j++) {
var r = rules.cssRules[j];
if (r.selectorText == "#text:before") {
// If you want the margin to be set on both sides of the line,
// replace 'margin' with '(margin * 2)' in the next line.
lineWidth = ((totalWidth / 2) - (textWidth / 2) - margin);
r.style.width = lineWidth + 'px';
r.style.left = -(lineWidth + margin) + 'px';
} else if (r.selectorText == "#text:after") {
r.style.width = lineWidth + 'px';
r.style.right = -(lineWidth + margin) + 'px';
}
}
}
}
foo();
#box {
width: 300px;
height: 200px;
background-color: #FF0000;
line-height: 200px;
text-align: center;
}
#text {
position: relative;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 10px;
padding: 4px;
color: white;
}
#text:before {
content: "";
position: absolute;
border-bottom: 1px solid black;
height: 100px;
}
#text:after {
content: "";
position: absolute;
border-bottom: 1px solid black;
height: 100px;
}
<div id="box"><span id="text">This is the text which is dynamic</span>
</div>
<div id="divWithBackground">
<div id="divActsAsLine">
<span id="DynamicText">Your text here </span>
</div>
</div>
Now the CSS
#divActsAsLine{
border-botton:1px solid #00;
text-align:center;
}
#DynamicText{
position:relative;
background-color: #fff;
margin-bottom:-20px /*Adjust this based on your requirements*/
z-index:1 /* optional */
}
The logic is to make a div margin as background line and make the span overlap this line, to do this we need to either decrease or increase margin property. you might need to use z-index if necessary

Dynamic Div Layout

I know there are a lot of posts about div layouts but what I'm looking to do doesn't seem to be on here. I am creating div's that contain dynamic text. Therefore each div is of variable length. I want these div's placed alongside each other, 4 across the page. In other words, each div occupies 25% of the width. The number of div's is variable as well so if there are more than 4 div's, then the remaining would start be placed below in the same fashion. Below is a picture of what I am trying to depict, with the gray boxes being the div's I am creating. Any help is appreciated, thank you in advance!
The div's are created in my function addSuggestion(), which is as follows:
HTML:
addSuggestion = function (counter, company_name, contact_name, street_address_1, street_address_2, phone_number, email_address) {
var output = document.getElementById('container');
var div = document.createElement('div');
var company = document.createElement('p');
company.className = "companyClass";
var contact = document.createElement('p');
contact.className = "otherClass";
var address1 = document.createElement('p');
address1.className = "addressClass";
var address2 = document.createElement('p');
address2.className = "addressClass";
var phone = document.createElement('p');
phone.className = "otherClass";
var email = document.createElement('p');
email.className = "otherClass";
if(counter%4 == 0) {
div.className = "farleft";
}
else if(counter%4 == 1) {
div.className = "centerleft";
}
else if(counter%4 == 2) {
div.className = "centerright";
}
else {
div.className = "farright";
}
if(company_name) {
company.textContent = company_name;
div.appendChild(company);
}
else {
company.textContent = "*** COMPANY INFO ***";
div.appendChild(company);
}
if(contact_name) {
contact.textContent = contact_name;
div.appendChild(contact);
}
if(street_address_1) {
address1.textContent = street_address_1;
div.appendChild(address1);
}
if(street_address_2) {
address2.textContent = street_address_2;
div.appendChild(address2);
}
if(phone_number) {
phone.textContent = phone_number;
div.appendChild(phone);
}
if(email_address) {
email.textContent = email_address;
div.appendChild(email);
}
output.appendChild(div);
}
CSS:
#container {
width: 100%;
}
#farleft {
width: 25%;
position: absolute;
float:left;
}
#centerleft {
width: 25%;
position: relative;
float:left;
}
#centerright {
width: 25%;
position: relative;
float:right;
}
#farright {
width: 25%;
position: relative;
float:right;
}
Assigning width: 25% to each div will get your 4 divs on the same row (counting there are no borders and/or margin/padding on the exterior).
float: left will keep them to the left. In order to get your 'new row' to drop down a line, <br clear="both"> would do the trick:
JSFiddle
If its a row of div's you can store them in a containing div "row" that has a variable height.
Sorry of that doesn't make much sense but try this CSS on the row's div.
min-height: 100px; /*whatever you want the minimum height to be*/
height:auto !important; /*An IE fix for older versions */
height:100%;
The above css will ensure your div is never smaller than 100px but can grow based on its content.
The solution is quite simple:
#container>div {
width:25%;
margin:0;
border:0;
float:left;
}
#container>div.farleft {
clear:both;
}
jsfiddle

IE: nth-child() using odd/even isn't working

My table (that works perfectly on Chrome, FireFox and Opera) is not displaying correctly on Internet Explorer.
The background remains white! (I am using IE-8)
CSS code:
/*My Table*/
.my_table{
border-collapse:collapse;
font:normal 14px sans-serif,tahoma,arial,verdana;
margin:5px 0;
}
.my_table th{
color:#fff;
background:#5E738A;
border:1px solid #3C5169;
text-align:center;
padding:4px 10px;
}
.my_table td{
color:#555;
border:1px solid #C1CAD4;
text-align:center;
padding:2px 5px;
}
.my_table tr:nth-child(even){
background:#E6EDF5;
}
.my_table tr:nth-child(odd){
background:#F0F5FA;
}
As a good workaround, jQuery has added this to their project and achieving this using JavaScript is acceptable:
For my CSS, I would have
.my_table tr.even{
background:#E6EDF5;
}
.my_table tr.odd{
background:#F0F5FA;
}
And I would use jQuery to do this:
$(document).ready(function() {
$(".my_table tr:nth-child(even)").addClass("even");
$(".my_table tr:nth-child(odd)").addClass("odd");
});
IE8 doesn't support the nth-child selector I'm afraid:
http://reference.sitepoint.com/css/pseudoclass-nthchild
You can use first-child and "+" to emulate nth-child, example:
tr > td:first-child + td + td + td + td + td + td + td + td {
background-color: red;
}
That select the 9th column, just like nth-child(9), and that works on IE
This is the Dojo version, it works fine:
dojo.addOnLoad(function(){
dojo.query("table tr:nth-child(odd)").addClass("odd");
dojo.query("table tr:nth-child(even)").addClass("even");
});
I made some time ago, a prude simple javascript solution for this problem:
https://gist.github.com/yckart/5652296
var nthChild = function (elem, num) {
var len = elem.length;
var ret = [];
var i = 0;
// :nth-child(num)
if (!isNaN(Number(num))) {
for (i = 0; i < len; i++) {
if (i === num - 1) return elem[i];
}
}
// :nth-child(numn+num)
if (num.indexOf('+') > 0) {
var parts = num.match(/\w/g);
for (i = parts[2] - 1; i < len; i += parts[0] << 0) {
if (elem[i]) ret.push(elem[i]);
}
}
// :nth-child(odd)
if (num === 'odd') {
for (i = 0; i < len; i += 2) {
ret.push(elem[i]);
}
}
// :nth-child(even)
if (num === 'even') {
for (i = 1; i < len; i += 2) {
ret.push(elem[i]);
}
}
return ret;
};
The usage is quite simple and similar to the css-selector:
var rows = document.querySelectorAll('li');
var num = nthChild(rows, 2);
var formula = nthChild(rows, '3n+1');
var even = nthChild(rows, 'even');
var odd = nthChild(rows, 'odd');
// Note, forEach needs to be polyfilled for oldIE
even.forEach(function (li) {
li.className += ' even';
});
odd.forEach(function (li) {
li.className += 'odd';
});
formula.forEach(function (li) {
li.className += ' formula';
});
num.style.backgroundColor = 'black';
http://jsfiddle.net/ARTsinn/s3KLz/

Resources