I have developed a custom jQuery carousel that includes functionality to start and stop the carousel based on specific conditions

I have set up a jQuery carousel that moves to the left when a checkbox is checked, but I need it to stop moving when the checkbox is unchecked. Can someone help me achieve this?

$("#checkBox").click(function(){
    if($(this).prop("checked") == true){
        carouselRun();
    }
    else if($(this).prop("checked") == false){
        carouselStop();
    }
});  

jQuery(document).ready(function ($) {
    var mslideWidth = 500, mslideHeight = 105, speed = 3000,
    slideCount = $('#slider ul li').length,
    slideWidth = $('#slider ul li').width(),
    slideHeight = $('#slider ul li').height(),
        sliderUlWidth = slideCount * slideWidth;
  
    function carouselRun(){
        setInterval(function () {
            moveRight();
}, speed);
};
    function carouselStop(){
setInterval(function () {
moveLeft();
}, speed).stop();
};
  
    $('#checkBox').click(function(){
if($(this).prop("checked") == true){
carouselRun();
}
        else if ($(this).prop("checked") == false){
carouselStop();
}
}); 
  
if (mslideWidth != 0 || mslideHeight != 0){
slideWidth = mslideWidth;
slideHeight = mslideHeight;
$('#slider ul li').css('width',mslideWidth);
$('#slider ul li').css('height',mslideHeight);
}
$('#slider').css({ width: slideWidth, height: slideHeight });
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
$('#slider ul li:last-child').prependTo('#slider ul');

    function moveLeft() {
$('#slider ul').animate({
left: + slideWidth
}, function () {
$('#slider ul li:last-child').prependTo('#slider ul');
$('#slider ul').css('left', '');
});
};

function moveRight() {
$('#slider ul').animate({
left: - slideWidth
},function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
};

$('a.control_prev').click(function () {
moveLeft();
});

$('a.control_next').click(function () {
moveRight();
});
});    
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600);

html {
  border-top: 5px solid #fff;
  background: #58DDAF;
  color: #2a2a2a;
}

html, body {
  margin: 0;
  padding: 0;
  font-family: 'Open Sans';
}

h1 {
  color: #fff;
  text-align: center;
  font-weight: 300;
}

#slider {
  position: relative;
  overflow: hidden;
  margin: 20px auto 0 auto;
  border-radius: 4px;
}

#slider ul {
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
}

#slider ul li {
  position: relative;
  display: block;
  float: left;
  margin: 0;
  padding: 0;
  width: 500px;
  height: 100px;
  background: #ccc;
  text-align: center;
}

a.control_prev, a.control_next {
  position: absolute;
  top: 10%;
  z-index: 999;
  display: block;
  padding: 4% 3%;
  width: auto;
  height: auto;
  background: #2a2a2a;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  font-size: 18px;
  opacity: 0.8;
  cursor: pointer;
}

a.control_prev:hover, a.control_next:hover {
  opacity: 1;
  -webkit-transition: all 0.2s ease;
}

a.control_prev {
  border-radius: 0 2px 2px 0;
}

a.control_next {
  right: 0;
  border-radius: 2px 0 0 2px;
}

.slider_option {
  position: relative;
  margin: 10px auto;
  width: 160px;
  font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider_option">
  <input type="checkbox" id="checkBox">
  <label for="checkbox">Autoplay Slider</label>
</div> 

<div id="slider">
  <a href="#" class="control_next">>></a>
  <a href="#" class="control_prev"><</a>
  <ul>
    <li>SLIDE 1</li>
    <li style="background: #aaa;">SLIDE 2</li>
    <li>SLIDE 3</li>
    <li style="background: #aaa;">SLIDE 4</li>
  </ul>  
</div>

Answer №1

To stop the timer and carousel, make use of the clearInterval function. Replace the carouselRun and carouselStop functions with the following code and include the interval variable where you declare your other variables.

function carouselRun(){
    interval = setInterval(function () {
        moveRight();
    }, speed);
};

function carouselStop(){
    clearInterval(interval);
};

Here is a working example:

jQuery(document).ready(function ($) {
  var mslideWidth = 500, mslideHeight = 105, speed = 3000,
slideCount = $('#slider ul li').length,
slideWidth = $('#slider ul li').width(),
slideHeight = $('#slider ul li').height(),
  sliderUlWidth = slideCount * slideWidth,
      interval;
  
function carouselRun(){
interval = setInterval(function () {
moveRight();
}, speed);
};
  function carouselStop(){
clearInterval(interval);
};
  
  $('#checkBox').click(function(){
if($(this).prop("checked") == true){
carouselRun();
}
    else if($(this).prop("checked") == false){
carouselStop();
}
}); 
  
if(mslideWidth != 0 || mslideHeight != 0){
slideWidth = mslideWidth;
slideHeight = mslideHeight;
$('#slider ul li').css('width',mslideWidth);
$('#slider ul li').css('height',mslideHeight);
}
$('#slider').css({ width: slideWidth, height: slideHeight });
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
$('#slider ul li:last-child').prependTo('#slider ul');

  function moveLeft() {
$('#slider ul').animate({
left: + slideWidth
}, function () {
$('#slider ul li:last-child').prependTo('#slider ul');
$('#slider ul').css('left', '');
});
};

function moveRight() {
$('#slider ul').animate({
left: - slideWidth
},function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
};

$('a.control_prev').click(function () {
moveLeft();
});

$('a.control_next').click(function () {
moveRight();
});

});
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600);

html {
  border-top: 5px solid #fff;
  background: #58DDAF;
  color: #2a2a2a;
}

html, body {
  margin: 0;
  padding: 0;
  font-family: 'Open Sans';
}

h1 {
  color: #fff;
  text-align: center;
  font-weight: 300;
}

#slider {
  position: relative;
  overflow: hidden;
  margin: 20px auto 0 auto;
  border-radius: 4px;
}

#slider ul {
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
}

#slider ul li {
  position: relative;
  display: block;
  float: left;
  margin: 0;
  padding: 0;
  width: 500px;
  height: 100px;
  background: #ccc;
  text-align: center;
}

a.control_prev, a.control_next {
  position: absolute;
  top: 10%;
  z-index: 999;
  display: block;
  padding: 4% 3%;
  width: auto;
  height: auto;
  background: #2a2a2a;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  font-size: 18px;
  opacity: 0.8;
  cursor: pointer;
}

a.control_prev:hover, a.control_next:hover {
  opacity: 1;
  -webkit-transition: all 0.2s ease;
}

a.control_prev {
  border-radius: 0 2px 2px 0;
}

a.control_next {
  right: 0;
  border-radius: 2px 0 0 2px;
}

.slider_option {
  position: relative;
  margin: 10px auto;
  width: 160px;
  font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider_option">
  <input type="checkbox" id="checkBox">
  <label for="checkbox">Autoplay Slider</label>
</div> 

<div id="slider">
  <a href="#" class="control_next">>></a>
  <a href="#" class="control_prev"><</a>
  <ul>
    <li>SLIDE 1</li>
    <li style="background: #aaa;">SLIDE 2</li>
    <li>SLIDE 3</li>
    <li style="background: #aaa;">SLIDE 4</li>
  </ul>  
</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

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

What is the reason behind the success of 'as' in ngFor compared to '='?

<tr *ngFor = "let item of list; let i = index;"> An issue arises with the code above: The error message reads: Type 'number' is not assignable to type 'string'. td [ngModelGroup]="j" #temp="ngModelGroup ...

Asynchronous Middleware in ExpressJS Routing

I'm having trouble implementing a middleware in Express. Whenever I make a request, I end up with infinite loading times. I've searched on various platforms but couldn't find any examples that utilize an async await middleware stored in a se ...

Utilizing jQuery to transmit an incessant stream of Ajax .post variables to the server

Is there a way to continuously send updates to the server using jQuery with minimal intervals? This is specifically for updating the cursor position of one person on others' screens, and will be used in an HTML5 whiteboard prototype. What options ar ...

Is there a way to use ajax to dynamically monitor the presence of a file in real-time?

Is there a way to automatically observe the status of a file using ajax without having to manually refresh it with a button? ...

unable to add browse-sync to Ubuntu 16.04

I recently installed nodejs and npm and attempted to install browser-sync using the command npm install -g browser-sync. However, I encountered an error. npm install -g browser-sync npm ERR! Linux 4.15.0-101-generic npm ERR! argv "/usr/bin/nodejs" "/ ...

JavaScript error: forEach is not a function

I've encountered an issue while attempting to loop through a JSON object to extract data. Whenever I run my code, I receive this error: Type Error: element.listing.forEach is not a function. It's worth mentioning that I've used this method ...

Guidelines for sending a personalized email through the WordPress admin dashboard

Currently, I am working on modifying a small plugin that calculates the deposit amount for an item. After the user pays the deposit, the plugin automatically sends an email to notify them about the successful payment. My goal is to enhance the functionali ...

Experiencing difficulties in displaying a React element that is being passed as a prop

One of my components looks like this: const Chip = (props) => { const ChipIcon = props.icon; let deleteButton = null; if (!props.readOnly) { deleteButton = <Delete style={styles.deleteButton} onTouchTap={props.onRemove} /& ...

Having difficulties in Vue while attempting to access a particular row

I encountered an error message stating Uncaught TypeError: snapShotChnaged.forEach is not a function. My goal is to retrieve specific row data, which is why I am utilizing the doc method. retrieveSpecificDonation() { firestore .collection('d ...

Issue encountered when making several calls with the jQuery Ajax load() function

Hey there! I'm currently in the process of incorporating the jQuery load() method to dynamically load content into a web page based on the input value entered. However, I seem to be encountering an issue where multiple AJAX calls are being made simult ...

Tips for implementing a hover transition effect in the navigation menu

I have a specific query regarding a particular issue that I am unsure how to address but would like to implement on my website. 1) My requirement is that when the parent li element has a child, I want the navigation to remain in a hovered state with the s ...

Issue with MVC HTML Helper DropDownListFor failing to submit the chosen value

I'm facing an issue with jQuery form serialize as it's not sending the value of the drop down list to the controller. The control is able to retrieve the ID and Name from the .cshtml file. HTML-code @using (Html.BeginForm("", "", FormMethod.Pos ...

Tips on moving the first item on the Bootstrap navigation bar to the left side

I have successfully implemented a Bootstrap navigation bar and created a container to display some descriptive text beneath it, as depicted in the image provided. Utilizing the most up-to-date version of Bootstrap has ensured smooth integration. https://i ...

Creating a texture in Three.js using an image file

Having some difficulty with creating a texture from an image file using Three.js. Currently, attempting to create a mesh using the following function: var image = document.createElement('img'); image.src = imageFile; var texture = ne ...

Replace a string in an array using JavaScript

I may be overlooking something very obvious, but here is my dilemma. I am trying to convert [ 'hr' ] into [ '* * *' ]. This is what I tried: var hr = jsonml[i] console.log(hr) // outputs: [ 'hr' ] hr.replace(/hr/g, '* * ...

Angular allows for the creation of a unique webpage layout featuring 6 divs

I am working on a project where I have an image of a car and I need to overlay 6 divs onto the image which can be selected with a mouse click. When a user clicks on one of the divs, it should change color. I've attempted using z-index, but it doesn&ap ...

Is there a Node.js method that is similar to jQuery AJAX's .complete() function

In the process of creating a Node.js API to enroll a user in a different web application, I encountered an issue. As part of the registration flow, the API called by the Node app using request is being redirected with a status code of 301 to another API to ...

Tips for retrieving the user-input value from an HTML text field

Exploring the world of JS, I set out to create a basic calculator after just one week of lessons. However, I hit a roadblock when trying to extract user-input values from my HTML text fields. Here's a snippet of my html: <div class="conta ...