lawrencehagman
lawrencehagman

Reputation: 493

css transition on element with value being set with javascript

I have a style sheet with a transition defined for an element and some template html code. If I delay the setting of the attribute I want to transition in javascript it works fine but not without the delat. I assume it's because both are evaluated at the same time. Is there a better way I should be doing this?

<html>
<head>
<style> 
div {
  width:0%;
  height: 100px;
  background: red;
  transition: width 2s;
}
</style>
<script>
/*
//this does work
setTimeout(()=>{
document.querySelector("div").style.width="100%";},1000);
*/

//this does not work
document.querySelector("div").style.width="200%";}
</script>
</head>
<body>

<h1>The transition Property</h1>

<p>Hover over the div element below, to see the transition effect:</p>
<div></div>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>

</body>
</html>

Upvotes: 0

Views: 29

Answers (1)

ray
ray

Reputation: 27275

It doesn't work because the div doesn't exist when your code runs. (It runs before the div is rendered.) Move the script to the bottom of the body or wrap it in an event listener so it runs when your page is fully loaded.

Also: You have an extraneous } at the end of that line which may be preventing it from running at all.

<html>

<head>
  <style>
    div {
      width: 0%;
      height: 100px;
      background: red;
      transition: width 2s;
    }
  </style>
  <script>
    /*
    //this does work
    setTimeout(()=>{
    document.querySelector("div").style.width="100%";},1000);
    */

    // wait for the page to load before running.
    window.addEventListener('load', () => {
      document.querySelector("div").style.width = "200%";
    })
    
  </script>
</head>

<body>

  <h1>The transition Property</h1>

  <p>Hover over the div element below, to see the transition effect:</p>
  <div></div>

  <p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>

</body>

</html>

Upvotes: 2

Related Questions