Count number of rows inside a div element - javascript

As shown in the image below, I have several div inside a div (outer div). I need to count the number of rows the outer div have. In this example the row count is 5.
Note:The inner div is floated left and its content is created dynamically.
Does anyone has any ideas?

Perhaps something along the lines of:
Demo Fiddle
var minLeft = null, rows = 0;
$('div div').each(function () {
var left = $(this).offset().left;
if (left <= minLeft || minLeft==null) {
rows++;
minLeft=left;
}
});
console.log(rows);

Try with something like this:
var parentX = $('#containerDiv').position().left;
var rows = 0;
$('#containerDiv div').each(function(){
if( $(this).position().left == parentX ){
++rows;
}
});
alert('Num of rows: ' + rows );

Related

Set table columns equal length

How would the css look if I needed to do this. I have a javascript function that gets data and outputs rows. The data matches up (like the first element of row 1 is of the same type as first of row 2, second is same as second etc.)
But sometimes one element of an upper row will be much longer than the corresponding elements, so it doesn't come down like a straight column. How do I fix this?
rowIndex=0;
while(rowIndex<table.length){
present_row = $("#table").append("<div class='row'></div>");
itemIndex= 0;
while(itemIndex<table[rowIndex].length){
present_row.append("<div class='tableItem'>"+ table[rowIndex][itemIndex] +"</div>");
itemIndex+=1;
}
rowIndex+=1
}
}
What this gives me is a set of rows that aren't
Use a real table:
rowIndex=0;
while(rowIndex < table.length) {
present_row = $("#table").append("<tr></tr>");
itemIndex= 0;
while(itemIndex < table[rowIndex].length) {
present_row.append("<td class='tableItem'>"+ table[rowIndex][itemIndex] +"</td>");
itemIndex+=1;
}
rowIndex+=1
}
}
You can use the following to make height of rows equal
$(document).ready(function() {
var nHeight = 0;
$('.tableItem').each(function() {
var defHeight = $(this).height();
nHeight = defHeight < nHeight ? nHeight : defHeight;
});
$('.tableItem').height(nHeight); });
});

JS: split and replace 1 ul into 2 equal ul's

I have a variable in which i search for ul's. I want every ul to split into 2 equal ul's and replace the original ul with these 2 new ul's.
I can't do this with CSS, because i want the li's to display from top to bottom every column, instead of from left to right.
I have the following code, but I am stuck right now...
<script type="text/javascript">
var wid_tekst1 = "<?php echo $wid_tekst1; ?>";
$(wid_tekst1).filter('ul').each(function() {
//Create array of all posts in lists
var postsArr = new Array();
$postsList = $(this);
$(this).find('li').each(function(){
postsArr.push($(this).html());
})
//Split the array at this point. The original array is altered.
var firstList = postsArr.splice(0, Math.round(postsArr.length / 2)),
secondList = postsArr,
ListHTML = '';
function createHTML(list){
ListHTML = '';
for (var i = 0; i < list.length; i++) {
ListHTML += '<li>' + list[i] + '</li>'
};
}
//$(firstList).before('<ul>');
//$(firstList).after('</ul>');
//$(secondList).before('<ul>');
//$(secondList).after('</ul>');
alert(firstList);
alert(secondList);
})
</script>
Thanks for your help...
UPDATE:
I now have the following:
<script type="text/javascript">
$( document ).ready(function() {
var wid_tekst1 = $('.content');
$(wid_tekst1).filter('ul').each(function() {
var $li = $(this).children(),
$newUl = $('<ul>').insertAfter(this),
middle = Math.ceil($li.length / 2) - 1;
$li.filter(':gt(' + middle + ')').appendTo($newUl);
//alert($newUl);
});
});
</script>
It doesn't split the ul's into 2. The only way I got it working was by setting
var wid_tekst1 = "*";
But if I set variable wid_tekst1 to all, it replaces all ul's in the webpage. I only want to replace the ul's within the .content-class
Thank you
Your code can be optimized:
$(wid_tekst1).filter('ul').each(function() {
var $li = $(this).children(),
$newUl = $('<ul>').insertAfter(this),
middle = Math.ceil($li.length / 2) - 1;
$li.filter(':gt(' + middle + ')').appendTo($newUl);
});
Demo: http://jsfiddle.net/R3VYZ/
Messing with innerHTML (when you construct lists using strings) is not ideal, since you will lose all event original handlers if there were something bound.

How would I write a variable to call all margins on all elements on the page with Jquery?

Title pretty much says it all, I duno if this is basic or advanced but I need a variable that will be the sum of all top and bottom margins of every element on the page that has margins. I don't need the left or right ones. Can this be done easily?
Try this:
function sumMargins() {
var total = 0;
$("*").each(function() {
var top = parseInt($(this).css("marginTop"));
var bottom = parseInt($(this).css("marginBottom"));
total += (top + bottom);
});
return total;
}
See this fiddle.
var x = 0;
$('*').each(function() {
x += parseInt($(this).css('margin-top'));
x += parseInt($(this).css('margin-bottom'));
});
alert(x);
Here is a working fiddle:
http://jsfiddle.net/jonigiuro/qQ6sB/
function allMargins() {
var total = 0;
$('.container *').each(function(i) {
var currentTop = parseInt($(this).css('margin-top'));
var currentBottom = parseInt($(this).css('margin-bottom'));
total = total + currentTop + currentBottom;
});
return total;
}
alert('The total of the margins is: ' + allMargins());
I added a .container div to limit the * selector, otherwise it would also include the html and the body tags, which are not consistent about the margin (I had 8 pixels).
The solutions above are faster, but this is more solid.

Shrinking boxes

I am pulling my hair out, trying to solve a simple problem. I know there is some math step here that I am missing and I feel like I am right on the edge of the solution but I just can't get there.
What I am trying to do is write an algorithm to fill an element with squares, and once the element is filled, resize the squares, create a new row and keep filling. Once both new rows are filled, append another row. Basically a line feed type algorithm?
So what I have so far works on the first row, but fails after that as it keeps resizing the unnecessarily.
$(function(){ //DOM Ready
//get columns of even squares
var columns = parseInt($(".grid").width()/$(".grid").height());
var rows = 1;
function checkSize(ico,index){
var grid,gridWidth,gridHeight
var icon,iconWidth,iconHeight
//get our grid info
grid = $(".grid");
gridWidth = grid.width();
gridHeight= grid.height();
//get our icon info
icon = $(ico);
iconWidth = icon.outerWidth();
iconHeight = icon.outerHeight();
//will go over columns?
if(index >= columns){
//do we need another row?
if(Math.floor(gridHeight/iconHeight) === rows){
//add row
rows++;
//reset columns
columns = gridWidth / Math.floor(gridHeight / rows);
//resize boxes
size();
};
}
};
function size(){
var grid,icon,newHeight;
grid = $(".grid");
newHeight = (grid.height()/rows)
$.each(grid.children(".icon"),function(index,value){
icon = $(value);
icon.css("height",newHeight+'px');
icon.css("width",newHeight+'px');
});
}
//fill
var counter = 0;
function fillGrid(){
var icon,grid,r,g,b,a
icon = $('<div class="icon"></div>');
//random color
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
a = 1;
icon.css('background-color','rgba('+r+','+g+','+b+','+a+')')
grid = $(".grid");
grid.append(icon);
size(icon);
checkSize(icon,counter);
counter++;
};
var timeoutID;
function start(){
if(timeoutID){
clearInterval(timeoutID);
timeoutID = undefined;
}else{
timeoutID = window.setInterval(fillGrid, 1000);
}
};
//START THE TIMER
$('#start').on('click',start);
});
See the working example here-
http://jsbin.com/ovewib/7/edit
Any help would be greatly appreciated!
Here's the problem:
//will go over columns?
if (index >= columns) {
This is counting wrong when there is more than one row. Try this instead:
//will go over columns?
if (index >= Math.floor(columns)*rows) {
http://jsfiddle.net/mblase75/zXeHG/

Swap canvas element with another table cells value

I have a 3x3 HTML table with each element storing a separate <canvas> element
There is one cell in the table containing text instead of a <canvas>
When a cell containing an image is clicked and the cell to its right contains text, I'm trying to swap that cell's canvas with the text stored in the neighbouring cell.
With the following code every time I click a cell, the canvas element disappears and only swaps the text, leaving the cell on the right no longer containing text or a <canvas>
I tried accessing the canvas using ("#blankCell").html() but it does not work .. anybody know how to access this content for swapping of values?
I created a simplified jsFiddle for this: http://jsfiddle.net/bobbyrne01/dbMnM/1/
$(function () {
var $tbl = $('<table border="1">').attr('id', 'grid');
var $tbody = $('<tbody>').attr('id', 'tableBody');
var tileCount = 0;
var rowCount = $("#numOfPieces").val();
for (var i = 0; i < rowCount; i++) {
var trow = $("<tr>").attr('id', 'row' + i); // New row
for (var j = 0; j < rowCount; j++) {
$cell.append(canvasArray[tileCount]); // Each data cell contains separate canvas element
$cell.appendTo(trow);
tileCount++;
}
trow.appendTo($tbody);
}
$tbl.append($tbody);
$('table').remove(); // removes previous table if it existed
$('body').append($tbl);
});
$('#grid tr:nth-child(2) td:last').prev().text("empty");
$('#grid tr:nth-child(2) td:last').prev().attr('id', 'blankCell');
Listens for clicks ..
$('body').on('click', '#grid td', function(e) {
var $this = $(this);
if ($(this).closest('td').next("#blankCell").length){
blank = $(this).closest('td').next("#blankCell");
if (blank.length) {
//alert('blank to the right');
$this.before(blank);
}
$(this).attr('id', 'blankCell');
$(this).closest('td').next("#blankCell").attr('id', 'piece');
}
Appreciate any help!
Instead of using canvas elements for swapping, it now only has text.
The goal is if a user selects a cell beside the blankCell I would like to swap that cell with the blankCell, if the user selects a cell not beside blankCell I would like nothing to happen.
Only concerned with left and right detection for now.
Make it simple and just exchange the whole table cells, not their contents or content strings and attributes:
$('#grid').on('click', 'td', function(e) {
var $this = $(this),
blank = $this.next("#blankCell");
if (blank.length) {
//alert('blank to the right');
$this.before(blank);
}
});
OK, some more complicated code for checking the position included:
var empty = $("#empty").get(0);
$('#grid').on('click', 'td', function(e) {
if (!empty || this == empty) return; // abort, abort!
var currow = this.parentNode,
emptyrow = empty.parentNode;
var cx = this.cellIndex,
cy = currow.rowIndex,
ex = empty.cellIndex,
ey = emptyrow.rowIndex;
if (cx==ex && Math.abs(cy-ey)==1 || cy==ey && Math.abs(cx-ex)==1) {
// empty and this are next to each other in the grid
var afterempty = empty.nextSibling,
afterthis = this.nextSibling;
currow.insertBefore(empty, afterthis);
emptyrow.insertBefore(this, afterempty);
}
});
Demo at jsfiddle.net

Categories