Skip to content

Instantly share code, notes, and snippets.

@pierceh89
Created May 22, 2019 16:01
Show Gist options
  • Save pierceh89/36a64fa20ace27aba082626f957dde24 to your computer and use it in GitHub Desktop.
Save pierceh89/36a64fa20ace27aba082626f957dde24 to your computer and use it in GitHub Desktop.
Dynamic DOM changes by ajax, element move by event
<!DOCTYPE html>
<html lang="ko">
<head>
<title>Dynamic DOM example</title>
<style type="text/css">
.content {
width: 100%;
margin-top: 15px;
overflow: auto;
}
.content-box {
border: 1px solid #000000;
width: 33%;
margin: auto;
float:left;
}
.employee-box {
background-color: blanchedalmond;
border: 1px solid #156015;
width: 100%;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="content">
<div class="content-box" id="list1">
</div>
<div class="content-box" id="list2">
<div class="employee-box">
employee_6
</div>
<div class="employee-box">
employee_7
</div>
<div class="employee-box">
employee_8
</div>
<div class="employee-box">
employee_9
</div>
<div class="employee-box">
employee_10
</div>
</div>
<div class="content-box" id="list3">
<div class="employee-box">
employee_11
</div>
<div class="employee-box">
employee_12
</div>
<div class="employee-box">
employee_13
</div>
<div class="employee-box">
employee_14
</div>
</div>
</div>
<script type="text/javascript">
const list1 = document.getElementById("list1")
const list2 = document.getElementById("list2")
const list3 = document.getElementById("list3")
function loadEmployees() {
let xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
let employees = JSON.parse(this.responseText);
let box1 = document.getElementById("list1");
for (let emp of employees) {
box1.innerHTML += createEmployeeElem(emp);
}
addEventToEmployeeElem();
});
xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees");
xhr.send();
}
function createEmployeeElem(employee) {
let html = '<div class="employee-box" id="';
html += employee.id + '">';
html += employee.employee_name;
html += employee.employee_age;
html += employee.employee_salary;
html += '</div>';
return html;
}
function addEventToEmployeeElem() {
let employees = document.querySelectorAll(".employee-box");
for (let emp of employees) {
emp.addEventListener('click', moveToNext);
}
}
function moveToNext(e) {
let self = e.target;
let containerId = e.target.parentNode.id;
if (containerId === "list1") {
// move to list2
list2.appendChild(self);
} else if (containerId === "list2") {
// move to list3
list3.appendChild(self);
} else {
// move to list1
list1.appendChild(self);
}
}
loadEmployees();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment