Tips for preventing automatic sliding in a bootstrap 4 carousel on mobile with JavaScript or other methods

Can someone assist me in stopping my carousel from auto-sliding on mobile devices only? I have attempted solutions from similar queries on this platform, but they have not worked for me. Any suggestions would be greatly appreciated. Below is an example of Bootstrap carousel code:

<script>
        
        // set breakpoint width
var BP = 362;

// start carousel
$('.carousel').carousel({ interval: (window.innerWidth<BP)?false:500 });

// if user rotates phone orientation | window resite
$(window).on('resize', function(ev){
  if( window.innerWidth < BP ){ 
    $('.carousel').carousel({ interval: false });
  } else {
    $('.carousel').carousel({ interval: 500 });
  }
})
    
    </script>
    
    
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
  <style>
  /* Make the image fully responsive */
  .carousel-inner img {
    width: 100%;
    height: 100%;
  }
  </style>
</head>
<body>

<div id="demo" class="carousel slide" data-ride="carousel">
  <ul class="carousel-indicators">
    <li data-target="#demo" data-slide-to="0" class="active"></li>
    <li data-target="#demo" data-slide-to="1"></li>
    <li data-target="#demo" data-slide-to="2"></li>
  </ul>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="https://www.w3schools.com/bootstrap4/la.jpg" alt="Los Angeles" width="1100" height="500">
      <div class="carousel-caption">
        <h3>Los Angeles</h3>
        <p>We had such a great time in LA!</p>
      </div>   
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/chicago.jpg" alt="Chicago" width="1100" height="500">
      <div class="carousel-caption">
        <h3>Chicago</h3>
        <p>Thank you, Chicago!</p>
      </div>   
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/ny.jpg" alt="New York" width="1100" height="500">
      <div class="carousel-caption">
        <h3>New York</h3>
        <p>We love the Big Apple!</p>
      </div>   
    </div>
  </div>
  <a class="carousel-control-prev" href="#demo" data-slide="prev">
    <span class="carousel-control-prev-icon"></span>
  </a>
  <a class="carousel-control-next" href="#demo" data-slide="next">
    <span class="carousel-control-next-icon"></span>
  </a>
</div>

Answer №1

To achieve this, utilize .carousel's pause and cycle functions as demonstrated in the code snippet below:

// define breakpoint width
var BP = 362;

// initialize carousel
$('.carousel').carousel({
  interval: (window.innerWidth < BP) ? false : 500
});

// handle window resize event
$(window).on('resize', function(ev) {
  if (window.innerWidth < BP) {
    $('.carousel').carousel('pause');
  } else {
    $('.carousel').carousel('cycle');
  }
})
/* Ensure images are fully responsive */

.carousel-inner img {
  width: 100%;
  height: 100%;
}
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
  <style>
  .carousel-inner img {
    width: 100%;
    height: 100%;
  }
  </style>
</head>
<body>

<div id="demo" class="carousel slide" data-ride="carousel">
  <ul class="carousel-indicators">
    <li data-target="#demo" data-slide-to="0" class="active"></li>
    <li data-target="#demo" data-slide-to="1"></li>
    <li data-target="#demo" data-slide-to="2"></li>
  </ul>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="https://www.w3schools.com/bootstrap4/la.jpg" alt="Los Angeles" width="1100" height="500">
      <div class="carousel-caption">
        <h3>Los Angeles</h3>
        <p>We had such a great time in LA!</p>
      </div>   
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/chicago.jpg" alt="Chicago" width="1100" height="500">
      <div class="carousel-caption">
        <h3>Chicago</h3>
        <p>Thank you, Chicago!</p>
      </div>   
    </div>
    <div class="carousel-item">
      <img src="https://www.w3schools.com/bootstrap4/ny.jpg" alt="New York" width="1100" height="500">
      <div class="carousel-caption">
        <h3>New York</h3>
        <p>We love the Big Apple!</p>
      </div>   
    </div>
  </div>
  <a class="carousel-control-prev" href="#demo" data-slide="prev">
    <span class="carousel-control-prev-icon"></span>
  </a>
  <a class="carousel-control-next" href="#demo" data-slide="next">
    <span class="carousel-control-next-icon"></span>
  </a>
</div>

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

Updating the information displayed in one section by selecting a button on the Google Maps infowindow located in a separate section

My webpage is divided into multiple divisions. One division contains a map using the Google Maps API with markers. When I click on a marker, an info window opens up. Now, I am attempting to place a button inside that info window which, when clicked, will ...

Display and conceal div with Jquery as you scroll to specific points on a mobile device

I'm looking to create a dynamic div that appears and disappears based on the user's scroll position. Here is what I have so far: $(document).scroll(function() { var y = $(this).scrollTop(); if (y > 200) { $('.float-contai ...

Click the closest checkbox when the value equals the Jquery datatable

I am facing an issue where I need to add a class and click on a specific element in each row of my jQuery datatable if a certain value is equal. However, I am unable to successfully add the class to that element and trigger a click event. <table id="us ...

What is the best way to ensure a button's size remains constant even when new text is inserted?

https://i.sstatic.net/K4QDt.png I created these buttons for a tic-tac-toe game as a way to improve my React skills. I'm aiming to have all the boxes form a perfect square shape. However, the box size changes when text is added. While I'm workin ...

The styled components can create identical CSS classes with varying conditions

Below are the CSS styles I am currently using: import styled, { css } from "styled-components"; const H4 = css` font-family: "Futura"; font-style: normal; font-weight: 500; font-size: 20px; line-height: 140%; color: #3a786a ...

Ways to rearrange items in the navigation bar?

I am working with a Bootstrap template and I am trying to adjust the layout to be right-to-left (RTL). Currently, when I set the site title to RTL in the navbar, the buttons in the navbar also switch to RTL alignment. This is not the desired layout I want. ...

Struggling to retrieve the session value using JavaScript in a C# application

Currently, I am attempting to retrieve four values from the session. However, I am only able to fetch two of them, while the other two seem to be missing. As a beginner, I apologize if my question comes across as too simplistic. Within a tree view, I have ...

Picture inside text area covering drop-down list

After making some adjustments to Bootstrap using a custom -theme.css file, I successfully altered the appearance of the dropdown menu. By removing the borders from the navbar and wrapping a header around it set to be fixed on top, everything seemed to be w ...

Encountering issues while retrieving information from database through AJAX and PHP

Update: The initial section of this question has been resolved and is now updated with the working code. ~ I'm currently developing a JavaScript application, and I'm encountering challenges with making an AJAX call function properly. While I ha ...

Tips on incorporating a parameter into an API call function within a React application

I'm a newcomer to the world of React and trying to figure things out as I go. Here is the code snippet I have: const handleDelete = e => { const token = getCookie('token'); e.preventDefault(); axios .delete( `$ ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Guide to updating the favicon with next js

I am facing an issue where the favicon is not changing when searched on Google. The image is located in the public folder, but it is still showing the old logo instead of the new one. Below is the code from the _document.tsx file: <Html dir={dir}> ...

Can data be transmitted to two separate scripts simultaneously?

Just a quick HTML inquiry: Can data from HTML forms be sent to two separate scripts using the "action" attribute, or is there an alternative method? I'd like to explore other options aside from utilizing curl. ...

What is the best way to include CSS in a CodeIgniter project?

I am facing an issue with loading a CSS file in Codeigniter. It seems like there might be something wrong with my code. Can someone help me understand how to properly load a CSS file in Codeigniter and possibly identify any errors in my current code? < ...

Click Action on CanJS Table

I am currently developing a canJS application and have been able to successfully handle the click event for an HTML table using the code below. 'table td click':function(el,event){ console.log('clicked ',el.text()); } ...

What is the process for marking a form field as invalid?

Is it possible to validate the length of a field after removing its mask using text-mask from here? The problem is that the property "minLength" doesn't work with the mask. How can I mark this form field as invalid if it fails my custom validation met ...

Creating a smooth transition effect on text length using Javascript and CSS: Fading the text as it

I have been searching everywhere for a solution to my issue, but I haven't found it yet. I keep coming across methods to fade text on and off on load, which is not what I need. My goal is to fade some text on the same line, and I have created a mockup ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Repeated information displayed in modal pop-ups

HTML <a class="btn" data-popup-open="popup-1" href="#">More Details</a> <div class="popup" data-popup="popup-1"> <div class="popup-inner"> <h2>Unbelievable! Check this Out! (Popup #1)</h2> ...

Trouble aligning two columns in a row with Bootstrap 4

Hey there! I've encountered an issue with my login form using bootstrap 4. I have set up two col-md-6 columns in a row for "Remember Me" and "Forgot Password", but on mobile devices, the "Forgot Password" section jumps down from the row. Can anyone sh ...