1

I'm having some trouble in trying to get my JS file to work with my HTML file, or at least I think that's the problem. When I run my website, it doesn't change the text to the new text when I click the buttons...

here's the Js file:

    var page = document.getElementById('pageContainer');

    function homepage() {
    page.innerHTML = '<p>This is the main page of the site!</p>';   
    }

   function contactpage() {
   page.innerHTML = '<p>This is the contact page of the site!</p>'; 
   }

   function aboutpage() {
   page.innerHTML = '<p>This is the about page of the site!</p>';   
   }

here's the HTML file:

    <html>
    <head>
        <script src="script.js" type="text/javascript" ></script>
        <link rel="stylesheet" href="style.css">
        <title>alphaEncryption's Website!</title>
    </head>
    <body>
        <h1>Welcome to the website!</h1>
        <h2>have a look around!</h2>
        <button id='home' onclick='homepage()'>Home</button>
        <button id='contact' onclick='contactpage()'>Contact</button>
        <button id='about' onclick='aboutpage()'>About</button>
        <div id='pageContainer'>
          <p id='page'>This is the main page of the site!</p>
        </div>
    </body>
    </html>

How it is now!

Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
James Deal
  • 13
  • 5
  • 1
    Files in same directory? Have you tried src="./script.js" for the js source? – TGarrett Feb 13 '18 at 14:33
  • 3
    "at least I think that's the problem" — Open the Developer Tools in your browser. Look at the Console. **Read the error messages**. – Quentin Feb 13 '18 at 14:36
  • You need to either wrap you javascript in a document ready function or you need to put your javascript inclusion at the end of the HTML document. – Schalk Keun Feb 13 '18 at 14:46
  • it works in jsbin but i agree with the answer below, your js should be at the end of your closing /body tag – iceveda06 Feb 13 '18 at 14:47

1 Answers1

3

It looks like your Javascript will run before the html is loaded. Try to add your script tag just before your closing body tag.