dream hunter dream hunter - 20 days ago 6
jQuery Question

Is it possible to toggle two classes in every 3 second using Jquery on page load?



$(document).ready(function(){
$('#green').toggleClass(green red).setTimeOut(3000);
$('#red').toggleClass(red green).setTimeOut(3000);
});

.wdr{
width:300px
height:50px;
}
.red{
background-color: red;
}
.wdg{
width:150px
height:100px;
}
.green{
background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="red" class="wdr red">
</div>
<div id ="green" class="wdg green">
</div>





I'm not too experienced with
jquery
. In this code I tried to toggle the colors of two
divs
on every 3 sec.but which is not working as expected.Can anyone help me to fix this?

Answer

You can do this using setInterval. It will run every x milliseconds giving you the desired result.

$(function() {
  setInterval(function() {
    $('#green').toggleClass('green red');
  }, 3000);

  setInterval(function() {
    $('#red').toggleClass('red green');
  }, 3000);
});
.wdr{
  width:300px
    height:50px;
  }
.red{
  background-color: red;
}
.wdg{
  width:150px
    height:100px;
}
.green{
  background-color: green;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="red" class="wdr red">
  test
</div>
<div id="green" class="wdg green">
  test
</div>

You could also ditch jQuery and use classList and it's toggle method for something like this.

const green = document.querySelector('#green');
const red = document.querySelector('#red');

setInterval(() => {
  red.classList.toggle('red');
  red.classList.toggle('green');
}, 3000);

setInterval(() => {
  green.classList.toggle('green');
  green.classList.toggle('red');
}, 3000);