Function is not running when page loads [closed]

0

The JavaScript code below should display an alert window with the phrase "Hello World!" when the page index.html was loaded, but this does not happen ... Page content loads, but the function does not execute.

var main = function () {
  'use strict';

alert("Hello World!");
};

$(document).ready(main);

Could anyone tell me what's wrong with her?

var main = function () {
  'use strict';

alert("Hello World!");
};

window.onload = main;
<!DOCTYPE html>
<html>
  <head>
    <title>A Simple App</title>
    <link rel="stylesheet" href="style.css" media="screen" title="no title" charset="utf-8">
  </head>

  <body>
    <header>
    </header>

    <section class="comment-input">
      <p>Add Your Comment:</p>
      <input type = "text"><button>+</button>
    </section>
    
    <section class="coments">
      <p>This is the first comment!</p>
      <p>Here's the second one!</p>
      <p>And this is one more.</p>
      <p>Here is another one.</p>
    </section>

    

    <script scr="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script scr="app.js"></script>

  </body>
</html>
    
asked by anonymous 23.12.2014 / 01:18

1 answer

4

Your code works perfectly, see the example below:

var main = function() {
  'use strict';

  alert("Hello World!");
};

$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Now,ifyoudonothavejQueryloaded,you'llgetanerrorlike:

  

ReferenceError:$isnotdefined

ThiswillcausetheJavaScriptcodeonyourpagetostopworking.

YoushouldincludejQuerybeforethiscodeisread:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><scripttype="text/javascript"> var main = function() { 'use strict'; alert("Hello World!"); }; $(document).ready(main); </script>

In case you are not using jQuery, you have to change your code as follows:

$(document).ready(main); // documento pronto

You should move to:

window.onload = main;    // documento pronto JavaScript puro

Example:

var main = function() {
  'use strict';

  alert("Hello World!");
};

window.onload = main;
    
23.12.2014 / 01:32