[RESOLVED]Trying to add onLoad event to div

I have a div that has different div identified by seperate ids. I want to collapse all other div apart from div1 on page load.. am new in javascript

here is the script

          function collapseElement(obj) {
        var el = document.getElementById(obj);
        el.style.display = 'none';
    }
    function expandElement(obj) {
        var el = document.getElementById(obj);
        el.style.display = '';
    }
    function collapsePages() {
        var numFormPages = 2;
        for (i = 1; i <= numFormPages; i++) {
            currPageId = ('page_' + i);
            collapseElement(currPageId);
        }
    }

I know I should add the onLoad event to the body tag.. but there are other ids in the page that is doing a different thing..adding it to the body would collapse/hide all div with an id..

How do I fix this

Approach 1: You can assign a className to the div elements you want to hide when the page loads and then use document.getElementsByClassName() and loop through each element returned by the document.getElementsByClassName() function and set the
display property.

Approach 2: You can use the jQuery to achieve the same result in a neat and simple way. Here is the sample code. Note that probably you can download the jquery js file to your local machine and refer that in the src property of script tag in
the code snippet below.

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
    <div id="1" class="hidden">Div 1</div>
    <div id="2" class="hidden">Div 2</div>
    <div id="3" class="hidden">Div 3</div>
    <div id="4" class="hidden">Div 4</div>
    <div id="5">Div 5</div>
    <script>
        $(".hidden").hide();
    </script>
</body>
</html>

 

Leave a Reply