0

I want to render tab elements on the page. The tabs are inline-blocks, so if there are too many tabs on a single row, the remaining tabs will automatically wrap themselves into a new row. I do not want this. What i want is that if there are too many tabs, an arrow icon is rendered at the end of the tab elements, which makes it possible to cycle between tab groups.

The problem is that the width of the container element which contains all the tabs can change dynamically, the number of tabs can change and also the width of every tab is different.

Would it be possible to make a JavaScript function which tells me that if these tabs were rendered on the container element then how many of them would fit on a single row? Even the width of all the rendered tabs would be useful.

I could use this function to calculate the number of tabs I can render on the page and put the remaining tabs in a different group.

Jarzka
  • 755
  • 7
  • 22
  • Does this help you at all: http://stackoverflow.com/questions/143815/determine-if-an-html-elements-content-overflows ? – Wold Nov 15 '16 at 20:20

2 Answers2

0

Looks like I can insert the tabs in the container, get their sizes and remove them from the DOM before the next render event happens. This way I can calcuate the sizes of the to-be-rendered tabs to put them in groups.

Here is a brief example how it can be done: https://jsfiddle.net/fqkx9krs/

HTML

<!-- Normally the tab list is generated with JSX, but in this simple example we just grab it from here-->
<ul class="tabs-list hidden" id="tabs">
    <li>Tab 1</li>
    <li>This is Tab 2</li>
    <li>And this Tab 3</li>
</ul>


<br>
<br>
<br>

<div class="tabs" id="container"></div>

CSS

.tabs {
  width: 200px;
  background-color: grey;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li {
  display: inline-block;
  background-color: blue;
  padding: 3px;
  color: white;
  border: 1px solid black;
}

.hidden {
 visibility: hidden;
}

JS

function predictElementSizes() {
  var tabs = document.getElementById("tabs");
  var container = document.getElementById("container");

  container.appendChild(tabs);

  var lis = tabs.childNodes;

  lis.forEach(elem => {
    if (elem.getBoundingClientRect) {
        console.log(elem.getBoundingClientRect().width);
    }
  });

  tabs.parentNode.removeChild(tabs);
}

setTimeout(predictElementSizes, 1000);
Jarzka
  • 755
  • 7
  • 22
-1

Maybe this is what you are looking for

carouFredSel plugin

https://github.com/Codeinwp/carouFredSel-jQuery

demo http://www.colemuseum.org/js/

VineetNayak28
  • 367
  • 3
  • 4
  • Actually I'm using Clojure/Reagent and I think it should be possible to do this without any jQuery plugins. If it is possible to do this with vanilla JavaScript I can figure out how to do it on Clojure. – Jarzka Nov 16 '16 at 08:35