Home > Software design >  Adding js inside <head> tag is not working
Adding js inside <head> tag is not working

Time:04-18

this is working code, i found it from somewhere else.

<html lang="en">
  <head>
    <meta charset="utf=8">
    <style type="text/css">
      #posts {
        width: 90%;
        height: 700px;
        margin: auto
      }
      .post {
      width: 100px;
      height: 100px;
      float: left;
      }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  </head>
  <body>
    <div id="posts">
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    </div>
    <script type="text/javascript">
      $(".post").each(function() {
        var color = '#'; // hexadecimal starting symbol
        var letters = ['eee','ddd','ccc','aaa','888','777','666','555']; //Set your colors here
        color  = letters[Math.floor(Math.random() * letters.length)];
        $(this).css("background-color", color);
      });
    </script>
  </body>
</html>

but if i place the js script below <head> tag, it seems js is not working. any reason why js script is working only if we place it inside <body> tag?

<html lang="en">
  <head>
    <meta charset="utf=8">
    <style type="text/css">
      #posts {
        width: 90%;
        height: 700px;
        margin: auto
      }
      .post {
      width: 100px;
      height: 100px;
      float: left;
      }
    </style>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
      <script type="text/javascript">
      $(".post").each(function() {
        var color = '#'; // hexadecimal starting symbol
        var letters = ['eee','ddd','ccc','aaa','888','777','666','555']; //Set your colors here
        color  = letters[Math.floor(Math.random() * letters.length)];
        $(this).css("background-color", color);
      });
    </script>
  </head>
  <body>
    <div id="posts">
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    </div>
  
  </body>
</html>

CodePudding user response:

When browser execute your second script there is no element added to document yet. So You must wrap your second script code with window.onload

  <script type="text/javascript">
      window.onload = () => { 
$(".post").each(function() {
        var color = '#'; // hexadecimal starting symbol
        var letters = ['eee','ddd','ccc','aaa','888','777','666','555']; //Set your colors here
        color  = letters[Math.floor(Math.random() * letters.length)];
        $(this).css("background-color", color);
      });

} 

    </script>
  • Related