SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Sep 2012
    0 Post(s)
    0 Thread(s)

    Amend code to work for different situations

    I have found some code (source lost, i'm afraid) that shows and hides divs to give a tabbed approach to a page. One part of the code hides all DIV with an id starting "sec" + an integer (sec1, sec2..).
    My issue is that i want the most efficient code - this sample is hard coded for 3 div (sec1, sec2, sec3) but other pages will have more or fewer divs, so i would like to amend this code to iterate thru all secX divs, no matter how many or few.

    Code is

    if (ng5) document.getElementById('sec1').style.visibility = "hidden"
    else if (ns4) document.sec1.visibility = "hide"
    else if (ie4) ="hidden"
    if (ng5) document.getElementById('sec2').style.visibility = "hidden"
    else if (ns4) document.sec2.visibility = "hide"
    else if (ie4) ="hidden"
    if (ng5) document.getElementById('sec3').style.visibility = "hidden"
    else if (ns4) document.sec3.visibility = "hide"
    else if (ie4) ="hidden"
    Thanks in advance for any help!!

  2. #2
    SitePoint Enthusiast
    Join Date
    Oct 2012
    1 Post(s)
    0 Thread(s)
    That code is terribly outdated... It'll be easier if you use some kind of framework (eg: jQuery).

    However, I'd work with this function:
    Code JavaScript:
    function hideDivs(x){
    	var i = 0;
    	for(i = 1;i <= x; i++){
    		document.getElementById("sec" + i).style.visibility = "hidden";
    You just call this function and pass along the number of divs there are on the page, for example: hideDivs(5).
    I haven't added a check to see if the element actually exists, that's something you can/may add yourself

    If you use jQuery, you can use the following:
    Code JavaScript:
    function hideDivs(){
    	$( "div[id^='sec']").css( "visibility", "hidden" );


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts