Last active
April 21, 2020 00:32
-
-
Save irian-codes/30124c7e7571046f491a7aa07852a165 to your computer and use it in GitHub Desktop.
HTML with JavaScript that grows a list dynamically every time arr.push() is called.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>JS dynamic list grow</title> | |
</head> | |
<body> | |
<h1>DYNAMIC LIST</h1> | |
<ul id="dynlist"> | |
</ul> | |
<!-- <script src="./script.js"></script> --> | |
<script> | |
// Answer from: https://stackoverflow.com/questions/5306843/attach-event-listener-to-array-for-push-event | |
const dynlist = document.getElementById("dynlist"); | |
const arr = [1, 2, 3, 4, 5]; | |
adaptList(dynlist, arr); | |
var eventify = function (arr, callback) { | |
arr.push = function (e) { // Here we are replacing the built in Array.push() method with our own. So like overriding a method. | |
Array.prototype.push.call(arr, e); // Here we are calling the normal Array.push() method, aka the base method. Passing arr as this and e as the element we want to push into. | |
callback(arr); // This is the key. Here we are calling the function we pass as 'callback' parameter. So essentially we have created an event. The 'arr' parameter is now the array with the element pushed since we called base.push the previous line. | |
}; | |
}; | |
eventify(arr, function (updatedArr) { | |
adaptList(dynlist, updatedArr); | |
}); | |
function adaptList(list, arr) { | |
list.innerHTML = ''; | |
arr.forEach(el => { | |
let newNode = document.createElement("li"); | |
newNode.innerHTML = el; | |
list.appendChild(newNode); | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment