Pregunta

I wrote up code to "Show more" / "Close" for each div and also when I have opened one and then already opened one close first and other open.

Problem is when I press close in same div it reopened it and doesn't close it. I also put in code .not(this), but doesn't really work. Problem is also because scroll to function doesn't work really good.

If I am on first div and just little scroll to second and press close it jumps in middle of text not on top of div like it suppose to.

Here is jquery code:

    $('.cities').each(function(){
    var max = 7;
    var numLi = $(this).find('li').length;
    var list = $(this).find('li:gt(' + max + ')');
    var id = '#' + $(this).attr('id');

    list.hide();
    if(numLi > max){
        $(this).find('ul').append('<a class="more" name="'+id+'">Show more</a>');
    }
    $(this).find('.more').click(function(){
        // zapre vse odprte
        $('.cities').find('li:gt(' + max + ')').not(this).hide('slow');
        $('.cities .more').not(this).text('Show more');

        list.toggle('slow');
        $(this).text($(this).text() == 'Show more' ? 'Close' : 'Show more');  

        $('html,body').animate({scrollTop: $(id).offset().top},'slow');
    }); 
});

And also working example http://jsfiddle.net/B2MXD/1/

¿Fue útil?

Solución

You can use slideToggle().

$('.more').click(function(){
var max = 7;
    $(this).closest("ul").find('li:gt(' + max + ')').slideToggle();
    $(this).text($(this).text() == 'Show more' ? 'Close' : 'Show more');  
});

You dont have to loop through each element to bind events. Simply use $('.more'). to bind events to all the elements with class namemore

Demo

Edit

$('.more').click(function(){
var max = 7;
    $('.more').not(this).each(function(){
        $(this).closest("ul").find('li:gt(' + max + ')').slideUp();
        $(this).text('Show more'); 
    });
    $(this).closest("ul").find('li:gt(' + max + ')').slideToggle();
    $(this).text($(this).text() == 'Show more' ? 'Close' : 'Show more');  
});

Updated fiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top