Issue
I've been working on changing the src attribute to change the image in javascript. I was using window.onload = function()
and my code wasn't working. I decided to take out window.onload
and miraculously my code worked. The src
attribute changed the image on the page.
A lot of literature I read boasted about window.onload function as though it was absolutely necessary to load a web page in order for other code to work. I'm confused because it didn't work for me in this instance. And I recalled a recent college assignment I was working on that didn't work with window.onload function. Here is the script I used with and without window.onload function. Can somebody give me an explanation for this oddity.
window.onload = function(){
function myFunction(){
document.getElementById("myImg").src = "people5.png";
};
};
</script>
</head>
<body>
<img id = "myImg" src="people1.png" width="240" height="240" alt="logo"/>
<button onclick="myFunction()">Click me</button>
Now without window.onload
function myFunction(){
document.getElementById("myImg").src = "people5.png";
};
</script>
</head>
<body>
<img id = "myImg" src="people1.png" width="240" height="240" alt="logo"/>
<button onclick="myFunction()">Click me</button>
Solution
function myFunction(){
document.getElementById("myImg").src = "people5.png";
};
window.onload = myFunction;
or
<body onload='myFunction()' >
Answered By - Bindrid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.