How can I hide DIVS with JavaScript on page load?

  • Java
  • Thread starter Hootenanny
  • Start date
  • Tags
    Javascript
In summary, the conversation discusses a problem with hiding specific div elements on a web page using JavaScript. The user has written a loop to hide the divs with a certain class name, but it is not working. Other users suggest adding a variable to count the number of elements and using it in the loop, as well as using diagnostic alerts to locate the problem. It is eventually discovered that the toggle function being used only takes in element IDs, not objects, so the code is adjusted to pass in the element object instead. The conversation also touches on the usefulness of JavaScript reference charts.
  • #1
Hootenanny
Staff Emeritus
Science Advisor
Gold Member
9,623
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
  • #2
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.
 
  • #3
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
 
  • #4
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
 
  • #5
"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
 
  • #6
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?
 
  • #7
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:
  • #8
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();
}
 
  • #9
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
 

1. How can I use JavaScript to hide a specific DIV on my webpage?

To hide a specific DIV on your webpage using JavaScript, you can use the style.display property and set it to "none". This will hide the DIV from view. For example, if your DIV has the id "myDiv", you can use the following code: document.getElementById("myDiv").style.display = "none";

2. Can I use JavaScript to hide multiple DIVS at once?

Yes, you can use a for loop to loop through an array of DIVs and hide each one using the style.display property as mentioned in the previous answer. Alternatively, you can use the querySelectorAll() method to select multiple DIVs and then use a forEach() loop to hide each one.

3. What is the difference between hiding a DIV with JavaScript and setting its visibility to hidden?

When you hide a DIV with JavaScript using the style.display property, the DIV will be completely hidden from view and will not take up any space on the webpage. However, when you set the visibility property to "hidden", the DIV will still take up space on the webpage, but it will not be visible. This means that other elements on the webpage may shift to fill the empty space left by the hidden DIV.

4. How can I make a hidden DIV reappear on my webpage?

To make a hidden DIV reappear on your webpage, you can use the style.display property again and set it to "block" or "inline", depending on the original display property of the DIV. Alternatively, you can also use the style.visibility property and set it to "visible".

5. Is it possible to animate the hiding and showing of a DIV with JavaScript?

Yes, it is possible to animate the hiding and showing of a DIV with JavaScript using CSS transitions or animations. You can set the transition property on the DIV and specify the duration, delay, and other transition properties. This will create a smooth animation when the DIV is hidden or shown using JavaScript.

Similar threads

  • Programming and Computer Science
Replies
8
Views
190
  • Programming and Computer Science
Replies
4
Views
744
  • MATLAB, Maple, Mathematica, LaTeX
Replies
3
Views
275
Back
Top