Bill
Bill

Reputation: 11

Why my javascript file doesn't load?

This is the code of my html file:

<html>
    <head>
        <script type="text/javascript" src="try1.js"></script>
    </head>

    <body>

        <h1>A Web Page</h1>
        <p id="demo">A Paragraph</p>
        <button type="button" onclick="myFunction()">Try it</button>

    </body>
</html>

And this is the code of my javascript file:

function myFunction() {
     document.getElementById("demo").innerHTML = "Paragraph changed";
}

Upvotes: 0

Views: 5720

Answers (2)

styfle
styfle

Reputation: 24610

Because the element doesn't exist yet. Try putting the javascript at the end of the body

<html>
    <head>
        <title>Example<title>
    </head>
    <body>

        <h1>A Web Page</h1>
        <p id="demo">A Paragraph</p>
        <button type="button" onclick="myFunction()">Try it</button>
        <script type="text/javascript" src="try1.js"></script>
    </body>
</html>

It seems to work just fine when inlining.

   
        <h1>A Web Page</h1>
        <p id="demo">A Paragraph</p>
        <button type="button" onclick="myFunction()">Try it</button>
        <script type="text/javascript">
        function myFunction() {
            document.getElementById("demo").innerHTML = "Paragraph changed";
        }
        </script>

Upvotes: 4

frodo2975
frodo2975

Reputation: 11725

The usual way to do this is to wrap your javascript in jquery's document ready function like this. If you're not using jquery, you should check it out, it's really useful.

$( document ).ready(function() {
    console.log( "ready!" );
});

Upvotes: -1

Related Questions