Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run html & javascript in VS Code

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)
like image 614
Bill Avatar asked Mar 20 '26 22:03

Bill


2 Answers

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");
};
like image 57
Lakindu Hewawasam Avatar answered Mar 22 '26 11:03

Lakindu Hewawasam


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>
like image 40
Kenedi Novriansyah Avatar answered Mar 22 '26 10:03

Kenedi Novriansyah