-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
94 lines (77 loc) · 2.13 KB
/
index.js
File metadata and controls
94 lines (77 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const tabs = document.querySelectorAll(".tab");
const codeInputs = document.querySelectorAll(".code");
const preview = document.getElementById("preview");
const error = document.getElementById("error");
const saveButton = document.getElementById("save");
const loadButton = document.getElementById("load");
let activeTabIndex = 0;
let combinedCode = '';
function runCode() {
error.style.display = "none";
preview.contentWindow.document.open();
preview.contentWindow.document.write(combinedCode);
preview.contentWindow.document.close();
}
function updateCode() {
const htmlCode = codeInputs[0].value;
const cssCode = codeInputs[1].value;
const jsCode = codeInputs[2].value;
combinedCode = `
<html>
<head>
<style>${cssCode}</style>
</head>
<body>
${htmlCode}
<script type="text/javascript" "unsafe-inline">${jsCode}</script>
</body>
</html>
`;
}
function saveCode() {
localStorage.setItem(`code-${activeTabIndex}`, codeInputs[activeTabIndex].value);
alert("Code saved!");
}
function loadCode() {
if (localStorage.getItem(`code-${activeTabIndex}`)) {
codeInputs[activeTabIndex].value = localStorage.getItem(`code-${activeTabIndex}`);
updateCode();
runCode();
alert("Code loaded!");
} else {
alert("No saved code found!");
}
}
function setActiveTab(index) {
tabs[activeTabIndex].classList.remove("active");
codeInputs[activeTabIndex].classList.remove("active");
activeTabIndex = index;
tabs[activeTabIndex].classList.add("active");
codeInputs[activeTabIndex].classList.add("active");
codeInputs[activeTabIndex].focus();
}
tabs.forEach((tab, index) => {
tab.addEventListener("click", () => {
setActiveTab(index);
updateCode();
runCode();
});
});
codeInputs.forEach((codeInput) => {
codeInput.addEventListener("input", () => {
updateCode();
runCode();
});
});
saveButton.addEventListener("click", () => {
saveCode();
});
loadButton.addEventListener("click", () => {
loadCode();
});
preview.contentWindow.addEventListener("error", (event) => {
error.innerText = event.message;
error.style.display = "block";
});
setActiveTab(0);
runCode();