Skip to content

Commit e0e5c15

Browse files
committed
chore: refactor DOM injection logic
1 parent ed4c45e commit e0e5c15

File tree

1 file changed

+25
-33
lines changed

1 file changed

+25
-33
lines changed

src/main.js

Lines changed: 25 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,35 @@
11
import { definitions } from "./data.js";
22

3-
// the left hand side panel that contains the list of
4-
// links to be clicked
3+
// the left hand side panel that contains the list of links to be clicked
54
const sectionLeft = document.querySelector(".section-left");
65

7-
sectionLeft.addEventListener("click", function (e) {
8-
const sectionRight = document.querySelector(".section-right");
9-
10-
const mainText = definitions
11-
.map((item) => {
12-
if (item.title === e.target.id) return item.text;
13-
})
14-
.join("");
15-
16-
const exampleImage = definitions
17-
.map((item) => {
18-
if (item.title === e.target.id)
19-
return '<img class ="images"src="' + item.image + '">';
20-
})
21-
.join("");
22-
23-
const listText = definitions
24-
.map((item) => {
25-
if (item.title === e.target.id) return item.bulletPointItems;
26-
})
27-
.join("");
28-
29-
const bulletPointText = displayTextAsList(listText);
30-
displayContent(sectionRight, mainText, bulletPointText, exampleImage);
31-
});
32-
33-
function displayContent(display, mainText, bulletPointText, exampleImage) {
34-
display.innerHTML = `<div class='def-text'>${mainText}</div><div class="bullet-text">${bulletPointText}</div>${exampleImage}`;
6+
/** Render a DOM element with dynamic props generated by the values
7+
* in definitions
8+
*/
9+
function renderHTML(DOMElement, text, bulletPointText, image) {
10+
DOMElement.innerHTML = `<div class='def-text'>${text}</div><div class="bullet-text">${bulletPointText}</div>${image}`;
3511
}
3612

37-
function displayTextAsList(listText) {
38-
return listText
13+
function renderBulletPointsAsList(bulletPoints) {
14+
return bulletPoints
3915
.split(".")
4016
.slice(0, -1)
41-
.map((item) => `<li class='list'>${item}</li>`)
17+
.map((bulletPoint) => `<li class='list'>${bulletPoint}</li>`)
4218
.join("");
4319
}
20+
21+
// when the user clicks on a link in the left panel update the DOM
22+
sectionLeft.addEventListener("click", function (e) {
23+
const sectionRight = document.querySelector(".section-right");
24+
const selectedValue = e.target.id;
25+
const selectedDefinition = definitions.find(
26+
({ title }) => title === selectedValue
27+
);
28+
29+
const { image: imageUrl, text, bulletPointItems } = selectedDefinition;
30+
31+
const HTMLImage = `<img class ="images"src=${imageUrl}>`;
32+
const HTMLBulletPoints = renderBulletPointsAsList(bulletPointItems);
33+
34+
renderHTML(sectionRight, text, HTMLBulletPoints, HTMLImage);
35+
});

0 commit comments

Comments
 (0)