Highlighting the incorrect image when clicked on in the BS4 carousel indicator (active)

I am currently working on a Bootstrap 4 carousel and using Jquery to fetch and display images. The images are named from 1.jpg to 72.jpg. Everything seems to be working fine except that when I click on an image, the indicator thumbnails highlight the wrong image.

For example, if I click on image 2, then image 3 is highlighted instead of image 2.

I have been trying to figure out why this issue is happening without much success.

If you want to take a look at my code, here is a link to the fiddle.

To fetch and append the images using Jquery, I use the following code:

$(document).ready(function(){
  for(var j = 1; j < 72; j++) {
$('<div class="carousel-item"><img src="./images/'+j+'.jpg" width="100%"></div>').appendTo('.carousel-inner');
$('<li data-target="#carousel" data-slide-to="'+j+'"><img src="./images/'+j+'.jpg" class="img-fluid"></li>').appendTo('.carousel-indicators')
console.log(j);
}
$('.carousel-item').first().addClass('active');
$('.carousel-indicators > li').first().addClass('active');
$('#carousel').carousel({
 pause: true,
 interval: true,
});
});

The HTML structure for the carousel is quite basic:


<div id="carousel" class="carousel slide" data-interval="false">            
  <div class='carousel-outer'>
    <div class="carousel-inner"></div>      
      <a class="carousel-control-prev" href="#carousel" data-slide="prev"> <span class="carousel-control-prev-icon"></span>
      </a>
      <a class="carousel-control-next" href="#carousel" data-slide="next"> <span class="carousel-control-next-icon"></span>
      </a>
     </div>
<!-- Indicators -->
    <ol class="carousel-indicators"></ol>
</div>


And here is the CSS used for styling the carousel:

#carousel {
      margin: 20px auto;
      max-height:658px;
      width: 1024px;
  }
  #carousel .carousel-indicators {
    flex-wrap: wrap;
       justify-content: center; 
       padding: 0 15px; 
       width: 100%; 
       position: static; 
       right: 0; 
       bottom: 0; 
       margin-right: 0; 
       margin-left: 0; 

  }
  #carousel .carousel-indicators li {
      background-color: transparent;
      -webkit-border-radius: 0;
      border-radius: 0;
      display: inline-block;
      height: auto;
      margin: 0 !important;
      width: auto;
  }
  #carousel .carousel-indicators li img {
      width: 50px;
      display: block;
      opacity: 0.9;
  }
  #carousel .carousel-indicators li.active img {
      opacity: 1;
  }
  #carousel .carousel-indicators li:hover img {
      opacity: 0.75;
  }
  #carousel .carousel-outer {
      position: relative;
  }

  .carousel-item-next, .carousel-item-prev, .carousel-item.active {
    display: block !important;
}

Answer №1

There is a high likelihood that the issue arises due to the loop starting from 1 instead of 0.

A potential solution could involve modifying the data-slide-to attribute's value to j - 1 rather than j:

$(document).ready(function(){
  for(var j = 1; j < 72; j++) {
    $('<div class="carousel-item"><img src=" ./images/'+ j +'.jpg " width="100%"></div>').appendTo('.carousel-inner');
    $('<li data-target="#carousel" data-slide-to="'+ (j - 1) +'"><img  src=" ./images/'+ j +'.jpg " class="img- fluid"></li>').appendTo('.carousel-indicators')
console.log(j);
}
    $('.carousel-item').first().addClass('active');
    $('.carousel-indicators > li').first().addClass('active');
    $('#carousel').carousel({
        pause: true,
        interval: true,
    });
});

Answer №2

It seems like the problem lies with the for loop starting at 1 instead of 0 for data-slide-to. Try adjusting it to start at 0, like this:

$('<li data-target="#carousel" data-slide-to="'+(j-1)+'"><img  src="./images/'+j+'.jpg" class="img-fluid"></li>').appendTo('.carousel-indicators')

Answer №3

Modify the data-slide-to="'+j+'" to data-slide-to="'+ (j - 1) +'"

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

js include exclude switch a category

Although this question has been asked before, I have a query on completely removing an "id" from an element. Let's consider the following scenario: <div id="page"> some content here </div> I want to eliminate the "id" attribute from the ...

Is there a way to blend together two elements within a Bigcommerce theme seamlessly?

Recently, I have been tasked with customizing a Bigcommerce theme for a client. While I am not very experienced with Bigcommerce and only have basic knowledge of php, I have encountered an interesting challenge with the current theme header setup. The exis ...

Conceal the slider thumb within the material-ui framework

I've been attempting to conceal the slide thumb, initially without using a library. However, I started considering utilizing material-ui as it might make the process easier. Hence, I'm seeking assistance here. Below is my code snippet: import * ...

Ways to create a blurred effect on a button that is in a disabled state

Can a button be blurred when it is disabled? Are there any methods to achieve this effect? <button (click)="addRow()" class="add-row-btn" mat-button [disabled]="isDisabled"> Add Row</button> ...

Angular's interactive dropdown menus

Currently, I am diving into Angular and working on implementing dynamic select boxes in jQuery to prompt the user for the number of children. These select boxes adapt according to the selection made, subsequently asking for the ages of the children. While ...

The options in the dropdown menu vanish when interacting with a jQuery feature that relies on

Recently, I have found AJAX, JSON, and jQuery to be indispensable tools in my coding endeavors. The application I am working on is a replacement for a flawed one, and it is coming along nicely. Despite making progress with the AJAX method, I have encounte ...

Tips for inserting text into the description field on Shopify using Python Selenium

I am looking to build a bot using Python Selenium that can input the values I provide. I understand how to work with headings and select items, but I am unsure of how to paste text in a description field. For example: How can I paste text? I am unable to ...

loop not functioning properly with file type input

Having trouble uploading an image and copying it into a folder named images within a loop. Can you assist with solving this issue? Here's my code: $sql="SELECT * FROM product"; $q=$conn->query($sql); while($r=$q->fetch(PDO::FETCH_ASSOC)) { $cod ...

Expand or reduce the displayed content based on the preset value in Angular

I am trying to implement a "Show More" and "Show Less" functionality for a product's description. It works fine with normal strings, but when I try to apply the same logic to the value with {{product.description}}, the entire value inside {{product.de ...

The hyperlink appears to be malfunctioning

I've been working with a jQuery multilayer menu, but I encountered an issue with the link not being clickable. For reference: jQuery: JS Array Demo: When navigating through the menu on the demo site - "devices" -> "Mobile phones" -> "super s ...

Discovering the screen dimensions or viewport using Javascript in Bootstrap 4

Is there a method to identify the view port/screen size being utilized by Bootstrap 4 using Javascript? I've been struggling to find a dependable way to determine the current view port after a user resizes the browser. I attempted to use the Bootstra ...

Absence of MVC5 Vanilla Layouts

Creating my first MVC5/Razor application from the ground up, I want to avoid including unnecessary references that cause bloat. In the Views folder, I have separate Home and Shared subfolders. The Home folder contains Index.cshtml, while the Shared folder ...

Switching Up Poster Images in Chrome with Afterglow HTML5 Video on Hover

I have been experimenting with the html5 video player from AfterGlow. In my sample video, I included a poster attribute. However, I noticed an issue when viewing the video in Chrome - whenever I hover over it, the poster image flickers, creating an undesir ...

Display an HTML tag with JavaScript

My code is in both HTML and TS files. The content stored in the Description variable looks like this: <div>aaaa</div><div>bbbb</div><div>cccc</div> Currently, the output displays as follows: aaaabbbbcccc I want to modi ...

What is the best way to implement a media query for changing styles on hover for an element

I am facing an issue with media queries where when I apply a hover effect to an element, such as a clickable link in the navigation bar, the new rules work as expected but also retain the default browser styles. For instance: nav ul li a:hover{ border:0; ...

Configuring Angular with Selenium to utilize model-driven values

Within the DOM, there is an input element linked to ng-model='obj.values.x.value' obj.values.x.value currently holds the value "foo". When using Selenium to run the code, the field displays "foo". However, after attempting to clear the field usi ...

Guide to executing a server request upon clicking a tab in asp.net using bootstrap

I managed to incorporate a tab system in my ASP.Net project using Bootstrap. <div> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"> <a href="#divrecentQ" id="linkdivrecentQ" aria ...

AngularJS Instant Search is experiencing significant delays

Currently, I am developing a database with a web front-end. In the previous versions of this project, I utilized jQuery. However, I have now transitioned to using AngularJS for the "instant-search" feature, as shown below: function SearchCtrl($scope, $htt ...

Transferring information between HTML pages using JSON and jQuery

After reviewing the topics, I was unable to find a complete answer. My objective is to populate a drop-down menu with text from another HTML file. Both HTML files are located on localhost. It is mandatory for the data to be in JSON format. Initially, I a ...

Tips for achieving a precise amount of boxes in each row

Is it possible to only have 5 boxes per line and then the next one goes to the next line using CSS? https://i.stack.imgur.com/L7vr4.png .box { border-color: #32ff00; border-width: 4px; border-style: dotted; width: 170px; height: 200px; fl ...