How to get css3 multi-column count in Javascript

We're using the new css3 multi-column layout properties to get our text into newspaper columns. Each column gets a fixed width, and the column-count defaults to "auto", which means that the browser decides how many columns there are.

How do we get the actual number of columns as an integer in Javascript?

If we query the css "column-count" (or -moz-column-count) we get either "auto" or a blank as a result.

Answers:

Answer

The secret is to put a small marker at the end of the content. You can programmatically add an empty span:

<span id="mymarker"></span>

then grab the span using a jquery $("#mymarker") and get the "left" property. Divide that number by the width of the columns (adjusted for column-gap), and that will tell you what column this last element is in. Math.ceil() on the value and you have the column count.

Answer

Try this:

$.fn.howMuchCols = function(){
  return Math.round($(this).find(' :last').position().left - $(this).position().left / $(this).outerWidth()) +1;
};

$('.my-stuff-with-columns').howMuchCols();

Code explanation:

This code will create a function 'howMuchCols ' to each jQuery element.

You can't get the width of a element with columns using the conventional way, because his width is used to define each inner column size. To know how many columns the element have inside, you need to get his real width and divide by the columns size, then you will have the column amount.

The way to get the real width is to sum the X offset of the last child element of the columns container with it width, then, subtract it with the sum of the column container X offset.

In the code, I have added the size of one column after make the subtraction and division rather than use the pixel unit before the division (it does not make difference).

The Math.round must be there because not always the container size will be exactly divisible by his inner columns width.

Answer

could you set a class to each column such as class="another-column" and then use Jquery to select the classes and iterate them.

var count = 0;
$('.another-column').each(function(){
    count++;
});

Warning, this is untested. If you could supply with some html/css3 code I could test it on jsfiddle

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.