简体   繁体   中英

Trying to change div by class every 5 seconds jquery

Good morning,

I am trying to create an array of classes and with a 5 second interval, I would like to add and remove class replacing the current div. This is for a carousel where I currently have the background image changing at this time. I would now like to make my descriptive text alternate in the same way. Can anyone help?

I was thinking an if statement checking the current background could work. Howver I get this error: 'unexpected token {'

$(document).ready(function(){

/* H E A D E R   C A R O S U E L */

    $(function() {
        var headCarosuel = $(".headCarosuel");
        var backgrounds = new Array(
        "url('./img/backgroundVinny1.jpg')","url('./img/backgroundVinny2.jpg')"
        );
        var current = 0;
        function nextBackground() {
        $(".headCarosuel").css("background", backgrounds[current = ++current % backgrounds.length]);
        setTimeout(nextBackground, 5000);
        }
        setTimeout(nextBackground, 5000);
        $(".headCarosuel").css("background", backgrounds[0]);

    if(backgrounds = $("url('./img/backgroundVinny1.jpg')").css() {
        $('.headCarosuelText').removeClass('description2').addClass('description1');
    }
    else {
        $('.headCarosuelText').removeClass('description1').addClass('description2');
    }

    });
});

To do something every 5 seconds in javascript, you can use setInterval, for instance:

setInterval(function(){
  //your code
,5000);

This will run the code every 5000ms or 5s.

Maybe something like this:

var classes = [
  'class1',
  'class2',
  'class3',
  'class4',
  'class5'
]

var classIndex = 0;

function loopClasses() {
  var currentClass = classes[classIndex];

  // loop through classes and remove from element
  for (var i = 0; i < classes.length; i++) {
    $('.element').removeClass(classes[i]);
  }

  // add current class to element
  $('.element').addClass(currentClass);

  // advance or reset loop counter
  classIndex = (classIndex + 1) % classes.length

}

setInterval(loopClasses, 5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM