" MicromOne: Debugging JavaScript in HTML

Pagine

Debugging JavaScript in HTML

When you’re working on websites, it’s easy for bugs to creep in—especially when messing with the DOM or dealing with unpredictable values. Luckily, browsers like Chrome have us covered with DevTools, an incredibly handy set of tools for debugging.


In this post, I’ll walk you through how to debug JavaScript right inside an HTML page. Plus, I’ve got a simple, testable example to make things clearer.


Since JavaScript runs directly in the browser, even small mistakes can cause big issues with how your page looks or behaves. Bugs like typos, undefined variables, or DOM mishaps can all throw a wrench in the works. Debugging helps you:


- Find out exactly where your code is going wrong

- Understand how your functions are working under the hood

- Watch variables and values change in real time


html

<!DOCTYPE html>

<html>

<head>

  <title>JavaScript Debugging Example</title>

</head>

<body>

  <h2>Random ID Generator</h2>

  <button onclick="generateId()">Generate ID</button>

  <p id="output"></p>


  <script>

    function e(randomize) {

      var t = (Math.random()).toString(16) + "000000000";

      return randomize ? t.substr(2, 4) + "-" + t.substr(6, 4) : t.substr(2, 8);

    }


    function generateId() {

      // Hit the debugger to pause execution here

      debugger;

      let id = e() + "-" + e(true) + "-" + e(true) + "-" + e();

      document.getElementById("output").textContent = "Generated ID: " + id;

    }

  </script>

</body>

</html>


OR


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>Debugging formRTMscript.js</title>

</head>

<body>

  <h2>Script Debug Example from formRTMscript.js</h2>

  <button onclick="runScript()">Run Script</button>

  <p id="output"></p>


  <script>

    // This is the same function logic from your image

    function e(t) {

      var r = (Math.random()).toString(16) + "000000000";

      return t ? "-" + r.substr(0, 4) + "-" + r.substr(4, 4) : r.substr(0, 8);

    }


    function runScript() {

      debugger; // Step into here using DevTools

      var id = e() + e(true) + e(true) + e();

      document.getElementById("output").textContent = "Generated: " + id;

    }


    //# sourceURL=formRTMscript.js

  </script>

</body>

</html>