Creating Bootstrap carousel indicators within a navbar can enhance the user experience and navigation of

I have a well-functioning carousel that slides perfectly between each image, but I am looking to highlight the active item when sliding and clicking on the navbar menu links. Can anyone point me in the right direction with this?

HTML CODE:

<nav class="navbar navbar-default" role="navigation">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>

            <div class="collapse navbar-collapse navbar-ex1-collapse">
                <ul class="nav navbar-nav">
                    <li data-target="#myCarousel" data-slide-to="0" class="active"><a href="#">slide 1</a></li>
                    <li data-target="#myCarousel" data-slide-to="1"><a href="#">slide 2</a></li>
                    <li data-target="#myCarousel" data-slide-to="2"><a href="#">slide 3</a></li>
                </ul>
            </div>
        </nav>    

<div id="myCarousel" class="carousel slide">
       <div class="carousel-inner">
          <div class="item active">
             <div class="wrapper">
                <%-- Slide 1 --%>
             </div>
          </div>
          <div class="item">
             <div class="wrapper">
                <%-- Slide 2 --%>
             </div>
          </div>
          div class="item">
             <div class="wrapper">
                <%-- Slide 3 --%>
             </div>
          </div>
       </div>

       <a class="carousel-control left" href="#myCarousel" data-slide="prev">
          <span class="icon-prev"></span>
       </a>
       <a class="carousel-control right" href="#myCarousel" data-slide="next">
          <span class="icon-next"></span>
       </a>
    </div>

Answer №1

I approached the task by dividing it into two stages: first, I removed the .active class from the old indicator, and then I added the .active class to the new indicator.

Building on Bosc's idea, I incorporated an additional function within the initial one.

You can view the example here.

Below is the jQuery code:

$(document).ready(function() {
  $(".carousel").carousel({
    interval: 5000
  });
  $('#myCarousel').on('slide.bs.carousel', function() {

    $(".myCarousel-target.active").removeClass("active");

    $('#myCarousel').on('slid.bs.carousel', function() {

      var to_slide = $(".carousel-item.active").attr("data-slide-no");

      $(".nav-indicators li[data-slide-to=" + to_slide + "]").addClass("active");

    });
  });

});
.navbar-default .navbar-nav>.active>a,
.navbar-default .navbar-nav>.active>a:hover,
.navbar-default .navbar-nav>.active>a:focus {
  color: #555;
  background-color: purple;
}
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>

<body>


  <nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="collapse navbar-collapse navbar-ex1-collapse">
      <ol class="nav navbar-nav nav-indicators">
        <li data-target="#myCarousel" data-slide-to="0" class="myCarousel-target active"><a href="#">slide 1</a>
        </li>
        <li data-target="#myCarousel" data-slide-to="1" class="myCarousel-target"><a href="#">slide 2</a>
        </li>
        <li data-target="#myCarousel" data-slide-to="2" class="myCarousel-target"><a href="#">slide 3</a>
        </li>
        <li data-target="#myCarousel" data-slide-to="3" class="myCarousel-target"><a href="#">slide 4</a>
        </li>
        <li data-target="#myCarousel" data-slide-to="4" class="myCarousel-target"><a href="#">slide 5</a>
        </li>
        <li data-target="#myCarousel" data-slide-to="5" class="myCarousel-target"><a href="#">slide 6</a>
        </li>
      </ol>
    </div>
  </nav>

  <div id="myCarousel" class="carousel slide">
    <div class="carousel-inner">
      <div data-slide-no="0" class="item carousel-item active">
        <div class="wrapper">
          &lt;%-- Slide 1 --%&gt;
        </div>
      </div>
      <div data-slide-no="1" class="item carousel-item">
        <div class="wrapper">
          &lt;%-- Slide 2 --%&gt;
        </div>
      </div>
      <div data-slide-no="2" class="item carousel-item">
        <div class="wrapper">
          &lt;%-- Slide 3 --%&gt;
        </div>
      </div>
      <div data-slide-no="3" class="item carousel-item">
        <div class="wrapper">
          &lt;%-- Slide 4 --%&gt;
        </div>
      </div>
      <div data-slide-no="4" class="item carousel-item">
        <div class="wrapper">
          &lt;%-- Slide 5 --%&gt;
        </div>
      </div>
      <div data-slide-no="5" class="item carousel-item">
        <div class="wrapper">
          &lt;%-- Slide 6 --%&gt;
        </div>
      </div>
    </div>

    <a class="carousel-control left" href="#myCarousel" data-slide="prev">
      <span class="icon-prev"></span>
    </a>
    <a class="carousel-control right" href="#myCarousel" data-slide="next">
      <span class="icon-next"></span>
    </a>
  </div>
</body>

</html>

Answer №2

Implement a jQuery/JS script to toggle the active class when an element is clicked

$('.nav li').on('click', function(){
    $('li.active').removeClass('active');
    $(this).addClass('active');
});

Check out the latest update here. Due to time constraints, some errors like the initial slide not becoming active again exist. Hopefully, it serves as a good starting point for you to troubleshoot and improve.

$(document).ready(function() {
  $(".carousel").carousel({
    interval: 5000
  });
  $('#myCarousel').on('slide.bs.carousel', function () {
    var to_slide;
    to_slide = $(".carousel-item.active").attr("data-slide-no");
    $(".myCarousel-target.active").removeClass("active");
    $(".nav-indicators [data-slide-to=" + to_slide + "]").addClass("active");
  });
});

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

What is the best way to establish the starting property state for CSS Animation?

I'm looking to create an animation that involves the following steps: Initial: elementA starts with opacity set at 0; When hovering over containerA, which contains elementA: elementA transitions from position (-5px, 5px) to (0px, 0px); elementA ch ...

What is the best way to adjust an element to match the height of the browser window?

I've coded a solution to ensure that the height of a section (#home) matches the height of the window, but it's causing issues. Here is the code snippet I used: // Adjust Home section height based on window height function fitHomeToScreen() { ...

When previewing a card on Twitter's validator tool, the image displays properly. However, when attempting to share the image on

Below is the code that I have written on my HTML page: <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@name" /> <meta name="twitter:title" content="Twitter - image share" /> <meta name="twi ...

Repetitive reloading of JQM pages due to ajax functionality

Having a strange issue... I'm in the process of setting up my application, and I'm using an ajax method to load another page. Between these pages, there's a simple forward/back functionality. When I hit the back button, I can see that the ...

The Dilemma of Mustache Integration with Jquery Plugin

I've implemented mustache js with an accordion plugin, using an external template file and an external json file to populate the accordion widget. However, I'm encountering an issue where the accordion does not seem to work properly unless prompt ...

How do I ensure the CSS triangles maintain their correct boundaries when hovered over with the cursor?

Can the issue of incorrect triangle activation be fixed when hovering on http://jsfiddle.net/2AXhR/? Sometimes the wrong triangle is triggered due to the triangles' bounding areas being rectangles, causing overlap and z-index conflicts. <style ...

Utilize PHP to read a text file and merge identical entries to declutter the

I am testing a code snippet that redirects users to a different page if their IP address does not match the predefined one. If it doesn't match, I also want to save their IP in a text file. $file = fopen("ips.txt", "w"); if ($ip == "iphere") { e ...

What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting ...

Generating a variety of distinct HTML elements in a PHP foreach loop

In the process of building a website, I am faced with the task of retrieving multiple rows of data from my database. Each displayed row should be accompanied by a button with a unique name. However, I am struggling to ensure that each button is assigned a ...

Using AJAX within the $.when function to extract the first character from the returned string

Currently, I am utilizing an AJAX call by using $.when to wait for the completion of that specific ajax request and then continue with processing the subsequent ajax request inside. The code block below demonstrates where the $.when method is being invoke ...

Sliding out menu using AngularJS

I have been attempting to create a slide out menu without success. My goal is for the text (home,users) to appear when the >> button is clicked. I seem to be stuck and can't figure out what I'm missing. This project also marks my initial ve ...

Error: The function $(...).jqGrid is not defined for caption: 'Array-Based Student List Loading'

Encountered an error when trying to load the Index view. I am attempting to implement JQGrid using the jQuery grid plugin. I have included several JS files and CSS for JQGrid in the view, but I am unable to create the grid using the plugin. I am using ver ...

The dynamic php form features a single set of buttons labeled Next and Before for easy navigation

I am in the process of creating a dynamic form using a single PHP file that displays and saves data from an SQL database. I now want to add two buttons, NEXT and BEFORE, but I have been having difficulty getting them to display or navigate to the next/prev ...

I'm currently facing difficulties transferring data as I'm unable to pinpoint the error in my jQuery Ajax code

I am currently working on my index page and I have a requirement to submit form data without reloading the page. To achieve this, I want to utilize AJAX with jQuery for a seamless user experience. Could you provide feedback on my implementation using jQue ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

What is the best way to change a javascript string into HTML so that it can be shown in a form?

I am struggling to find a solution to this issue. I am fairly new to jQuery and JavaScript, so please forgive me if my question seems basic. I am trying to call a cfc (ColdFusion) using jQuery and retrieve HTML data. However, when I receive the data, it ...

Tips for modifying the table structure while utilizing datalist

Is there a way to adjust the table layout when using datalist? The current result, as shown in Example 1, does not properly display all the data in a continuous manner due to the table layout. How can I achieve a layout similar to Example 2? I must use th ...

What is the correct method for attaching event listeners to newly added elements following an AJAX request for HTML content? (Using jQuery or JavaScript)

I'm working on a project where new setting pages are loaded via AJAX. I'm trying to figure out the best way to bind listeners to elements in the new content. One idea I had is to create a function that checks the file path and applies appropriat ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

The print preview displays a single div in an incorrect location

I have successfully created a javascript plot and wanted to incorporate a legend that overlaps the plot. Unfortunately, the function I used does not support directly overlapping legends, but it does allow for placing the legend in a separate div. To work a ...