Reputation: 61
I have a function defined as follows:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
I am trying to call myFunction
from button onclick
in html:
<button onclick="myFunction();"></button>
But it says myFunction
is not defined. I understand because this is inside window.onload
. How can I fix this? I need window.onload
because I need to use document.getElementById("testID")
to get content.
Upvotes: 0
Views: 63
Reputation: 816312
I need window.onload because I need to use document.getElementById("testID") to get content
No, you don't need window.onload
. You simply have to put the code somewhere after the element with ID testID
in the document.
Example:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
However, if you want to keep using window.onload
, then I suggest to not use inline event handlers, but bind the handler with JS:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(that might be a good thing to do anyway).
Lastly, you can get the a reference to the element inside the event handler using this
or event.target
:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
Learn more about event handling.
Upvotes: 4
Reputation: 211560
You defined it within a function
so it's locked to that scope. Maybe you want to define it outside of that:
function myFunction() {
var ids = document.getElementById("idname");
// ...
}
window.onload = function() {
// ...
}
As a note, this is extremely old-school JavaScript. You could clean this up considerably using something like jQuery which would look something like this:
$(function() {
// Any initialization after page load.
});
function myFunction() {
var ids = $('#idname');
// ...
}
Upvotes: 1