0

When trying to invoke a JavaScript function of a .js file from .html file the function doesn't being invoked.

Project hierarchy:

  • html (folder)
    • main.html
  • js (folder)
    • script.js

Example #1 - using .html - Works

main.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Main page</title>
    </head>
    <body>
        <label id="label1"></label>
        <input id="text1" type="text"/>
        <button onclick="document.getElementById('label1').innerHTML = document.getElementById('text1').value">Button</button>
    </body>
</html>

Example #2 - using .html and .js - Doesn't work

main.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Main page</title>
    </head>
    <body>
        <label id="label1"></label>
        <input id="text1" type="text"/>
        <button onclick="outputInput()">Button</button>

        <script src="/js/script.js"></script>
    </body>
</html>

script.js

function outputInput(){
    document.getElementById('label1').innerHTML = document.getElementById('text1').value;}
5
  • 1
    Could be several things. It would be very helpful if you checked for any error in the JavaScript console and made sure that the script is loaded. Commented Nov 21, 2015 at 22:04
  • 1
    Touffy thank you for your answer, how could I check for JavaScript errors? I'm using WebStorm by the way. Commented Nov 21, 2015 at 22:06
  • 1
    Open your webpage in a browser. Depending on the browser you may have to enable dev tools. Then find where your browser has the developer tools / JavaScript console / WebKit inspector… the console will probably also show you if there was a 404 error when trying to retrieve the script. Commented Nov 21, 2015 at 22:09
  • 1
    Touffy thank you for your replay, I navigated to "script" tab when inspecting elements while running the .html and the following error occurred: Failed to load resource: the server responded with a status of 404 (Not Found). I am using Chrome. Commented Nov 21, 2015 at 22:14
  • 3
    Well then, I suspect that your absolute URL in the src attribute is the culprit. Try "../js/script.js" Commented Nov 21, 2015 at 22:15

1 Answer 1

1

In your <script src="/js/script.js"></script>, you're using an absolute URL. Based on further testing, it appears that your "js" folder is not at the root of your website and so it is not found there. Using a relative URL src="../js/script.js" is more tolerant about where you put things.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.