Search code examples
loopsinvision-power-board

How to create jQuery loop


How could I do loop in this code? I want to make it shorter, #nav_app_page_5 is in foreach and code show in id #nav_app_page_{$pageID}

   <script type='text/javascript'>
       var j = jQuery.noConflict();
            j(document).ready(function() {

           j( 'p:eq(1)' ).show();
           j( 'p:eq(2), p:eq(3), p:eq(4), p:eq(5), p:eq(6), p:eq(7), p:eq(8), p:eq(9), p:eq(10), p:eq(11)' ).hide();

           j( '#nav_app_page_0').click(function(){  

           j( 'p:eq(1)' ).show();

           });
           j( '#nav_app_page_1').click(function(){  

           j( 'p:eq(2)' ).show();
           j( 'p:eq(1)' ).hide();

           });
           j( '#nav_app_page_2').click(function(){  

           j( 'p:eq(3)' ).show();
           j( 'p:eq(2)' ).hide();
           });
           j( '#nav_app_page_3').click(function(){  

           j( 'p:eq(4)' ).show();
           j( 'p:eq(3)' ).hide();

           });

    });
    </script>

Solution

  • I can think of this answer based on the code what you have submitted.

    My assumption is that when the index is X you want to show the

    with #nav_app_page_(X + 1) as the ID and hide the #nav_app_page_(X-1) id element. In that case I can suggest the following code

     for(var idx=0; idx < 3; idx ++){
       j( '#nav_app_page_'+idx).click(function(){  
         if(j( 'p:eq(' + (idx + 1)+ ')' ).length > 0){
           j( 'p:eq(' + (idx+1) + ')' ).show();
         }
         if((idx - 1) >= 0 && j( 'p:eq(' + (idx - 1)+ ')' ).length > 0) {
           j( 'p:eq(' + (idx - 1) + ')' ).hide();
         }
       });
     }
    

    note that before calling the show() or hide(), the code checks whether the element exists or not. In the second condition it checks for non negative index and element existence before calling the hide().

    Hope this helps.