How can I hide DIVS with JavaScript on page load?

  • Context: Java 
  • Thread starter Thread starter Hootenanny
  • Start date Start date
  • Tags Tags
    Javascript
Click For Summary

Discussion Overview

The discussion revolves around how to hide specific div elements with the class name "hans" using JavaScript when a web page loads. Participants explore various approaches to implement this functionality, including the use of a toggle function to show or hide the divs.

Discussion Character

  • Technical explanation
  • Exploratory
  • Debate/contested

Main Points Raised

  • One participant describes their initial attempt to hide divs using a loop and a toggle function, but encounters issues with execution.
  • Another participant suggests ensuring the loop uses the correct length of the elements by storing it in a variable.
  • A different participant proposes using alert statements for debugging to track the flow of execution and identify where the code fails.
  • One participant shares their toggle function and discusses its complexity, suggesting it could be simplified by passing the element directly instead of its ID.
  • Another participant points out that the toggle function should be able to work with the element object rather than just the ID, which could streamline the code.
  • Some participants express uncertainty about the best approach to pass elements to the toggle function, with one suggesting that the class name may not be sufficient for the toggle function's requirements.
  • There is a discussion about the necessity of the toggle function's design, as it is used elsewhere on the site, which leads to some clarification on its intended use.

Areas of Agreement / Disagreement

Participants have differing opinions on the best way to implement the toggle functionality, with some advocating for a simpler approach while others defend the existing structure due to its broader application. No consensus is reached on a single solution.

Contextual Notes

Some participants mention potential issues with the toggle function's reliance on element IDs, which may not align with the initial approach of using class names. There are also discussions about the need for debugging and the effectiveness of different coding strategies.

Hootenanny
Staff Emeritus
Science Advisor
Gold Member
Messages
9,621
Reaction score
9
I have some divs on a web page, with the class name "hans" which I would like to hide with JavaScript when the page loads. The reason I have it set up this way is so that the user can reveal the div's by clicking a link, but if JavaScript is disabled, the div's will be displayed by default. I've written a loop to loop through the document and hide all the divs, but it doesn't seem to be working. All the divs have unique ID's. The toggle() function used below is a function that just toggle's a named div between display:none; and display:block;

Code:
function hideans() {
	var boxes = document.getElementsByTagName("div");
	
	 for(var i=0;i<boxes.length;i++) {
        var boxClass = boxes[i].className;
      
        if(boxClass.match("hans")) {
            toggle(boxes[i]);
        }
    }
}

Any help would be much appreciated.
 
Technology news on Phys.org
Very very few people have JS disabled.

At first glance, I think to get the number of elements for the loop you need to do var num = boxes.length; after getting the list from getelements. Then use num instead of boxes.
 
I don't see any problems with that, although I'm not that familiar with javascript. If you make a sample page and give me the url I'm sure I can locate the problem for you though.

Or you can try to locate the exact problem yourself by inserting alerts with the relevant data as output and see if it coincides with reality. IE:

Code:
function hideans() {
	var boxes = document.getElementsByTagName("div");
         alert('Document contains ' + boxes.length + ' div elements.');

	 for(var i=0;i<boxes.length;i++) {
        var boxClass = boxes[i].className;
         alert('Div #' + i + ' is of class "' + boxClass + '".');
      
        if(boxClass.match("hans")) {
            alert('Div #' + i + ' (class "' + boxClass + '") is a match, toggling now.');
            toggle(boxes[i]);
        }
    }
}

If you get no alert boxes then your code never reaches the hideans() function, if you get all the expected alert boxes then the problem is inside toggle() somewhere.

k
 
Thanks guys, I added the num variable as you suggested Greg. I also implemented the diagnostic alerts that you suggested kenewbie. All goes well until the function calls the toggle function, after which the function fails to execute and the for loop terminates. I've posted the toggle code below. Thanks for your help thus far guys,

Code:
function toggle( whichLayer ){
  var elem, vis;
  if( document.getElementById ) // W3 Standard Compliance
    elem = document.getElementById( whichLayer );
  else if( document.all ) // Old IE
      elem = document.all[whichLayer];
  else if( document.layers ) // Nestscape 4
    elem = document.layers[whichLayer];
  vis = elem.style;

  // if no style.display value

  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.dis
 
"whichLayer" is already an element object, there is no need to go through all the hoops at the beginning of the function. As far as I can tell, this is all you need to do:

Code:
function toggle(e)
{
    e.style.display = e.style.display != '' ? '' : 'none';
}

If you still have trouble, it would be a lot easier to fix this for you if you made a sample document with a few divs and the relevant code in it and put it on a webserver. Sort of a bare bones sample that should work only it doesn't.

k
 
I think I've found the problem. My toggle function takes the element ID as an argument, however, my hideans() function only provides the class name. Is there anyway to loop though all the elements with a given class name I've already found and find their ID?
 
Hootenanny said:
I think I've found the problem. My toggle function takes the element ID as an argument, however, my hideans() function only provides the class name. Is there anyway to loop though all the elements with a given class name I've already found and find their ID?

I'm pretty sure it's just a “.id” property on the element object.

The http://www.visibone.com/javascript/" are really handy for this stuff; you should buy them if you use them, of course, but he provides full images of the charts themselves on his site.
 
Last edited by a moderator:
CaptainQuasar said:
I'm pretty sure it's just a “.id” property on the element object.
That's great, thanks a lot! For those who are interested, here's the complete code,

Code:
function toggle( whichLayer ){
  var elem, vis;
  if( document.getElementById ) 
    elem = document.getElementById( whichLayer );
  else if( document.all )
      elem = document.all[whichLayer];
  else if( document.layers )
    elem = document.layers[whichLayer];
  vis = elem.style;
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function hideans() {
	var boxes = document.getElementsByTagName("div");
	var num = boxes.length;
	 for(var i=0;i<num;i++) {
      
        if(boxes[i].className.match("hans")) {
            toggle(boxes[i].id);
        }
    }
}

window.onload = function() {
        hideans();
}
 
You are doing this overly elaborate. boxes is a DOM element, why not just send that to toggle() rather than go out of your way to pass boxes.id and then transform it back to a DOM element?

Code:
function toggle( elem ) {
  vis = elem.style;
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function hideans() {
	var boxes = document.getElementsByTagName("div");
	
        for(var i=0;i<boxes.length;i++) 
        if(boxes[i].className.match("hans")) toggle(boxes[i]);
 }

k
 
  • #10
The reason I have my toggle() function set up as shown, is that it's used elsewhere on the site where I need it to take an element Id as an argument. Thanks for your help by the way.
 
  • #11
Hootenanny said:
The reason I have my toggle() function set up as shown, is that it's used elsewhere on the site where I need it to take an element Id as an argument.

Ahh ok, that explains it :)

k
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K