1

I have a webpage that contains a few ASP.NET panels and JavaScript that is executed when the user clicks a button to expand and collapse the panels. I need to open the panels in the reverse order but using JavaScript reverse() doesn't appear to reverse the order of items stored in components (panels variable).

I have the following JavaScript:

function expandCollapsePanels() 
{
    var collapse = $('#<%= lbltogglePanels.ClientID %>').html() == "Collapse all panels";
    var panels = Sys.Application.getComponents(); //adding .reverse() does not work

    for (var i in panels) 
    {
        panels[i].set_Collapsed(collapse);
    }
}

How can I modify the code above to do this?

5
  • to you want to reverse the order they open or simple reverse the dom order?
    – meo
    May 24, 2012 at 8:24
  • @meo, I want to reverse the order they open
    – Theomax
    May 24, 2012 at 8:25
  • If you put an alert() in your loop to tell you the order they are being processed in and the order is as intended, then you might need to put in a delay between each call to .set_Collapsed. May 24, 2012 at 8:33
  • I tried adding an alert, but it didn't display anything (the code appeared to still execute, however. I added alert(i) in the foreach loop - is that correct?
    – Theomax
    May 24, 2012 at 8:35
  • @aspdotnetuser could you do console.log( panels ); and tell us what it contains?
    – meo
    May 24, 2012 at 8:44

2 Answers 2

3

You could simply loop in the opposite direction:

for (var i = panels.length-1; i>=0; i--) 
{
  panels[i].set_Collapsed(collapse);
}

demo: http://jsfiddle.net/de6NF/1/

2

An easy, but may not be the best, way to do that will be to push the "panels" into an array in the for..in and then call "set_Collapsed" in a for loop using the array.

1
  • 1
    If it is already an array, then for..in is not needed and a for loop will work as shown by you. Also, reverse() should work for an array.
    – Abhijit
    May 24, 2012 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.