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

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

Utilizing JQuery to capture user input in a textarea and showcase it in a span element with key press

Is there a way to capture the user's input and display it in a span above the textarea? Specifically, how can I detect when the user presses the enter/return key (keyCode 13) and correctly insert a line break ( ) in the span? $('#InviteMessage ...

"Utilize Bootstrap Modal to load dynamic content with Ajax and incorporate loading

When I use the Bootstrap Modal to load content from another page, the data is quite complex with multiple queries and dynamic forms. As a result, when the modal opens, it tends to get stuck momentarily. I am looking for some sort of animation or indicator ...

Displaying an additional section using hover effects in Bootstrap

I recently utilized Bootstrap to create pricing tables which can be viewed here: http://www.bootply.com/VyHsJBDoNc Is there a way for me to implement hover functionality on a span element (+ More Information!) that will display additional information as s ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Is it possible to modify state prior to the link being activated in react-router-dom?

I need to gather user information before the link works, but I'm not sure how to do that. The issue is that when I click on the link, the component it's linking to gets activated first without receiving the necessary info. const [userId, setUse ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

Exploring error management in Vue3 and Vite when deploying to production

After following the error handler setup in the Vue documentation, I encountered a difference between using it on the development server and in production. The error handler effectively pinpointed the component and line number where the error occurred durin ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

Incorrect CSS percentage calculations detected on mobile devices

My webpage consists of three large containers, each with an alpha transparent background. While they display correctly on desktop browsers, I'm facing alignment issues on tablets (both iOS and Android) and iPhones where the percentage sum seems to be ...

Incorrect legend colors in Highcharts pie chart

[![enter image description here][1]][1] There seems to be an issue with the Pie-Chart where the Slice color and the Legend color do not match when the color is set using className. This problem does not occur with some other charts. If you look at the co ...

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Implement a loading spinner to display each time a computed method is invoked in a Vue.js

Whenever a checkbox is checked, my filtering method gets triggered. I am trying to implement a loader that displays while the filter process is ongoing and then shows the results. However, I have encountered an issue where the loader remains visible at all ...

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

Do not ask for confirmation when reloading the page with onbeforeunload

I am setting up an event listener for the onbeforeunload attribute to show a confirmation message when a user attempts to exit the page. The issue is that I do not want this confirmation message to appear when the user tries to refresh the page. Is there ...

Creating a Cross-Fade Effect in easySlider 1.7 using the Jquery Plugin

Want to achieve a cross-fade effect in easySlider 1.7 Jquery Plugin? Check out this tutorial Easy Slider 1.7 for guidance. Appreciate any help, thanks! ...

What is the process for embedding HTML and CSS content into an Outlook email?

Has anyone experienced trouble adding an HTML and CSS web page to an Outlook email? I attempted to use the "Insert as text" option, but the CSS file is not loading correctly in Outlook. Any suggestions on how to fix this? The error message states that the ...

Unusual issue with jQuery's AJAX functionality

Utilizing jQuery AJAX, I am fetching data from a PHP page and displaying a loading GIF image in the placeholder to indicate that results are being processed. $(".project").change(function(){ $(".custName").html("<img src='/admin/images ...

Knockout Mapping is causing a complete re-render of all elements

Utilizing the Knockout mapping plug-in to update the UI with JSON data fetched from the server every 3 seconds. The UI contains nested foreach bindings. However, it appears that all elements within the foreach bindings are completely erased and re-rendered ...