INCHMAN1900
INCHMAN1900

Reputation: 135

Script to change animation play state

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

Answers (2)

Abdennour TOUMI
Abdennour TOUMI

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 :

    • Fail to import script. (check browser's console)

OR

  • Import the script BEFORE rendering the button .

Solution :

  • follow this order .

      <button>....</button>
         .......
      <script src="/uri/of/script.js"></script>
    
    • OR, run your code inside onload listner of window

Upvotes: 1

guest271314
guest271314

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

Related Questions