March 6, 2012

.first('li) select first item in the list not working

Question by ScoVin

Hope you can help, this code is not working. It is selecting the next image ok, but if it is on the last image and there is no ‘next image’ then I want to select the first image in the ‘li’. I’ve added an if condition: if (nextLi.value !==”)… but this doesn’t seem to be working.

    function nextImg(){         
    $('#background').find('img').animate({'opacity': 0}, 500, function (){
        var nextLi = $('.sel').parent().parent().next('li').find('a');

        if (nextLi.value !=='') {
            var nextLiA = nextLi.attr('rel');
            $('#background').find('img').attr({'src':nextLiA});
            $('.sel').appendTo(nextLi); 
        } else {
            var nextLi = $('.sel').parent().parent().first('li').find('a');
            var nextLiA = nextLi.attr('rel');
            $('#background').find('img').attr({'src':nextLiA});
            $('.sel').appendTo(nextLi); 
        }
    });
}

Answer by Starx

Try this. It checks for the size of the li and if not found anything, selects the first.

function nextImg(){         
    $('#background').find('img').animate({'opacity': 0}, 500, function (){
        var li = $('.sel').parent().parent().next('li').find('a'); 

        if(li.length == 0) {
           //if there is not last item  
           li = $('.sel').parent().parent().first('li').find('a'); //get the first item
        } 
        var liA = li.attr('rel');
        $('#background').find('img').attr({'src':liA});
        $('.sel').appendTo(li); 

    });
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!