SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2006
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript to hide divs.

    I have a javascript function which I'm using to toggle on and off certain divs on a page when an object is moused over.

    This function in turn calls another function (hideAllFriendNames) which hides any of the divs that might be already being displayed - as I only want one div displayed at a time:

    Code:
    function toggleFriendName(theDiv)
    {	
    	hideAllFriendNames();						
    	var elem = document.getElementById(theDiv);
    	elem.style.display = (elem.style.display == "none")?"":"none";
    }
    
    function hideAllFriendNames()
    {
    	hideDiv('friendName1');					
    	hideDiv('friendName2');					
    	hideDiv('friendName3');					
    	hideDiv('friendName4');					
    	hideDiv('friendName5');					
    	hideDiv('friendName6');					
    	hideDiv('friendName7');					
    	hideDiv('friendName8');					
    	hideDiv('friendName9');					
    	hideDiv('friendName10');					
    	hideDiv('friendName11');	
    	hideDiv('friendName12');					
    	hideDiv('friendName13');					
    	hideDiv('friendName14');													
    }
    
    function hideDiv(theDiv)
    {
    	var elem = document.getElementById(theDiv);
    	elem.style.display = "none";
    }
    The problem with the code is that there can be any number of friendName div tags (up to a fixed maximum amount), and we will not know beforehand how many there will be, so we cannot define them as above.

    Is there a way of re-writing this code to allow for any number of friendName div tags? I know what the maximum number could be so could I just modify the hideDiv function so that it checks the div exists first before trying to hide it - how would I do this?

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Shiny, try this:

    Code:
    function hideAllFriendNames()
    {
      for (var i = 1; hideDiv('friendName' + i); ++i) { ; }
    }
    
    function hideDiv(theDiv)
    {
      var elem = document.getElementById(theDiv);
      if (elem) {
        elem.style.display = "none";
        return true;
      }
      return false;
    }

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2006
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks!


Bookmarks

Posting Permissions

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