Search code examples
javascriptjquerycheckboxswitchery

Jquery / JavaScript boostrap Switchery clearInterval doesn't work


I have a boostrap switchery on my site:

<div class="form-group">
        <label class="checkbox-inline checkbox-right checkbox-switchery switchery-sm">
                <input type="checkbox" class="switchery" id="test55">
                    Live
        </label>                                
</div>
<div id="tableHolder"></div>

I want to achive this:

  1. on page load load external page into "tableHolder" div.
  2. Switchery is default turned off.
  3. When you click on switchery, load the same external page, but with div resfresh every 5 seconds.
  4. If you turn off switchery, show only loaded external page, without resfresh interval.

I'm having troubles, because everything works ok, but when i press switchery to off, the div still keeps refreshing, so clearInterval doesnt' work :(

Here is my script:

<script type="text/javascript">
 $(document).ready(function () {
   $('#tableHolder').load('external.php?name=myId001')
   var documentInterval = 0;
   $('#test55').change(function () {

     if ($(this).prop("checked")) {

       documentInterval = setInterval(function () {
         $('#tableHolder').load('external.php?name=myId001')
       }, 3000);

     } else {

       clearInterval(documentInterval)
     }
   });
 });
</script>

Solution

  • Use click, not change function.

    $(document).ready(function() {
        $('#tableHolder').load('external.php?name=myId001');
        var elem = document.querySelector('#test55');
        var init = new Switchery(elem);
        var documentInterval = 0;
        var clickCheckbox = document.querySelector('#test55');
        $(document).on('click', '#test55', function() {
            if ($(this).prop("checked")) {
            documentInterval = setInterval(function() {
                $('#tableHolder').load('external.php?name=myId001');}, 3000);
            } else {
              clearInterval(documentInterval);
            }
        });
    });
    

    Sample fiddle here . This will append some text to the div as when switch is on and will stop appending when switch is turned off. If you change the 'click' event to 'change' event the text appending will continue even when the switch is off