Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One possible solution is to use JavaScript to dynamically create and append tabs based on the user's input. Here is an example:

HTML:

<div>
  <input type="text" id="tab-input">
  <button onclick="addTab()">Add Tab</button>
  <div id="tab-container"></div>
</div>

JavaScript:

function addTab() {
  var tabTitle = document.getElementById("tab-input").value;
  var tabContent = "This is the content for the " + tabTitle + " tab.";

  // create tab header
  var tabHeader = document.createElement("button");
  tabHeader.textContent = tabTitle;
  tabHeader.addEventListener("click", function() {
    showTab(tabContent);
  });

  // add tab header to container
  var tabContainer = document.getElementById("tab-container");
  tabContainer.appendChild(tabHeader);

  // show first tab by default
  if (tabContainer.children.length === 1) {
    showTab(tabContent);
  }
}

function showTab(content) {
  var tabContent = document.createElement("div");
  tabContent.textContent = content;

  // remove previous tab content
  var oldContent = document.getElementById("tab-content");
  if (oldContent) {
    oldContent.remove();
  }

  // add new tab content
  var tabContainer = document.getElementById("tab-container");
  tabContainer.appendChild(tabContent);
  tabContent.id = "tab-content";
}

Explanation:

  • The HTML code contains an input field and a button for the user to add tabs, as well as a container div where the tabs will be displayed.
  • The JavaScript code defines two functions: addTab and showTab.
  • When the user clicks the "Add Tab" button, the addTab function is called. It retrieves the input value from the text field, creates a button element for the tab header, adds an event listener to the header that will call the showTab function with the corresponding content, and appends the header to the container. If this is the first tab, it also shows the content by default.
  • When the user clicks a tab header, the showTab function is called with the corresponding content as a parameter. This function creates a new div element for the tab content, removes any previous content element, adds the new content element to the container, and assigns it an id so it can be easily identified and removed later.

Note: This is just one example implementation and may not suit all use cases. There are many other ways to create tabs in HTML and JavaScript, using libraries like Bootstrap or jQuery, or using CSS to hide and show elements based on user interaction.