Include a proximity button onto the tabs

Currently, I'm diving into learning Bootstrap and one thing I'd like to implement is having an x next to each tab name for easy closing:

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2924243f383f392a3b0b7e65796578">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item" id="tab-li-1">
    <button
      class="nav-link active"
      data-bs-toggle="tab"
      data-bs-target="#tab-1"
      type="button"
    >
      First
      <button
        class="btn-close"
        onclick="
          document.getElementById(`tab-li-1`).remove();
          document.getElementById(`tab-1`).remove();
        "
       ></button>
    </button>
  <li class="nav-item" id="tab-li-2">
    <button
      class="nav-link"
      data-bs-toggle="tab"
      data-bs-target="#tab-2"
      type="button"
     >
     Second
       <button
        class="btn-close"
        onclick="
          document.getElementById(`tab-li-2`).remove();
          document.getElementById(`tab-2`).remove();
        "
       ></button>
     </button>
  </li>
</ul>
<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="tab-1" tabindex="0">Some text here for `First`</div>
  <div class="tab-pane fade" id="tab-2" tabindex="0">More text here for `Second`</div>
</div>

    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adcfc2c2d9ded9dfccdded98839f839e">[email  protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

After some trial and error, I managed to come up with a workaround by nesting another button inside my initial button and then executing:

document.getElementById(tabId).remove();
document.getElementById(tabContentId).remove();

However, I recently discovered that nesting a button within another button is considered invalid. So, I'm reaching out to ask if anyone has suggestions for a better alternative approach?

Answer №1

There is no need to nest buttons for your tabs; a simple div can suffice. To make it accessible, consider adding role="button".

Instead of hardcoding the buttons, use JavaScript to dynamically create close buttons for each tab.

Your script should not only remove the tab itself but also the associated tab-pane:

window.addEventListener('DOMContentLoaded', function() {
  const TABS = document.querySelectorAll('.nav-link');

  //adds clsoe button to all tabs
  TABS.forEach(tab => {
    let closeBtn = document.createElement('button');
    closeBtn.ariaLabel = 'Close Button';
    closeBtn.textContent = 'X';
    closeBtn.addEventListener('click', removeTab); 
    tab.appendChild(closeBtn);
  })
  
  //removes the tab and the tab-pane
  function removeTab() {
    let tabId = this.closest('.nav-link').dataset.bsTarget;
    let tabPaneElement = document.querySelector(tabId);
    let liElement = this.closest('li');
    tabPaneElement.remove();
    liElement.remove();
  }
})
.nav-link {
  &:hover {
    cursor: pointer;
  }
  button {
    margin-left: 1em;
  }
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfada0a0bbbcbbbdaebf8ffae1fde1fc">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item" id="tab-li-1">
    <div class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-1" role="button">First</div>
  </li>
  <li class="nav-item">
    <div class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-2" role="button">Second</div>
  </li>
</ul>
<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="tab-1" tabindex="0">Some text here for `First`</div>
  <div class="tab-pane fade" id="tab-2" tabindex="0">More text here for `Second`</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d0ddddc6c1c6c0d3c2f2879c809c81">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

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

The new data is not being fetched before *ngFor is updating

In the process of developing a "Meeting List" feature that allows users to create new meetings and join existing ones. My technology stack includes: FrontEnd: Angular API: Firebase Cloud Functions DB: Firebase realtime DB To display the list of meeting ...

You can interact with our dropdown menu using the tab key, even when it is

We are looking to make our dropdown tabbable when expanded and non-tabbable when collapsed. We attempted using tabindex="-1" on the content inside the expandable div, but this resulted in it being non-tabbable even when expanded. Any suggestions on how t ...

Updating HTML content dynamically using Node.js without requiring a page refresh

Currently, I am in the process of learning nodejs and I am looking to dynamically change the content within my HTML without having to completely re-render the entire page every time I make a post. Below is the snippet of code I am currently working with: ...

Django does not support CSS styling out of the box

My webpage is rendering HTML correctly, but the CSS styles are not being applied. I am currently in development mode and running the django dev runserver. STATICFILES_DIRS = ("C:/Users/user/site/sitemain/static",) STATIC_ROOT= '' STATIC_URL = ...

Scaling CSS to fit both height and width (Stretch)

My content is contained within an 800x480 pixel box. When the window size changes, I want to achieve the following: Expand/Stretch the container to fill the entire screen Include all elements inside the container and maintain their relative positions I a ...

Tips for enabling the wrap property with autogeneratecolumn set to true

In my grid view, I want to ensure that any text in a column that exceeds the width of the column will either wrap within the column or display on a new line. Below is the code for the grid view: <asp:GridView ID="GridView1" AllowSorting="True" runa ...

Alter the arrow to dynamically point towards the location of the click source

I am currently working on creating a popover dialog that should point to the element triggering its appearance. The goal is for the arrow to align with the middle of the button when clicked. While I am familiar with using CSS to create pointing arrows, th ...

Move the box upwards and change it to grayscale when hovering over the image, then reverse the effect when the hover

As I hover over the image, my goal is to make a gray box appear at the bottom and smoothly slide up. While it slides up, everything it covers should turn grayscale. When I move my mouse away from the image, I want the gray box to slide back down and remove ...

Using Python's Beautiful Soup library to retrieve text from h1 and id tags

I've been attempting to retrieve the text from an HTML id called "itemSummaryPrice," but I'm having trouble figuring it out. html = "" <div id="itemSummaryContainer" class="content"> <div id=&quo ...

Trouble with displaying the NVD3 sample chart

I seem to be missing something simple... I've copied the code for an nvd3 example exactly, but I'm getting a blank page without any error messages. Both the nvd3 and d3 libraries are showing up when I check in the console by typing "nv" or "d3", ...

Trigger the onClick event of an element only if it was not clicked on specific child elements

<div onClick={()=>do_stuff()}> <div classname="div-1"></div> <div classname="div-2"></div> <div classname="div-3"></div> <div classname="div-4"></div> ...

Guide on how to submit an image along with text using AJAX, PHP, and HTML

Hey there! I'm currently working on a project where I need to upload an image with comments added into a database using a combination of PHP, AJAX, and HTML. Let me show you the HTML part first: <form name="form1" enctype="multipart/form-data" ac ...

Achieving Vertical Alignment of Text and Icon in the Same Line Using HTML and CSS

I am struggling to align these icons vertically center with the text. However, there seems to be a slight offset of a few pixels. I have experimented with different solutions, but this is the closest I could get to. Can anyone explain why it's not ali ...

The HTML and CSS code I wrote functions perfectly on Codepen, but for some reason, it appears different when I view it in my Chrome environment

My codepen displays perfectly, but when I run the same code on my local environment it looks off. I can't seem to figure out what is causing the difference, especially since I copied and pasted the exact code. Both the codepen and my environment are u ...

Swap out the svg element with an icon alternative

Transforming Circle Elements into Shopping Cart Icons I am attempting to change the appearance of my SVG circle elements to resemble shopping carts. Is there a method to completely alter the definition of a circle element in svg so that it displays a spec ...

Interact with HTML style attribute using JavaScript

Is there a way to retrieve a specific CSS property from the style attribute of an HTML element, without considering the stylesheet or computed properties? For example: <div style="float:right"></div> function fetchStyleValue(element, propert ...

"Pros and Cons of Using Extended URLs vs Concise URLs in SEO

Currently, I'm developing a website and I find myself uncertain about which link structure would be most beneficial for SEO purposes. Which format is more likely to receive a higher ranking from Google? Should I go with domain.com/users/username or d ...

Dynamic Cell Class Assignment in Ag Grid

My Div's dimensions can change based on user interaction, with the div containing an ag-grid component. Initially, the div/grid loads in a compressed size, so I've applied specific classes (like small font-size, height, padding, etc.) to eliminat ...

Interactive table on click

Seeking assistance with an issue involving a combobox (select) and a dynamic table generated from PHP. The table displays names along with their Firstname, Lastname, and ID (hidden). Upon clicking on a row in the table, I should retrieve the ID of that spe ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...