views:

182

answers:

2

I have an HTML element (let's say a division) that contains a set titles (h2) and paragraphs (p) with other element inside (some links for example, a).

My goal is to cut my HTML element in 2 same size element.

Constrains : paragraphs, titles, and block should not be cut

My idea asbout this was to browse inside the child nodes list and copy childNodes of each paragraphs.

Each time I copy a paragraph, i compute the size in ordre to know if I reached the half size of the division.

Here is some code to explain it:

var elm = document.getElementById('article_colonnes'); // I want to cut this into 2 parts
var paragraphesNumber = paragraphes.length;
var halfSize = elm.innerHTML.length / 2 ;
var col1 = document.getElementById('col1');
var col2 = document.getElementById('col2');
var i=0;
do {
  var node = createNodeFromParagraphe(paragraphes[i]);
  if(node) {
    col1.appendChild(node);
    // update the size of the 1st column by updating inner HTML
    col1String = col1String + paragraphes[i].innerHTML;
  }
  i++;
  // compute the size of the 1st column
  col1Size = col1String.length;
}
while(col1Size < halfSize  || i < paragraphesNumber) ;

And I do the same for the 2nd column.

Thanks for your help.

+2  A: 

If your trying to make an automatic two column layout; take a look at multicolumnlists

Gary Green
A: 

To get a true two column layout, you need the height of the paragraphs (not the characters in it). The problem here: The only way to get the height is to wait for the browser to layout the page unless you specify the width of every element. Otherwise, the user would see an ugly flicker.

So I suggest to try this:

  1. Use a multi column layout which most browser support. If the browser is not IE <= 7, you're done.

  2. For IE 7 and lower, set a fixed width for all elements. Wait for the browser to layout the page (it should be enough to run this code in body.onload or from a script tag at the end of the page). Put all elements into a div with the id "col1".

  3. Use JavaScript to find the element at half the height of the the div "col1". (see here)

  4. If this element is a heading, skip one element.

  5. Move the next element (and all beyond) into the div "col2".

That should give you a longer col1 and a shorter col2.

If moving doesn't work, insert an invisible character after you identified the split point, get col1.innerHtml, split it at the split char and use the resulting two strings as innerHtml for col1 and col2.

If that flickers a lot, try to hide col1 and col2 while your script runs (display='None').

Aaron Digulla