Forecast the width of an element using JavaScript

Is there a way to display tab elements on a webpage without them automatically wrapping into a new row if there are too many? Instead, I would like an arrow icon to appear at the end of the tabs so users can cycle between tab groups.

The challenge is that the width of the container holding the tabs can change dynamically, the number of tabs can vary, and each tab has a different width.

Could a JavaScript function be created to determine how many tabs could fit on a single row within the container? It would also be helpful to know the total width of all rendered tabs.

By utilizing this function, I could calculate the maximum number of tabs to display on the page and then separate any additional tabs into another group.

Answer №1

It seems like a clever idea to insert the tabs into the container, retrieve their sizes, and then remove them from the DOM before the next render event occurs. This method allows for calculating the sizes of the upcoming tabs to organize them into groups.

For a quick demonstration, here's an example: https://jsfiddle.net/fqkx9krs/

The HTML Structure:

<!-- Usually tab list is generated with JSX, but for this simple demo, we extract 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>

The CSS Styling:

.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;
}

The JavaScript Logic:

function calculateElementSizes() {
  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(calculateElementSizes, 1000);

Answer №2

Perhaps this is the solution you've been seeking

Check out the carouFredSel plugin

Visit the GitHub page here

To see a demo in action, click on this link Demo Page

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing Data on Vuetify Range Slider

My goal is to update the value as the slider position changes. [codepen]https://codepen.io/JakeHenshall/pen/WLezNg <div id="app"> <v-app id="inspire"> <v-card flat color="transparent"> <v-subheader>Tick labels</v-subheade ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

python using selenium to bypass javascript popups

I have a project where I need to visit a specific website and interact with it using the Python selenium module. However, I am encountering a popup (a cookie acceptance form) when trying to access the site with a bot. I must accept this popup in order to p ...

Issue with the message deletion feature in discord.js

I am encountering an issue with the delete function in discord.js. My code is meant to deduct 1 point from a user's balance when an image is deleted from a channel. The problem arises when I try to delete another image that I uploaded - instead of ded ...

Selenium's click() method in Python seems to experience issues when used within a script, but functions properly when used through

While working with python 3 selenium, I encountered an issue when trying to login to the Zomato website. When running a script, the login button was clicked but the dialog box did not open. However, when executing the same statements in the command line or ...

retrieve the most recent file following a $group operation

I am currently utilizing the official MongoDB driver specifically designed for Node.js. This is how my message data is organized. Each post consists of a timestamp, a user ID, and a topic ID. [ { "_id" : ObjectId("5b0abb48b20c1b4b92365145"), "t ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Prevent a JavaScript file from resetting when a user refreshes the page

I'm currently developing a desktop application using node.js and electron. My task involves creating a JavaScript file that manages multiple processes, stores them in a dictionary, and ensures that the dictionary content is retained even without any r ...

The z-index property seems to be malfunctioning when used in conjunction with the relative and absolute positioning

I have created a dropdown menu using pure CSS3, but I am facing an issue with the z-index property. The dropdown list is appearing above the menu when it should be dropping below it. I have spent all day trying to troubleshoot this problem to no avail, so ...

If a second instance is hidden, SVG will appear as a mysterious black box

Two separate div elements each contain an identical SVG graphic. If I hide the first div by setting it to "display: none", the SVG in the second div appears as a gray box. This issue is present in both Firefox and Chrome browsers. Any insights into why ...

Transitioning away from bundled Javascript for local debugging

My current tasks on the gulpfile.js for my frontend app involve a serve task that handles the following: Processing less files Bundling all javascripts into dist/bundle.js Uglifying dist/bundle.js However, this setup made local debugging difficult. To a ...

Always ensure that only one div is visible at a time

I am currently working on a project where I cannot use ng-cloak due to the way the css files are loaded. I have been exploring alternative solutions and have tried a few different approaches. My main goal is to ensure that two icons are never shown at the ...

Issues with the functionality of jQuery event functions

My webpage retrieves content from a database using jQuery and AJAX. There are various processes on the page such as adding new content, editing, and deletion, all of which use AJAX. However, I am experiencing issues with event functions like click and mous ...

Tips on altering the h2 color when hovering using h2:hover:after

I'm attempting to alter the color of my h2 element using h2:hover:after. Can someone guide me on how to achieve this? Here is what I have tried so far. h2 { font-size: 25px; } h2:after { content: ""; display: block; width: 14%; padding-to ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

Can you provide instructions on how to insert a hyperlink onto a background image?

Is it possible to add a hyperlink to this background image without causing it to disappear? Would creating a new class in the stylesheet be the way to go? (I encountered an issue where the image disappeared when trying to call the new class). body{ back ...

Removing data with the click of a button

I have successfully implemented a feature where clicking the "add to my stay" button displays the name and price data. Subsequently, it automatically changes to a remove button when clicked again for another addon. If I press the remove button of the first ...

background image alteration when scrolling

I've been attempting to change the background image on scroll, but I haven't had any luck finding a guide. So, I'm hoping someone here can help me out. I found a video that showcases exactly what I'm trying to accomplish - https://www.y ...