Creating Bootstrap 5 Tabs with Previous and Next Buttons without the use of jQuery

I would like to implement Prev and Next buttons in bootstrap 5 tabs without relying on jQuery.

I came across this post with a great solution, which I have provided below. However, I am struggling to replicate the same functionality using Javascript only, without jQuery.

Is there anyone who can offer assistance?

$('.btnNext').click(function() {
  const nextTabLinkEl = $('.nav-tabs .active').closest('li').next('li').find('a')[0];
  const nextTab = new bootstrap.Tab(nextTabLinkEl);
  nextTab.show();
});

$('.btnPrevious').click(function() {
  const prevTabLinkEl = $('.nav-tabs .active').closest('li').prev('li').find('a')[0];
  const prevTab = new bootstrap.Tab(prevTabLinkEl);
  prevTab.show();
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab8b5b5aea9aea8bbaa9aeff4eaf4e8">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<!-- Nav tabs -->
<ul class="nav nav-tabs">
  <li class="nav-item">
    <a class="nav-link active" data-bs-toggle="tab" href="#home">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-bs-toggle="tab" href="#menu1">Menu 1</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-bs-toggle="tab" href="#menu2">Menu 2</a>
  </li>
</ul>

<!-- Tab panes -->
<div class="tab-content">
  <div class="tab-pane container active" id="home">
    <h1>Home</h1>
    <a class="btn btn-primary btnNext">Next</a>

  </div>
  <div class="tab-pane container fade" id="menu1">
    <h1>Menu 1</h1>
    <a class="btn btn-primary btnPrevious">Back</a>
    <a class="btn btn-primary btnNext">Next</a>
  </div>
  <div class="tab-pane container fade" id="menu2">
    <h1>Menu 2</h1>
    <a class="btn btn-primary btnPrevious">Back</a>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24464b4b50575056455464110a140a16">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Answer №1

It's important to shift away from relying on jQuery methods and instead translate your logic into plain JavaScript. This will result in a different syntax and overall approach. Make sure to refer to the example at https://www.w3schools.com/howto/howto_js_tabs.asp for guidance.

Don't forget to eliminate the jQuery script tag from the bottom of your HTML file as well.

Answer №2

Here is a sample utilizing only Javascript. There are various approaches to achieve this task, and the following code snippet is just one of them. Hopefully, it proves to be helpful.

const nextBtn = document.querySelectorAll(".btnNext");
const prevBtn = document.querySelectorAll(".btnPrev");

nextBtn.forEach(function(item, index){
    item.addEventListener('click', function(){
      let id = index + 1;
      let tabElement = document.querySelectorAll("#myTab li a")[id];
      var lastTab = new bootstrap.Tab(tabElement);
      lastTab.show();   
    });
});

prevBtn.forEach(function(item, index){
    item.addEventListener('click', function(){
      let id = index;
      let tabElement = document.querySelectorAll("#myTab li a")[id];
      var lastTab = new bootstrap.Tab(tabElement);
      lastTab.show();
    });
});
      <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73111c1c07000701120333465d435d41">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<!-- Nav tabs -->
<ul class="nav nav-pills" id="myTab">
  <li class="nav-item">
    <a class="nav-link active" data-bs-toggle="tab" href="#home">Menu-1</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-bs-toggle="tab" href="#menu1">Menu-2</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-bs-toggle="tab" href="#menu2">Menu-3</a>
  </li>
</ul>

<!-- Tab panes -->
<div class="tab-content" id="myTabContent">
  <div class="tab-pane container active" id="home">
    <h1>Menu-1</h1>
    TEXT A:......
    <hr>
    
    <a class="btn btn-primary btnNext">Next</a>
  </div>
  <div class="tab-pane container fade" id="menu1">
    <h1>Menu-2</h1>
    TEXT B:....
    <hr>
    <a class="btn btn-primary btnPrev">Back</a>
    <a class="btn btn-primary btnNext">Next</a>
  </div>
  <div class="tab-pane container fade" id="menu2">
    <h1>Menu-3</h1>
    TEXT C:....
    <hr>
    <a class="btn btn-primary btnPrev">Back</a>
    <input class="btn btn-info" type="submit" value="Submit">
  </div>
</div>



<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8dad7d7cccbcccad9c8f88d9688968a">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" 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

Incorporating Subtitles into Videos using NodeJS and the FFMpeg Fluent API

I'm having trouble adding subtitles (srt) to a video stream using Node JS and FFMpeg... Here's what I've tried: var command = ffmpeg(file.createReadStream()) .input("C:\\code.srt").videoCodec('copy') .videoCodec(& ...

Enhanced functionality for Thingworx using ThreeJS

I'm currently facing an issue while developing a 3 JS extension for Thingworx, specifically with the renderHtml function when working with a 3 JS canvas (Check out the code). //runtime.ts file renderHtml(): string { let htmlString = '<div ...

Modifying the label focus does not alter the CSS style

I'm struggling with a simple form where I want to highlight the focused labels by changing their background colors. However, the jquery code doesn't seem to be working as expected. Despite no errors showing up in the console, the functionality is ...

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Error in Chart.jsx: Unable to retrieve the length property of an undefined object in the COVID-19 Tracker App

INQUIRY Greetings, I am in need of assistance to identify an error that is perplexing me. The source of this code can be traced back to a tutorial on creating a covid tracker available on YouTube. While attempting to implement the chart feature, I encounte ...

Bootstrap navbar partially collapsed with inner items concealed not at the edges

Many discussions have come up regarding partially collapsing Bootstrap navbars, such as: Item1 Item2 Item3 Item4 Item5 Is it possible to achieve the following collapsed format: Item1 Item2 Item3 =menu= Or: =menu= Item3 Item4 Item5 This method ...

Mixing controllers with the same name in AngularJS from different modules can lead to

Recently, while working on an AngularJS web application with multiple sub-modules, I encountered a situation where two sub-modules had controllers with the same name due to them both having CRUD functionality. Here's a snippet of the code structure: ...

Bordering the limits with Highcharts

Can I enhance the plot area with a border, similar to the black border shown in the image? https://i.sstatic.net/KirsN.png -- UPDATE -- I am encountering some unwanted white space between the plot area and the border. Is it possible to eliminate this wh ...

Retrieving an Angular Application directly from the Server

In order to ensure user authentication from the backend before any other code loads in my Angular app, I need the initial request sent to the backend to check if the user is authenticated. Only once the user has been verified as authenticated can the app b ...

Node.js encountered an SFTP error stating "Error: connect: An existing SFTP connection is already defined."

Working within my node.js application, I have implemented ssh2-sftp-client to upload an image every 5 seconds. The initial upload functions correctly, but upon repeating the process, I encounter an error message: node .\upload.js uploaded screenshot ...

Tips for refreshing the current page with passing a parameter in the URL?

To achieve the functionality of reloading the page whenever different buttons are pressed and sending a String to the same page, I need to take that String on created() and use it to send an HTTP Get into my Database. My current setup looks like this: exp ...

Implementing a document update event using jQuery

On my WordPress site, I am using a responsive lightbox plugin. When an image is clicked, it opens a popup box with the ID fullResImage. Now, I would like to incorporate the Pinch Zoomer function to it. Do I need to bind a function for this, or is there a s ...

What is the best way to connect an HTML file to a controller in Angular.js?

When developing an app module using the MEAN stack with MVC, I created a folder named AppModules. Inside AppModules, there is a folder called search, which contains three subfolders: models, views, and controllers. I've written an HTML file in the vie ...

What is the best way to send data between pages in a React application?

After solving the question, I can confirm that the code lines are correct. By utilizing console log, I verified that all parameters are being passed correctly: I am creating a website to showcase my personal projects, using components across different pag ...

What is the most efficient way to retrieve the largest category_id within a nested object array?

Seeking guidance as a beginner in ReactJS. I am struggling with looping through a nested object array to find the largest category Id. Despite my efforts, I am unable to retrieve the desired result because the largest category ID may not always be locate ...

Preventing page re-rendering with redux when a condition is not met

I am currently working on a page that features a question paper with multiple options and a button to navigate to the next question. import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import React, { useEffec ...

Instructions for setting up a "beta edition" with npm or bower

Is there a way to download Dojo version 1.11.0-pre using npm or bower? I have tried adding the dependency in my package.json file, but npm is unable to locate it. Any suggestions on how to resolve this issue and successfully load Dojo 1.11.0-pre? { " ...

What is causing the component to render three times?

Below is the structure of my component: import { useEffect, useState } from "react"; function Counter() { const [count, setCount] = useState(0); console.log("comp run"); const tick = () => { setCount(count + 1); conso ...

Is there a way to optimize downloading multiple identical images using html, css, jquery, etc.?

My chess board features 64 squares, each with a picture of a board piece on either a light or dark square. To ensure proper formatting, a Clear knight is placed on the board. The design utilizes a div element with a background image (representing light or ...

how can one cycle through this demonstration

Within my code, there is a variable called "data" which holds an array of objects: [{"id_questao":1,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 1","id_formulario":1},{"id_questao":2,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 2","id_formulario":1} ...