3

I have the following code. How do I run this in VS Code with the debugger. I installed and tried live-server but maybe not doing it correctly.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button>Test</button>
  <script src="index.js"></script>
</body>
</html>

index.js

var button = document.querySelector('button');
var fn = () => console.log(this)

function fn() {
  console.log(this);
}

button.addEventListener('click', fn)

3 Answers 3

8

You can install the following extensions.

  1. Live Server.
  2. Chrome Debugger.

Once you have these two extensions installed, open the page index.html using the live server and then press F12 to open the developer tools for chrome.

And then you can paste a single line of code on the debugger like this.

document.querySelector('button').addEventListener('click',()=>{
     console.log("Event Raised");
};
Sign up to request clarification or add additional context in comments.

1 Comment

Interestingly if the server is running on my desktop PC and i connect using 192.168.0.xx:someport then I still get the error, so really it must be a localhost not just a live server...
1

You can do like this

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button>Test</button>
  <script>
    const button = documnet.querySelector("button")
    if(button) {
       button.addEventListener("click", () => {
          console.log("This Works")
       })
    }
  </script>
</body>
</html>

Comments

1

You can run live server but I suggest you to use lite-server library.


  1. Run this command in terminal inside project folder to initialize project with npm init -y

  2. Add lite-server to your devDependencies with npm install lite-server --save-dev

  3. Add start command to run server to package.json

    "scripts": { "start": "lite-server" },

To start server use npm start

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.