Reputation: 135
If i put some script in HTML file to change the animation play state,it's works.But when i put the script in a script file,it's not working.Can anyone tell me why? script like this:
var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++) {
console.log(buttons.length);
buttons[i].onclick=function(e) {
document.getElementById("para")
.style.WebkitAnimationPlayState=e.target.innerHTML;
};
}
Upvotes: 0
Views: 70
Reputation: 93223
Your script dependens on the existing of this Button :
=document.getElementsByTagName("button");
So,
it works because the script has been running after rendering the button .
It does not work because either :
OR
follow this order .
<button>....</button>
.......
<script src="/uri/of/script.js"></script>
onload
listner of window
Upvotes: 1
Reputation: 1
The elements may not be defined in document
. Try placing the existing script within load
event handler of window
function toggleAnimationPlayState() {
var buttons=document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++) {
console.log(buttons.length);
buttons[i].onclick=function(e) {
document.getElementById("para")
.style.WebkitAnimationPlayState=e.target.innerHTML;
};
}
}
window.addEventListener("load", toggleAnimationPlayState);
Upvotes: 1