views:

56

answers:

2

Hello. I have 30 divs with the same class on the same page. When i'm pressing the title (.pull) the content is sliding up (.toggle_container). When the content is hidden and i'm pressing the title again, the content is sliding down. Also, i want to store the div state inside a cookie. I modified my original code to store the div state inside a cookie but it's not working for all the divs (pull1, toggle_container1, pull2, toggle_container2 [...]), it's working only for the first one (pull0, toggle_container0). What i'm doing wrong?

var increment = 0;
           if ($.cookie('showTop') == 'collapsed') {
               $(".toggle_container" + increment).hide();
            }else {
               $(".toggle_container" + increment).show();
         };
          $("a.pull" + increment).click(function () {
            if ($(".toggle_container" + increment).is(":hidden")) {
               $(".toggle_container" + increment).slideDown("slow");
               $.cookie('showTop', 'expanded');
               increment++;
            } else {
               $(".toggle_container" + increment).slideUp("slow");
               $.cookie('showTop', 'collapsed');
               increment++;
            }
            return false;

          });    
+1  A: 

I haven't tried any of your code, but won't $("a.pull" + increment) = $("a.pull0") ? and I don't see any for loop so the increment 0 selector is the only one that will get executed?

a jquery selector to look at might be http://api.jquery.com/attribute-starts-with-selector/ If you can select divs that have a class that starts with .pull (or whatever) instead of having to bind to 30 different divs then I think your code will be more performant.

DannyLane
It's not working because i'm trying to separate the divs using the number from the end. If i'm using selector and pressing a.pull0, all the divs will slideup. I'm trying to toggle one div at a time, not all the divs.
John Doe
A: 

This is the code:

$('div.toggle_container').each(function() { // Initialise
        var index = this.id.replace(/^\D+/, '');
              $(this).toggle($.cookie('showTop' + index) == 'collapsed');
            });

    $('a.pull').click(function() { //Activate                  
        var index = this.id.replace(/^\D+/, '');
        if ($.cookie('showTop' + index) == 'collapsed') {
        var container = $('#toggle_container' + index).slideDown('slow');
        $.cookie('showTop' + index, container.is(':hidden') ? 'collapsed' : 'expanded');
        }else {
        var container = $('#toggle_container' + index).slideUp('slow');
        $.cookie('showTop' + index, container.is(':visible') ? 'expanded' : 'collapsed');
            }
});
John Doe