HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<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>
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;
}
}
// 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();
};
Also see: Tab Triggers