Utilizing the Bootstrap Carousel tied to a specific slide index

Here is a simple HTML page I have created.

<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
    <body>
        <div id="MyCarousel" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img height="500px" class="d-block w-100" src="1.jpg" alt="First">
    </div>
    <div class="carousel-item">
      <img height="500px" class="d-block w-100" src="2.jpg" alt="Second">
    </div>
    <div class="carousel-item">
      <img height="500px" class="d-block w-100" src="3.jpg" alt="Third">
    </div>
  </div>
  <a class="carousel-control-prev" href="#MyCarousel" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#MyCarousel" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
  <img id="test" height="100px" width="100px" src="4.png" alt="Fourth">
  <p id="test2" >This is a paragraph.</p>
</div>
<script>
$('#MyCarousel').on('slide.bs.carousel', function onSlide (ev) {
  var id = ev.relatedTarget.id;
  switch (id) {
    case "1":
      window.alert(1);
      break;
    case "2":
      window.alert(2);
      break;
    case "3":
      window.alert(3);
      break;
    default:
      window.alert(4);
  }
});
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    </body>
</html>

The ID of the carousel is #MyCarousel.
Bootstrap version being used is 4.0.0.
I want to display an alert when changing the carousel slide, but it's not working. Any suggestions on how to fix it?
Possibly the issue lies with the onSlide function.

Answer №1

The main issue you are facing is attempting to utilize jQuery before importing it. To resolve this, make sure you import

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
before making any calls to $

However, you may still need to refine the code that identifies id. If you require further assistance on this matter, feel free to reach out for help.

Answer №2

The issue with the onSlide event not functioning correctly stemmed from a lack of recognition of the jQuery CDN reference within the application. This problem became apparent after I made a specific adjustment to my code. It's important to note that trying to directly extract the id value from the variable ev.relatedTarget did not yield the expected result.

$('#MyCarousel').on('slide.bs.carousel', function onSlide (ev) {
  var id = ev.relatedTarget.id;
  console.log(ev);
  switch (id) {
    case "1":
      window.alert(1);
      break;
    case "2":
      window.alert(2);
      break;
    case "3":
      window.alert(3);
      break;
    default:
      window.alert(4);
  }
});
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<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>
</head>
    <body>
        <div id="MyCarousel" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img height="500px" class="d-block w-100" src="https://picsum.photos/200/300" alt="First">
    </div>
    <div class="carousel-item">
      <img height="500px" class="d-block w-100" src="https://picsum.photos/200/300" alt="Second">
    </div>
    <div class="carousel-item">
      <img height="500px" class="d-block w-100" src="https://picsum.photos/200/300" alt="Third">
    </div>
  </div>
  <a class="carousel-control-prev" href="#MyCarousel" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#MyCarousel" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
  <img id="test" height="100px" width="100px" src="https://picsum.photos/200/300" alt="Fourth">
  <p id="test2" >This is a paragraph.</p>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

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

Is it possible to incorporate some scripting to enhance the efficiency of deploying my mongoose database?

I'm completely new to setting up servers and diving into back-end development. My technical language is limited, making it challenging to find solutions through online research. I apologize in advance for my lack of expertise in this area. Currently, ...

Having trouble converting json encoded data from php to JSON parse using javascript/jquery

Hi there! I'm currently facing an issue while trying to extract data from my database and display it on my HTML view. Can anyone help me identify what might be going wrong? Below is my code snippet: function display($dbhandler){ $sql = "SELECT * FR ...

What is the best way to ensure that the question text will wrap onto a new line if it becomes too lengthy

I am currently working on developing ASP.NET MVC applications. However, I am facing a design issue with the HTML, CSS, and Bootstrap elements on one of my pages. The problem arises when Question 8 exceeds the border and does not wrap to a new line as inte ...

Ensuring User Data is Current in the UI with Firebase Auth Callbacks

Below is the standard method for setting the user state to currentuser that is returned from onAuthStateChanged. I am looking for a useEffect hook that will be triggered whenever there is an update to the user's information. Unfortunately, I am unable ...

What is the extent of a variable within a jQuery function?

Similar Question: Understanding Asynchronous Behavior in Ajax Question: Why does my variable "temp" remain as 0 after the AJAX request? function calculate7() { var temp = 0; $.ajax({ type: "POST", ...

VueJS - Building a Real-Time Timer with Begin, Halt, Continue and End

Currently, I am facing an issue with the resume function of my counter up feature. For instance, if the timer is paused at 00:00:03, and then, five seconds later the resume button is clicked, it should continue from 00:00:04. However, in reality, the time ...

Implementing scrollIntoView() method in Typescript

Currently, I am focused on automating an AngularJS application. Our go-to automation language is TypeScript. My aim is to scroll to a specific element and then click on it. var element = element(by.className('learn-link')); browser.driver.exec ...

What is the best way to calculate the product of decimal numbers within a TypeScript Number variable?

Imagine you have a number, for example 288.65, and you want to multiply it without the decimal point in order to obtain the result of 28865. However, when attempting to achieve this by using console.log(288.65 * 100), the output is not as expected, showin ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Storing retrieved data in React without using Redux involves using either the Context API or

When using Redux, I have a common store where fetched data is stored. For example, if I navigate away from my videos page (/videos) and then return to it, the videos are still available in the videos reducer. This allows me to show the user already loaded ...

Insert an array of objects into the td elements of a pre-existing table

Currently, I have a table where the td cells are intentionally displayed as blocks. My aim is to insert labels inside each of these td cells by creating spans with specific classes and then prepend them to the table cell. To achieve this, I am utilizing an ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...

Eliminating blank attributes within an array of objects

I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they ...

Generating an array by iterating through each object within an array of objects

I am working with a JSON structure and I need to separate it into two arrays. The first array should include all the values from the key "employee only" to "Annual OOP max / entire family" from each object in the JSON array. The second array should contain ...

Tips for customizing the color of pagination in bootstrap

I'm currently in the process of designing a website and I've chosen to implement Bootstrap's pagination for navigating between pages. Due to time constraints, I was wondering if anyone knows how I can utilize classes like "bg-dark", "bg-prim ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Adding extra spacing to a bootstrap container the correct way

Scenario: Increasing padding in container view sketch Hello there! I am currently using bootstrap scss in typo3 and having ws_scss compile it for me. I feel like the content area needs more padding to make it slightly smaller. Here are some basic details ...

Delete the radio button list within the content placeholder

I'm having trouble with accessing elements by name on a master page content placeholder. Can someone assist me with this issue? Thank you in advance. <asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <script type="tex ...

Setting up or modifying JQuery AJAX encoding settings

I am currently working on a simple PATCH call similar to the one below: .ajax({ url: "/foo/bar/" type: "PATCH", dataType: 'json', data: { "foo": "foosball", "bar": "bars on bars" }, ... }); After Jquery e ...

Slider for comparing images is currently malfunctioning in Firefox

I recently came across a tutorial on how to create an image comparison slider, and it worked flawlessly on Chrome. However, when I tried to load it on Firefox, the slider didn't respond at all. Below is a snippet of the code: const slider = do ...