0

i want to log some value onto console on clicking a button by reading the function from scripts.js file from index.html file.

below is my code,

within index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title></title>
        <link rel="stylesheet" href="src/styles.css">
        <script src="src/scripts.js"></script>
    </head>
    <body>
        <button onClick="data()">click</button>
    </body>
</html>

within scripts.js file

function data() {
    const data = "3";
    console.log('data');
}

in doing this, i get error like below,

"uncaught reference error: data is not defined at HTMLButtonElement.onclick"

not sure what is causing the problem. could someone help me with this. thanks.

EDIT:

in the source tab i see this

enter image description here

in the networks tab i see scripts.13aae5c5.js file being called.

enter image description here

EDIT2:

i have tried to create a div with id message and change its content with js code in scripts.js file and it works.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="src/styles.css">
</head> 
<body>
    <h2>here i am </h2>
    <div id="message"></div>
    <script src="src/scripts.js"></script>
    <button onclick="data">click</button>
</body>

in scripts.js file

function data() {
    console.log('data');
}

document.getElementById('message').innerText = "Hello World!";

it displays hello world message but on clicking button it says uncaught reference error data not defined

  • 2
    The script itself works, altough you try to log a static `"data"` string instead of the actual value of `const data`. The path to your external script file (=`src/scripts.js`) seems to be incorrect, by which `data()` is `undefined`. – Lain Oct 12 '20 at 09:20
  • Also if you mean to log `data` variable you need to use `console.log(data);` instead of your version. – maveriq Oct 12 '20 at 09:21
  • As @Lain said, check the path of the included script file. – André Oct 12 '20 at 09:23
  • thanks. scripts.js file is within src folder and index.html file outsides src folder. so path seems to be correct? – stackoverflow_user Oct 12 '20 at 09:23
  • Check the console and/or the network tab, if using chrome. Both will show whether the file gets found or not. In older browser `script` also requires `type`, `language` attributes. – Lain Oct 12 '20 at 09:24
  • i see the scripts.js file in the source tab. i have added the image to the question. i am also using parcel as development server. – stackoverflow_user Oct 12 '20 at 09:28
  • **304** is not modified. Perhaps and old cached version of your script file. Tick *Disable Cache* and reload the site. – JavaScript Oct 12 '20 at 09:42
  • thanks but it is still the same. i have tried to modify html content of div with id message and added its js code in scripts.js file and it worked. but calling the data function doesnt work. i have added to question what i tried. – stackoverflow_user Oct 12 '20 at 09:46

1 Answers1

1

Basicly there is nothing wrong here, exept you should considder binding your events in JS. BUT: This looks like you have some sort of preprocessor, like webpack or browserify, active at your project.

The preprocessors or packer will wrap your code in a seperate scope to prevent filling up the global space.

a small example:

// the code:

function data() {
  return 'some data'; 
}

// will be converted to something like this (Boiled down for understanding)

(function(){
  function data() {
    return 'some data'; 
  }
})()

The (function(){ ... })() is called a self executing function and will provide a encapsulation to your code. What is the purpose of a self executing function in javascript?

<button onClick="data()">click</button> on the other side will need method data in the global scope, or to be exact: window.data has to be set!

so you have two options right here:

  • bind the data method to the global scope
  • bind your event using js

function data() {
  console.log('call to data');
}
// bind to global scope (not nice!)
window.data = data;

// onload method
function onload() {
  console.log('onload');
}
window.onload = onload;


// bind event using JS (Waaaay nicer!)
// wait for Dom is loaded: https://developer.mozilla.org/de/docs/Web/Events/DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
  onload();
  // get the element
  const button = document.getElementById('test');
  if(button) {
    // bind event
    button.addEventListener('click', data)
  }
})
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title></title>
        <link rel="stylesheet" href="src/styles.css">
        <script src="src/scripts.js"></script>
    </head>
    <body onload="onload()">
        <button id="test" onClick="data()">click</button>
    </body>
</html>
Bellian
  • 2,009
  • 14
  • 20
  • thanks for the explanation. but one doubt when i click the button it seems like calling data method twice. also do we need to call this data method with onclick attr when we have click eventlistener added? – stackoverflow_user Oct 12 '20 at 09:59
  • also how can i call this data method onload attr for body tag? but this gives undefined. thanks – stackoverflow_user Oct 12 '20 at 10:05
  • Haha yea. it is called twice, since at this example it is bound twice, since i wanted to show you both ways ;) Pick one aproach for yourself (please let it be the second one) – Bellian Oct 12 '20 at 10:05
  • 1
    Well like the `DOMContentLoaded` event you can also bind the `load` event in code: `document.addEventLiestener('load', data)` please read up on ebent binding here: https://developer.mozilla.org/de/docs/Web/API/EventTarget/addEventListener – Bellian Oct 12 '20 at 10:08
  • thanks for the reply. but then calling the data method in the body tag onload gives the same error. not sure how to call that – stackoverflow_user Oct 12 '20 at 10:08
  • Like you see in the example. i have updated the onload event stuff. Please be shure to define the callbacks outside the `DOMContentLoaded`, read up on JS events and try to understand what you are doing. – Bellian Oct 12 '20 at 10:13
  • thanks a ton. really nice explanation. thanks for your help. – stackoverflow_user Oct 12 '20 at 10:18