Dan Wier
Dan Wier

Reputation: 344

Passing reference to object javascript function

I have a function that gets called during a control update where 'This' is passed so the function knows what control is updating. I am also calling the function at page load to get initial values but sending document.getElementById() doesn't seem to work. What should I be passing here?

For example:

    <script type="text/javascript">

    window.onload = function () {
        alert("Got to window.onload");
        materialSelectionChange(document.getElementById('SquaresDropDownList'));

    };


</script>

in the js file...

function materialSelectionChange(obj) {

alert("Got into function");
}

Also, it does fire the js function on change properly

EDIT

The problem seems to be the load time of the JS document. The function wasn't successfully being called at that point because apparently the JS file hadn't finished loading. Likely because of window.onload. It works if I move the function into the page rather than in the JS file. Is there a way I can add delay so I know the page and it's components are fully loaded?

Upvotes: 1

Views: 59

Answers (3)

user2575725
user2575725

Reputation:

You are not delegating for window load event, you are invoking it, also your missing quotes around the id:

window.onload = myFunction(document.getElementById(typeSelect));

Try wrapping it around:

window.onload = function() {
     myFunction(document.getElementById('typeSelect')); //id in quotes
};

EDIT

You must take care of js file import, import must be first before invoking the function within:

<script src='your-script-file.js'></script>

<script type="text/javascript">
    window.onload = function () {
        materialSelectionChange(document.getElementById('SquaresDropDownList'));
    };
</script>

Upvotes: 4

Dan Wier
Dan Wier

Reputation: 344

The problem seems to be the load time of the JS document. The function wasn't successfully being called at that point because apparently the JS file hadn't finished loading. It works if I move the function into the page rather than in the JS file. Is there a way I can add delay so I know the page and it's components are fully loaded?

Upvotes: 0

Chad Hedgcock
Chad Hedgcock

Reputation: 11775

<select id="typeSelect" onchange="myFunction(this)">

window.onload = function(){
  myFunction.bind(document.getElementById('typeSelect'));
}

Upvotes: 0

Related Questions