Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="index.css" />
    <link
      href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@531&display=swap"
      rel="stylesheet"
    />
    <title>Path finding visualization</title>
  </head>
  <body>
    <nav>
      <button class="start nav" onClick="start()">Start</button>
      <button class="refresh nav" onClick="refresh();">Refresh</button>
      <a
        href="https://github.com/tlylt/path-finding-visualization"
        target="_blank"
        >Repo</a
      >
      |
      <a href="https://dev.to/tlylt/path-finding-visualization-with-just-html-css-javascript-3blj" target="_blank">Article</a>|
      <a href="https://tlylt.github.io/" target="_blank">Author</a>
    </nav>
    <div class="container"></div>
    <div class="explanation">
      <h2>Algo Explanation</h2>
      <div class="tab">
        <button class="tablinks" onclick="openTab(event, 'setup')">
          Set-up
        </button>
        <button class="tablinks" onclick="openTab(event, 'Steps')">
          Steps
        </button>
        <a href="https://youtu.be/K_1urzWrzLs" target="_blank">Reference</a>
      </div>
      <div id="setup" class="tabcontent">
        <p>
          - Every square is a node.<br />
          - Every node is connected to the four nodes on its north, east, south,
          west direction.<br />
          - Initial number on the node is randomly generated and represents the
          difficulty in reaching that node from its surrounding nodes.<br />
          Final number updated on the node is the cost of reaching that node
          from the starting point. Initial cost to every node except the first,
          is infinity.
        </p>
      </div>
      <div id="Steps" class="tabcontent">
        <p>
          1. Starting with the chosen node, update the cost of reachable nodes
          by taking minimum of ( (cost to reach the "coming from" node +
          difficulty to the visiting node), previously updated cost to the
          visiting node), set the "coming from" node as parent if the cost is
          less to come from that node. <br />
          2. Repeat the steps for reachable nodes in the sequence of least cost
          to most cost, until all nodes have been visited.
        </p>
      </div>
    </div>
    <script src="index.js"></script>
  </body>
</html>

              
            
!

CSS

              
                body {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f4f6ff;
  font-family: "Roboto Slab", serif;
}
.container {
  display: grid;
  grid-template-columns: repeat(10, 40px);
  grid-template-rows: repeat(10, 40px);
  grid-row-gap: 13px;
  grid-column-gap: 13px;
}

button {
  width: 7em;
  height: auto;
  color: white;
  border: 4px solid white;
  font-size: 20px;
  background-color: #f7977a;
  cursor: pointer;
  margin-bottom: 1rem;
}
a {
  color: #f7977a;
}
.node {
  background-color: #8bcdcd;
  text-align: center;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.explanation {
  max-width: 55vh;
}

.tab button {
  background-color: #ccc;
}
.tab button.active {
  background-color: #f7977a;
}
.tabcontent {
  display: none;
  border: 1px solid #ccc;
}

@media only screen and (max-width: 600px) {
  body {
    margin-top: 1em;
    font-size: small;
  }
  button {
    border: 4px solid white;
    font-size: 10px;
    text-align: center;
  }
  .container {
    display: grid;
    grid-template-columns: repeat(10, 28px);
    grid-template-rows: repeat(10, 28px);
    grid-row-gap: 8px;
    grid-column-gap: 8px;
  }
}

              
            
!

JS

              
                // Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
} // End getRandomArbitrary

// Create a Node
function createNode(row, col, weight) {
  var node = document.createElement("div");
  node.setAttribute("class", "node");
  node.setAttribute("row", row);
  node.setAttribute("col", col);
  node.setAttribute("cost", Number.POSITIVE_INFINITY);
  node.setAttribute("parent", null);
  node.setAttribute("weight", weight);
  node.innerText = weight.toString();
  return node;
} // End createNode

// Create Board and insert into HTML
function createBoard() {
  var grid = document.querySelector(".container");
  grid.innerHTML = "";
  for (var row = 0; row < 10; row++) {
    for (var col = 0; col < 10; col++) {
      let weight = Math.round(getRandomArbitrary(1, 100));
      let temp = createNode(row, col, weight);
      let shadow = weight / 10;
      temp.style.boxShadow = `${shadow}px ${shadow}px ${shadow}px rgba(0,0,0,0.8)`;
      grid.appendChild(temp);
    }
  }
  // Set start and end node
  var startNode = document.querySelector("div[row='0'][col='0']");
  var endNode = document.querySelector("div[row='9'][col='9']");
  startNode.setAttribute("cost", 0);
  startNode.innerHTML = "start";
  endNode.innerHTML = "end";
  startNode.style.boxShadow = `${0}px ${0}px ${0}px rgba(0,0,0,0.5)`;
} // End createBoard

// Refresh Button
function refresh() {
  var btn = document.querySelector(".start");
  btn.style.visibility = "visible";
  createBoard();
} // End refresh

// Check and update node
function checkNode(row, col, curr, checker, seen, counter) {
  if (row >= 0 && col >= 0 && row <= 9 && col <= 9) {
    var node = document.querySelector(`div[row="${row}"][col="${col}"]`);

    var cost = Math.min(
      parseInt(curr.getAttribute("cost")) +
        parseInt(node.getAttribute("weight")),
      node.getAttribute("cost")
    );
    if (cost < node.getAttribute("cost")) {
      node.setAttribute(
        "parent",
        curr.getAttribute("row") + "|" + curr.getAttribute("col")
      );
      node.setAttribute("cost", cost);
    }
    changeColor(node, counter, cost);
    changeColor(curr, counter, false);
    if (!seen.includes(node)) {
      checker.push(node);
    }
    seen.push(node);
    return node;
  } else {
    return false;
  }
} // End checkNode

// Animate the nodes
function changeColor(node, counter, cost) {
  setTimeout(() => {
    node.style.backgroundColor = "#e5edb7";
    if (cost) {
      node.innerHTML = cost;
    }
  }, counter * 100);
  setTimeout(() => {
    node.style.backgroundColor = "#f1c5c5";
  }, counter * 100 + 100);
} // End changeColor

// Start path-finding
function start() {
  var startNode = document.querySelector("div[row='0'][col='0']");
  var endNode = document.querySelector("div[row='9'][col='9']");
  // Hide button
  var btn = document.querySelector(".start");
  var refreshBtn = document.querySelector(".refresh");
  btn.style.visibility = "hidden";
  refreshBtn.style.visibility = "hidden";
  // Algo here
  var seen = [startNode];
  var checker = [startNode];
  var counter = 1;
  while (checker.length != 0) {
    checker.sort(function (a, b) {
      if (parseInt(a.getAttribute("cost")) < parseInt(b.getAttribute("cost"))) {
        return 1;
      }
      if (parseInt(a.getAttribute("cost")) > parseInt(b.getAttribute("cost"))) {
        return -1;
      }
      return 0;
    });
    let curr = checker.pop();
    // Important to parse string to integer
    let row = parseInt(curr.getAttribute("row"));
    let col = parseInt(curr.getAttribute("col"));
    // Check up down left right
    let nextRow = row + 1;
    let prevRow = row - 1;
    let leftCol = col - 1;
    let rightCol = col + 1;
    let a = checkNode(nextRow, col, curr, checker, seen, counter);
    let b = checkNode(prevRow, col, curr, checker, seen, counter);
    let c = checkNode(row, leftCol, curr, checker, seen, counter);
    let d = checkNode(row, rightCol, curr, checker, seen, counter);
    counter++;
  }

  // Draw out best route
  setTimeout(() => {
    startNode.style.backgroundColor = "#faf0af";
    while (endNode.getAttribute("parent") != "null") {
      endNode.style.backgroundColor = "#faf0af";
      var coor = endNode.getAttribute("parent").split("|");
      var prow = parseInt(coor[0]);
      var pcol = parseInt(coor[1]);
      endNode = document.querySelector(`div[row="${prow}"][col="${pcol}"]`);
    }
  }, counter * 100 + 100);
  // Show refresh button again
  setTimeout(() => {
    refreshBtn.style.visibility = "visible";
  }, counter * 100 + 100);
} // End start

// Algo Explanation tabs | Source https://www.w3schools.com/howto/howto_js_tabs.asp
function openTab(evt, id) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(id).style.display = "block";
  evt.currentTarget.className += " active";
} // End openTab

// Initialize
window.onload = () => {
  createBoard();
  document.querySelectorAll("button")[2].click();
};

              
            
!
999px

Console