difference between calling javascript function on body load or directly from script.

Posted by Abbas on Stack Overflow See other posts from Stack Overflow or by Abbas
Published on 2011-02-28T06:46:31Z Indexed on 2011/02/28 7:24 UTC
Read the original article Hit count: 280

Filed under:
|

i am using a javascript where in i am creating multiple div (say 5) at runtime, using javascript function, all the divs contain some text, which is again set at runtime, now i want to disable all the divs at runtime and have the page numbers in the bottom, so that whenever user clicks on the page number only that div should get visible else other should get disable, i have created a function, which accepts parameter, as page number, i enable the div whose page number is clicked and using a for loop, i disable all the other divs, now here my problem is i have created two functions, 1st (for adding divs and disabling all the divs except 1st) and writing content to it, and other for enabling the div whose page number is clicked, and i have called the Adding div function on body onload; now first time when i run, page everthing goes well, but next time when i click on any of the page number, it just gets enabled and again that AddDiv function, runs and re-enables all the divs..

Please reply why this is happening and how should i resolve my issue...

Below is my script, content for the div are coming using Json.

<body onload="JsonScript();">
<script language="javascript" type="text/javascript">
        function JsonScript()
        {
            var existingDiv = document.getElementById("form1");
            var newAnchorDiv = document.createElement("div");
            newAnchorDiv.id = "anchorDiv";

            var list = { "Article": articleList };
            for(var i=0; i < list.Article.length; i++)
            {
                var newDiv = document.createElement("div");
                newDiv.id = "div"+(i+1);
                newDiv.innerHTML = list.Article[i].toString();
                newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a>&nbsp;";
                existingDiv.appendChild(newDiv);
                existingDiv.appendChild(newAnchorDiv);
            }

            for(var j = 2; j < list.Article.length + 1; j ++)
            {
                var getDivs = document.getElementById("div"+j);
                getDivs.style.display = "none";
            }
        }
       function displayMessage(currentId) {
            var list = {"Article" : articleList}
            document.getElementById("div"+currentId).style.display = 'block';
            for(var i = 1; i < list.Article.length + 1; i++)
            {
                if (i != currentId)
                {
                    document.getElementById("div"+i).style.display = 'none';
                }
            }
        }
    </script>    

Thanks and Regards

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about onload-event