views:

167

answers:

1

I'm trying to create my own plugin. But I'm having trouble getting things right. It appears when I'm trying to traverse inside .each things go wrong.

I'm trying to go to the next item every 6 seconds by fading.

jQuery(function($){
    $.fn.rotator = function(options){
        this.each(function() {
            var container = $(this);
            var images = container.children();
            //Set the opacity of all images to 0
            images.css({opacity: 0.0});

            //Get the first image and display it (gets set to full opacity)
            $('div:first',this).css({opacity: 1.0}).addClass('show');

            //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
            var obj = $(this);
            setInterval(nextimage(obj),6000);

        }); 
    };
    // rotate function
    function nextimage(obj) {
        var container = $(obj);
        var images = container.children();
        //Get the current image
        var current = (images.hasClass('show')?  images.hasClass('show') : images.first());

        //Get next image, when it reaches the end, rotate it back to the first image
        var next = ((current.next().length) ? ((current.next().hasClass('show')) ? images.first() :current.next()) : images.first());   

        //Set the fade in effect for the next image, the show class has higher z-index
        next.css({opacity: 0.0})
        .addClass('show')
        .animate({opacity: 1.0}, 1000);

        //Hide the current image
        current.animate({opacity: 0.0}, 1000)
        .removeClass('show');
    };
});

$(document).ready(function(){

    $("#bg").rotator({
    })
});

The error I get is: current.next is not a function Line 35

Line 35 =

var next = ((current.next().length) ? ((current.next().hasClass('show')) ? images.first() :current.next()) : images.first());

Can someone tell me what I'm doing wrong?

+1  A: 

On line 31:

var current = (images.hasClass('show')?  images.hasClass('show') : images.first());

current is either getting assigned a boolean or a jQuery object. My guess is that error is thrown when current gets a boolean (caused by current.next().length returning zero). .next() is a jQuery method, it cannot be called on a boolean.

karim79
ye, make it: `($('.show',images).length? $('.show',images) : images.first())`and you don't need var `container = $(obj);` as it's already a jQuery object
Zlatev