Java How can I hide DIVS with JavaScript on page load?

  • Thread starter Thread starter Hootenanny
  • Start date Start date
  • Tags Tags
    Javascript
AI Thread Summary
The discussion revolves around a JavaScript implementation for hiding div elements with the class name "hans" when a webpage loads. The user aims to ensure that these divs are hidden by default if JavaScript is enabled, while remaining visible if JavaScript is disabled. The initial code attempts to loop through all div elements and toggle their visibility using a custom toggle function. However, issues arise when the toggle function fails to execute properly.Key points include suggestions to implement diagnostic alerts to track the execution flow and identify where the problem lies. It is noted that the toggle function originally takes an element ID as an argument, which complicates the process since the hideans function provides class names. A solution is proposed to pass the actual DOM element to the toggle function instead of its ID. The final code adjustments reflect this simplification, allowing the toggle function to directly manipulate the display style of the elements. The discussion emphasizes the importance of clear function parameters and the efficiency of directly working with DOM elements.
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
Views
2K
Replies
4
Views
1K
Replies
5
Views
2K
Replies
2
Views
2K
Replies
1
Views
4K
Back
Top