0

I have this function in my code which works as a slider for elements within a class.
I want to setInterval to it on click event but keeps giving me function is undefined.

Here is my Script:

$(document).ready(function(){
    $(".slide").click(
        setInterval( function fadeNext() {
            $(this).children('div:nth(0)').children('img:nth(0)').fadeOut().appendTo($(this).children("div:nth(1)"));
            $(this).children("div:nth(1)").children('img:nth(0)').fadeIn().appendTo($(this).children("div:nth(0)"));
        },1000)
    );
});
Cerbrus
  • 70,800
  • 18
  • 132
  • 147

2 Answers2

2

In the setInterval functions this belongs to the anonymous function, not the click one. So you need to pass this in the interval. Solution is to use bind on the anonymous function

$(document).ready(function () {
$(".slide").click(function(){
    setInterval(function fadeNext() {
        $(this).children('div:nth(0)').children('img:nth(0)').fadeOut().appendTo($(this).children("div:nth(1)"));
        $(this).children("div:nth(1)").children('img:nth(0)').fadeIn().appendTo($(this).children("div:nth(0)"));
    }.bind(this), 1000)
)
});
});

Or just

$(document).ready(function () {
$(".slide").click(function(){
var _this = this;
    setInterval(function fadeNext() {
        $(_this).children('div:nth(0)').children('img:nth(0)').fadeOut().appendTo($(this).children("div:nth(1)"));
        $(_this).children("div:nth(1)").children('img:nth(0)').fadeIn().appendTo($(this).children("div:nth(0)"));
    }, 1000)
)
});
});
Deepsy
  • 3,769
  • 7
  • 39
  • 71
  • @Satpal No, I wanted to show a solution without bind, but I copied the code in the above example. Notice that I used $(_this) – Deepsy Jun 23 '14 at 12:15
  • 1
    click is expecting a `function`, you havent wrapped your code in a `function` – sabithpocker Jun 23 '14 at 12:17
  • Well I just wanted to show a solution to the problem, which is working. I copied the authors code, so it was a typo. – Deepsy Jun 23 '14 at 12:19
0

May be try something with jQuery delay and fadeOut callback. I havent tested this myself.

$(document).ready(function(){
    $(".slide").click(function () {
            $(this)
                .children('div:nth(0)')
                    .children('img:nth(0)')
                    .delay(1000);
                    .fadeOut(400, function(){
                        $(this).appendTo($(this).children("div:nth(1)"));
                    });
    });
});
sabithpocker
  • 15,274
  • 1
  • 42
  • 75