1

I've been teaching myself Javascript for HTML, over the past week. Mainly from w3schools. I'm trying to make two functions - one to run on the body / window onload event, then this will trigger the update function, which will repeat indefinitely, every 10 / 100 steps.

I'm basically making a website that will be heavily controlled by Javascript. I need to create this template, to use for the system I plan to build (Responsive layout + content, with screen resize).

The initial startup function is not affecting any of the divs. Why is this?

<!DOCTYPE html>
<html>
   <head>
      <script>
         //         STARTUP
         function startupClass(classnm)
         {
            // scan through all divs, altering size accordingly.
            classid = document.getElementsByClassName(classnm);

            for(i=0;i<classid.length;i+=1)
            {
               // apply style to each div class
               classid[i].style.position="absolute";
               classid[i].style.width=(screen.availWidth/classid.length);
               classid[i].style.height="300px";
               classid[i].style.top="0px";
               classid[i].style.left=i*(screen.availWidth/classid.length);
               classid[i].style.backgroundColor="#f3f3f3";
            } 

            setTimeout(updateClass(classnm),1);
            }
            // jump to update function (Which then automatically updates, every step)

            //      UPDATE FUNCTION
            function updateClass(classnm);
            {
               setTimeout(updateClass(classnm),10);
            }

            window.onload = startupClass("newclass");
      </script>
   </head>
   <body onload="startupClass('newclass');">
      <div class="newclass"></div>
      <div class="newclass"></div>
      <div class="newclass"></div>
      <div class="newclass"></div>
   </body>
</html>

I'm probably making an obvious mistake, but neither the window.onload, or the body tag onload are triggering the function?

Please forgive me if it's an obvious mistake - I'm very new to Javascript.

ANSWER:

There were a few errors with the syntax - firstly the accidental placement of the semicolon after the updateClass(); {} - then there was an error with the setTimeout() syntax - which was 'setTimeout(updateClass(classnm),1);', changed to 'setTimeout(updateClass,1,classnm);'.

The console no longer threw back any errors - but the divs still weren't being styled. This is because the startupClass() function was running before the divs were placed! In order to fix this, I simply made a very basic function, that then triggered the startupClass function after 1 step:

<head>
<script>
//--------------STARTUP
    function startupClassInit(classnm)
    {
        setTimeout(startupClass,1,classnm);
    }

    function startupClass(classnm)
    {
        // scan through all divs, altering size accordingly.
        classid = document.getElementsByClassName(classnm);
            for(i=0;i<classid.length;i+=1)
            {
                // apply style to each div class
                classid[i].style.position="absolute";
                classid[i].style.width=(screen.availWidth/classid.length)+"px";
                classid[i].style.height="300px";
                classid[i].style.top="0px";
                classid[i].style.left=i*(screen.availWidth/classid.length)+"px";
                classid[i].style.backgroundColor="#AA0000";
            } 
        // jump to update function (Which then automatically updates, every step)
        setTimeout(updateClass,1,classnm);
    }

//--------------UPDATE FUNCTION
    function updateClass(classnm)
    {
        classid = document.getElementsByClassName(classnm);
            for(i=0;i<classid.length;i+=1)
            {

            }
    setTimeout(updateClass,100,classnm);
    }

window.onload = startupClassInit("newclass");
</script>
</head>

This now works fine :) Thank you all for the suggestions and help.

3 Answers 3

1

I really would say, take a look at jQuery.

$(document).ready(function() {
    // some functions
}

this will run the functions or bind functions to elements AFTER the page is load because sometimes you want to add some functionality to elements but they don't exist during the page creating but the function already does :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, before hand, though I'd much prefer to familiarise myself with Javascript - as I plan to learn it, for programming Apps and Games in Unity - as well as websites.
jquery is javascript the only diffrence is, you have kinda extendet function collection...
1

Need to use setInterval instead of setTimeOut.

1 Comment

Ok, but the window.onload should tigger the startupClass function, right? It's not. It should change the divs positions, sizes and background colours, and after that, link to the next function - but it's not affecting the elements styles at all, why is this?
1

First of all, there's an error in your syntax :

function updateClass(classnm);

Remove the semicolon as the function will otherwise contain no body (rendering it as undefined, which is the reason why nothing is happening).

I'd remove the onload-handler of the body as well as you specified the window.onload inside your script tag, essentially firing it twice.

Then the issue of recursion, the "startupClass"-method is invoking a 1 millisecond timeout before calling updateClass, which in turn has a 10 ms timeout before calling itself. What is it you're trying to do here ?

Another thing is the way you assign the callback functions to execute when the timeout has passed, when you type updateClass(classnm) you're actually executing the updateClass function (and returning it's return value to "setTimeout" which in this case is void as the function returns no value), what you want to do is pass the REFERENCE to the function (by using it's name), so you what you should type is :

setTimeout( updateClass, 10, classnm );

This is causing a RangeError as you are repeatedly invoking the method.

You might want to look into setInterval if you wish to repeatedly invoke a handler at a fixed interval without manually calling it upon each invocation.

On a side note : you mention you want to listen to changes in layout size, if this is the sole reason for polling at a fixed interval, it is much more efficient to a add a listener onto the window for the "(on)resize" and "(on)orientationchange" Events which are fired when the window is actually resized by the user. This omits the need for sacrificing CPU cycles in repeated polling and checking whether these events have actually occurred by comparing values.

8 Comments

Yes, the plan is for the setupClass function to run once, on page load, then after the updateClass will run every fraction of a second, just checking for screen size changes, or any variable changes that I choose to monitor, then changing the page layout / content accordingly.
I have just removed the body onload - but I had both to stress that neither are running the startupClass function. - still not!
Can you confirm that no errors are thrown in the console ? Can you add a log statement to the startupClass function to inidicate that it is running ?
Oh! It says: 'Uncaught SyntaxError: Unexpected token ; '
That might just be the semicolon at the end of function updateClass(classnm); removing it should help:)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.