-1

The anchors in the span tag should change every 5 seconds but nothing happens. I've tested that jQuery works in WordPress with alert("test"); at the top of my js file.

    <div class="img_ad"><span><a class="active"><img src="http://www.test.co.uk/wp-content/uploads/2014/10/client3.png" /></a>
    <a><img src="http://www.test.co.uk/wp-content/uploads/2014/10/client1.png" /></a>
    <a><img src="http://www.test.co.uk/wp-content/uploads/2014/10/client2.png" /></a></span><span></span><span></span>
 </div>

-

jQuery(document).ready(function($) {


  function swapImages(){
      var $active = $('.img_ad').find("span:first").find(".active");
      var $next = ($('.img_ad').find("span:first").find('.active').next().length > 0) ? $('.img_ad').find("span:first").find('.active').next() : $('.img_ad').find("span:first").find('a:first');
      $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
      });
    }

     // Run our swapImages() function every 5secs
      setInterval('swapImages()', 5000);


});

This code doesn't work, i put alert("test"); in the function swapImages() but nothing happens. I think setInterval is not working. How do i solve this?

user892134
  • 3,078
  • 16
  • 62
  • 128

2 Answers2

2

Just pass the function directly:

setInterval(swapImages, 5000);

Passing a string is not a recommended way.


Your code doesn't work because swapImages is not a global function. Passing a string to setInterval -- e..g. "swapImages()" -- requires that the function is globally defined (window.swapImages = function () { ... }).

(function () {
    function foo() {
        console.log(1);
    }
    setInterval("foo()", 100); // foo is not defined
})();

That's why you have to pass the real function or an anonymous function that will call your function.

For the links from JSFiddle, open the dev tools window (press F12) and go to console.

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
0
setInterval(function(){
   swapImages()
},5000);

Try this

Rohit Batham
  • 1,238
  • 1
  • 9
  • 13