Search code examples
javascripthtmlonclickbrowserify

Calling a Javascript function from an external js file in the html file


I am unable to call a function from external javascript file in an HTML file. Kindly suggest me where am I making a mistake...

I have updated the js file.

File 1: A.js

    (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
function sayHello(){
    console.log("hello");
}





},{}]},{},[1]);

File 2: index.html

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
<div>
    <button onclick="sayHello()">click Me</button>
    <script type="text/javascript" src="bundle1.js"></script>
  </div>
<div>
  <button type="button">rotate me</button>
</div>
</body>
</html>

Now, Whenever I run the html file, I get an error after clicking the button that sayHello() is not found.

The command: browserify A.js -o bundle1.js

Kindly help me spotting the error!


Solution

  • Change the script type to "text/javascript" or simply omit it as it is no longer needed in HTML5.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    <style>
      article, aside, figure, footer, header, hgroup, 
      menu, nav, section { display: block; }
    </style>
    </head>
    <body>
    <div>
        <button onclick="sayHello()">click Me</button>
        <script type="text/javascript" src="A.js"></script>
      </div>
    <div>
      <button type="button">rotate me</button>
    </div>
    </body>
    </html>